Snippets Collections
// bad
var leds = stage.selectAll('.led').data(data).enter().append('svg:svg').classed('led', true)
    .attr('width', (radius + margin) * 2).append('svg:g')
    .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
    .call(tron.led);

// good
var leds = stage.selectAll('.led')
    .data(data)
  .enter().append('svg:svg')
    .classed('led', true)
    .attr('width', (radius + margin) * 2)
  .append('svg:g')
    .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
    .call(tron.led);
document.querySelectorAll('input, textarea').forEach((el) => {
      // Remove inline oncopy and onpaste handlers
        console.log(el)
      el.oncopy = null;
      el.onpaste = null;

      // Or remove attribute values if needed
      el.removeAttribute('oncopy');
      el.removeAttribute('onpaste');
    });
  
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kiểm tra Thứ hạng Google</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 20px;
            color: #333;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        h1 {
            text-align: center;
            margin-bottom: 20px;
        }
        .form-row {
            margin-bottom: 15px;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"], textarea, select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        button:hover {
            background-color: #45a049;
        }
        .loading {
            display: none;
            margin: 20px 0;
            text-align: center;
        }
        .progress-container {
            width: 100%;
            background-color: #f1f1f1;
            border-radius: 4px;
            margin-top: 10px;
        }
        .progress-bar {
            width: 0%;
            height: 30px;
            background-color: #4CAF50;
            text-align: center;
            line-height: 30px;
            color: white;
            border-radius: 4px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            padding: 8px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f2f2f2;
        }
        tr:hover {
            background-color: #f5f5f5;
        }
        .error {
            color: red;
            margin-top: 10px;
            display: none;
        }
        .success {
            color: green;
            margin-top: 10px;
            display: none;
        }
        .results-actions {
            display: none;
            justify-content: space-between;
            margin-top: 20px;
        }
        .tooltip {
            position: relative;
            display: inline-block;
            cursor: pointer;
        }
        .tooltip .tooltiptext {
            visibility: hidden;
            width: 200px;
            background-color: #555;
            color: #fff;
            text-align: center;
            border-radius: 6px;
            padding: 5px;
            position: absolute;
            z-index: 1;
            bottom: 125%;
            left: 50%;
            margin-left: -100px;
            opacity: 0;
            transition: opacity 0.3s;
        }
        .tooltip:hover .tooltiptext {
            visibility: visible;
            opacity: 1;
        }
        .rank-good {
            background-color: #d4edda;
            color: #155724;
        }
        .rank-medium {
            background-color: #fff3cd;
            color: #856404;
        }
        .rank-bad {
            background-color: #f8d7da;
            color: #721c24;
        }
        .rank-none {
            background-color: #e2e3e5;
            color: #383d41;
        }
        .copy-btn {
            background-color: #007bff;
        }
        .copy-btn:hover {
            background-color: #0069d9;
        }
        .redirect-info {
            font-size: 12px;
            color: #666;
            margin-top: 3px;
        }
        .report-settings {
            background-color: #f9f9f9;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 15px;
        }
        /* Pháo hoa CSS */
        .pyro {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 999;
            pointer-events: none;
            display: none;
        }
        .pyro > .before, .pyro > .after {
            position: absolute;
            width: 5px;
            height: 5px;
            border-radius: 50%;
            box-shadow: 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff, 0 0 #fff;
            animation: 1s bang ease-out infinite backwards, 1s gravity ease-in infinite backwards, 5s position linear infinite backwards;
        }
        .pyro > .after {
            animation-delay: 1.25s, 1.25s, 1.25s;
            animation-duration: 1.25s, 1.25s, 6.25s;
        }
        @keyframes bang {
            to {
                box-shadow: -70px -115.67px #00ff73, -28px -99.67px #a6ff00, 58px -31.67px #0051ff, 13px -7.67px #00ffa2, -19px -33.67px #ff00d0, -37px -23.67px #ff8800, 19px -78.67px #ff002f, 56px -87.67px #00ffcc, -29px -45.67px #ff5e00, 1px -66.67px #ff1500, 42px -123.67px #91ff00, 21px -108.67px #b300ff, -23px -3.67px #ffd000, -65px -55.67px #ff4800, -63px -27.67px #00ff88, 46px 0.33px #0055ff, 75px -86.67px #8cff00, -11px -117.67px #00ff4d, 69px -125.67px #ff0033, 82px -36.67px #00ffbb, -39px -92.67px #00ff73, 49px -124.67px #ff0040, 94px -7.67px #ff6600, 82px 22.33px #ff001a, -14px -98.67px #00ffd5, 27px 7.33px #00ff33, -68px -18.67px #0080ff, 89px -42.67px #ff00fb, -88px -93.67px #ff0004, -62px -59.67px #00ff8c, 52px -21.67px #00ff33, 74px 6.33px #ff00bf, -42px -69.67px #00ff8c, -9px -92.67px #00ff8c, 26px -65.67px #ff0004, 57px -51.67px #a2ff00, 47px -89.67px #0099ff, 74px -123.67px #ff0037, -86px -108.67px #ff4000, 76px -25.67px #0400ff, 77px -57.67px #6aff00, -13px -91.67px #00ff95, 52px -66.67px #91ff00, -42px -103.67px #00ff73, -69px -115.67px #ff0037, 89px -38.67px #ff0088, 90px -113.67px #00ff6a, -63px -42.67px #0066ff, -71px -69.67px #0400ff, 0px -53.67px #002bff, 26px -70.67px #ff006a;
            }
        }
        @keyframes gravity {
            to {
                transform: translateY(200px);
                opacity: 0;
            }
        }
        @keyframes position {
            0%, 19.9% {
                margin-top: 10%;
                margin-left: 40%;
            }
            20%, 39.9% {
                margin-top: 40%;
                margin-left: 30%;
            }
            40%, 59.9% {
                margin-top: 20%;
                margin-left: 70%;
            }
            60%, 79.9% {
                margin-top: 30%;
                margin-left: 20%;
            }
            80%, 99.9% {
                margin-top: 30%;
                margin-left: 80%;
            }
        }
        /* Thông báo chúc mừng */
        .celebration {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: rgba(255, 255, 255, 0.9);
            border: 2px solid #4CAF50;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
            z-index: 1000;
            display: none;
        }
        .celebration h2 {
            color: #4CAF50;
            margin-top: 0;
        }
        .celebration p {
            font-size: 18px;
            margin-bottom: 20px;
        }
        .celebration button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
        }
        .redirect-chain {
            margin-top: 5px;
            font-size: 0.85em;
            color: #666;
        }
        .redirect-chain-item {
            display: block;
            margin-bottom: 3px;
            padding-left: 10px;
            border-left: 2px solid #d35400;
        }
        @media (max-width: 768px) {
            .form-row {
                flex-direction: column;
            }
            .form-row > div {
                width: 100%;
                margin-bottom: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Kiểm tra Thứ hạng Google</h1>
        
        <div class="form-row">
            <div style="flex: 1;">
                <label for="api-key">API Key (Serper.dev):</label>
                <input type="text" id="api-key" placeholder="Nhập API key của bạn" value="85dd0b1bd9a79f29cd3a121a23cc404a759dc00a" hidden>
            </div>
        </div>
        
        <div class="form-row">
            <div style="flex: 1;">
                <label for="domains">Danh sách Domain:</label>
                <textarea id="domains" rows="5" placeholder="Mỗi domain một dòng, ví dụ:&#10;example.com&#10;example.org"></textarea>
            </div>
            <div style="flex: 1;">
                <label for="keywords">Danh sách Từ khóa:</label>
                <textarea id="keywords" rows="5" placeholder="Mỗi từ khóa một dòng, ví dụ:&#10;từ khóa 1&#10;từ khóa 2"></textarea>
            </div>
        </div>
        
        <div class="form-row">
            <div>
                <label for="device">Thiết bị:</label>
                <select id="device">
                    <option value="desktop">Desktop</option>
                    <option value="mobile">Mobile</option>
                </select>
            </div>
            <div>
                <label for="location">Vị trí:</label>
                <select id="location">
                    <option value="">Mặc định (Việt Nam)</option>
                    <option value="1006094">Hà Nội</option>
                    <option value="1006113">TP. Hồ Chí Minh</option>
                    <option value="1006151">Đà Nẵng</option>
                </select>
            </div>
        </div>
        
        <div class="report-settings">
            <label for="report-name">Tên báo cáo:</label>
            <input type="text" id="report-name" placeholder="PIC" value="">
        </div>
        
        <div class="form-row">
            <button onclick="checkRanks()">Kiểm tra Thứ hạng</button>
        </div>
        
        <div id="loading" class="loading">
            <p>Đang kiểm tra thứ hạng... Vui lòng đợi.</p>
            <div class="progress-container">
                <div id="progress" class="progress-bar">0%</div>
            </div>
            <p id="progress-text">0/0</p>
        </div>
        
        <div id="error" class="error"></div>
        <div id="success" class="success"></div>
        
        <div id="results-actions" class="results-actions">
            <button class="copy-btn" onclick="copyAllRanks()">Sao chép dán vào daily ranking</button>
            <button class="copy-btn" onclick="copyFormattedReport()">Sao chép báo cáo Viptalk</button>
        </div>
        
        <div id="results"></div>
    </div>
    
    <!-- Hiệu ứng pháo hoa -->
    <div class="pyro">
        <div class="before"></div>
        <div class="after"></div>
    </div>
    
    <!-- Thông báo chúc mừng -->
    <div id="celebration" class="celebration">
        <h2>🎉 Chúc mừng! 🎉</h2>
        <p id="celebration-message"></p>
        <button onclick="closeCelebration()">Đóng</button>
    </div>
    
    <script>
        // Biến toàn cục để lưu kết quả
        let results = [];
        
        // Kích thước batch mặc định
        const DEFAULT_BATCH_SIZE = 5;
        
        // Đường dẫn API redirect server
        const DEFAULT_REDIRECT_SERVER = "https://red.nguonkienthuc.com";
        
        // Cache kết quả tìm kiếm
        const searchCache = {};
        
        // Hàm làm sạch domain
        function cleanDomain(domain) {
            let cleanedDomain = domain;
            
            // Loại bỏ http://, https://, www. và dấu / ở cuối
            cleanedDomain = cleanedDomain.replace(/^https?:\/\//, '');
            cleanedDomain = cleanedDomain.replace(/^www\./, '');
            cleanedDomain = cleanedDomain.replace(/\/$/, '');
            
            return {
                cleanedDomain: cleanedDomain.toLowerCase(),
                originalDomain: domain
            };
        }
        
        // Hàm chia mảng thành các mảng con có kích thước nhỏ hơn
        function chunkArray(array, size) {
            const chunks = [];
            for (let i = 0; i < array.length; i += size) {
                chunks.push(array.slice(i, i + size));
            }
            return chunks;
        }
        
        // Hàm kiểm tra nhiều chuyển hướng cùng lúc (sử dụng API như phiên bản cũ)
        async function checkMultipleRedirects(domains) {
            try {
                // Đảm bảo mỗi domain có protocol
                const urls = domains.map(domain => {
                    if (!domain.startsWith('http://') && !domain.startsWith('https://')) {
                        return 'https://' + domain;
                    }
                    return domain;
                });
                
                // Gọi API kiểm tra nhiều chuyển hướng
                const response = await fetch(`${DEFAULT_REDIRECT_SERVER}/check-redirects`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ urls, maxRedirects: 10 })
                });
                
                if (!response.ok) {
                    throw new Error(`Lỗi API: ${response.status}`);
                }
                
                return await response.json();
            } catch (error) {
                console.error('Lỗi kiểm tra nhiều chuyển hướng:', error);
                return {};
            }
        }
        
        // Hàm tìm kiếm Google với cache
        async function searchGoogleBatch(queries) {
            const apiKey = document.getElementById('api-key').value.trim();
            if (!apiKey) {
                throw new Error('API key không được để trống');
            }
            
            const device = document.getElementById('device').value;
            const location = document.getElementById('location').value;
            
            // Gom nhóm các từ khóa giống nhau để tránh tìm kiếm trùng lặp
            const uniqueQueries = [];
            const queryMap = new Map(); // Ánh xạ từ từ khóa đến chỉ mục trong uniqueQueries
            
            queries.forEach(query => {
                const cacheKey = `${query.keyword}_${device}_${location || 'default'}`;
                
                // Nếu từ khóa đã có trong cache, bỏ qua
                if (searchCache[cacheKey]) {
                    return;
                }
                
                // Nếu từ khóa chưa được thêm vào uniqueQueries, thêm vào
                if (!queryMap.has(query.keyword)) {
                    queryMap.set(query.keyword, uniqueQueries.length);
                    uniqueQueries.push({
                        keyword: query.keyword,
                        cacheKey: cacheKey
                    });
                }
            });
            
            // Nếu có từ khóa cần tìm kiếm
            if (uniqueQueries.length > 0) {
                const searchQueries = uniqueQueries.map(query => {
                    const queryParams = {
                        q: query.keyword,
                        device: device,
                        gl: "vn",
                        hl: "vi",
                        num: 100
                    };
                    
                    if (location) {
                        queryParams.location = location;
                    }
                    
                    return queryParams;
                });
                
                const myHeaders = new Headers();
                myHeaders.append("X-API-KEY", apiKey);
                myHeaders.append("Content-Type", "application/json");
                
                const requestOptions = {
                    method: "POST",
                    headers: myHeaders,
                    body: JSON.stringify(searchQueries),
                    redirect: "follow"
                };
                
                try {
                    const response = await fetch("https://google.serper.dev/search", requestOptions);
                    
                    if (!response.ok) {
                        const errorText = await response.text();
                        throw new Error(`Lỗi API: ${response.status} - ${errorText}`);
                    }
                    
                    const data = await response.json();
                    
                    // Lưu kết quả vào cache
                    uniqueQueries.forEach((query, index) => {
                        searchCache[query.cacheKey] = data[index];
                    });
                } catch (error) {
                    console.error("Lỗi khi tìm kiếm:", error);
                    throw error;
                }
            }
            
            // Trả về kết quả từ cache cho tất cả queries
            return queries.map(query => {
                const cacheKey = `${query.keyword}_${device}_${location || 'default'}`;
                return searchCache[cacheKey];
            });
        }
        
        // Hàm hiển thị pháo hoa
        function showFireworks() {
            const pyro = document.querySelector('.pyro');
            pyro.style.display = 'block';
            
            // Ẩn pháo hoa sau 3 giây
            setTimeout(() => {
                pyro.style.display = 'none';
            }, 3000);
        }
        
        // Hàm hiển thị thông báo chúc mừng
        function showCelebration(message) {
            const celebration = document.getElementById('celebration');
            const celebrationMessage = document.getElementById('celebration-message');
            
            celebrationMessage.textContent = message;
            celebration.style.display = 'block';
            
            // Hiển thị pháo hoa
            showFireworks();
        }
        
        // Hàm đóng thông báo chúc mừng
        function closeCelebration() {
            document.getElementById('celebration').style.display = 'none';
        }
        
        // Hàm kiểm tra thứ hạng tối ưu
        async function checkRanks() {
            const domainsText = document.getElementById('domains').value.trim();
            const keywordsText = document.getElementById('keywords').value.trim();
            
            if (!domainsText) {
                showError('Vui lòng nhập danh sách domain');
                return;
            }
            
            if (!keywordsText) {
                showError('Vui lòng nhập danh sách từ khóa');
                return;
            }
            
            // Parse danh sách domain và từ khóa
            const domains = domainsText.split('\n')
                .map(domain => domain.trim())
                .filter(domain => domain.length > 0);
                
            const keywords = keywordsText.split('\n')
                .map(keyword => keyword.trim())
                .filter(keyword => keyword.length > 0);
            
            if (domains.length === 0) {
                showError('Không có domain hợp lệ');
                return;
            }
            
            if (keywords.length === 0) {
                showError('Không có từ khóa hợp lệ');
                return;
            }
            
            // Hiển thị loading
            document.getElementById('loading').style.display = 'block';
            document.getElementById('error').style.display = 'none';
            document.getElementById('success').style.display = 'none';
            document.getElementById('results').innerHTML = '';
            document.getElementById('results-actions').style.display = 'none';
            
            // Reset kết quả
            results = [];
            
            // Kiểm tra chuyển hướng cho tất cả domain một lần
            let redirectResults = {};
            try {
                redirectResults = await checkMultipleRedirects(domains);
            } catch (error) {
                console.error('Lỗi khi kiểm tra chuyển hướng:', error);
            }
            
            // Tạo danh sách các domain đã làm sạch để kiểm tra
            const domainInfo = domains.map(domain => {
                const { cleanedDomain } = cleanDomain(domain);
                let domainToCheck = domain;
                if (!domainToCheck.startsWith('http://') && !domainToCheck.startsWith('https://')) {
                    domainToCheck = 'https://' + domainToCheck;
                }
                
                // Thêm thông tin chuyển hướng
                const redirectInfo = redirectResults[domainToCheck] || {};
                
                return {
                    domain: domain,
                    cleanedDomain: cleanedDomain,
                    redirected: redirectInfo.hasRedirect || false,
                    redirectChain: redirectInfo.redirectChain || null,
                    finalUrl: redirectInfo.finalUrl || null,
                    redirectCount: redirectInfo.redirectCount || 0
                };
            });
            
            // PHƯƠNG PHÁP TỐI ƯU: Tạo danh sách các từ khóa duy nhất để tìm kiếm
            const uniqueKeywords = [...new Set(keywords)];
            
            // Tạo ánh xạ từ từ khóa đến các domain cần kiểm tra
            const keywordToDomains = new Map();
            
            // Nếu số lượng domain và từ khóa bằng nhau, giả định mỗi domain đi với một từ khóa
            if (domains.length === keywords.length) {
                for (let i = 0; i < domains.length; i++) {
                    if (!keywordToDomains.has(keywords[i])) {
                        keywordToDomains.set(keywords[i], []);
                    }
                    keywordToDomains.get(keywords[i]).push(domainInfo[i]);
                }
            } else {
                // Nếu số lượng không bằng nhau, kiểm tra mọi domain với mọi từ khóa
                uniqueKeywords.forEach(keyword => {
                    keywordToDomains.set(keyword, domainInfo);
                });
            }
            
            // Tạo danh sách các query để tìm kiếm
            const queries = uniqueKeywords.map(keyword => ({
                keyword: keyword
            }));
            
            // Thực hiện tìm kiếm theo batch
            const batchSize = DEFAULT_BATCH_SIZE;
            const batches = chunkArray(queries, batchSize);
            
            let completed = 0;
            const totalKeywords = uniqueKeywords.length;
            
            try {
                for (const batch of batches) {
                    // Cập nhật tiến trình
                    document.getElementById('progress-text').textContent = `${completed}/${totalKeywords}`;
                    const percent = Math.round((completed / totalKeywords) * 100);
                    document.getElementById('progress').style.width = `${percent}%`;
                    document.getElementById('progress').textContent = `${percent}%`;
                    
                    // Tìm kiếm batch
                    const searchResults = await searchGoogleBatch(batch);
                    
                    // Xử lý kết quả tìm kiếm
                    for (let i = 0; i < batch.length; i++) {
                        const keyword = batch[i].keyword;
                        const searchResult = searchResults[i];
                        
                        // Lấy danh sách domain cần kiểm tra cho từ khóa này
                        const domainsToCheck = keywordToDomains.get(keyword) || [];
                        
                        // Kiểm tra từng domain trong kết quả tìm kiếm
                        for (const domainData of domainsToCheck) {
                            let rank = null;
                            let matchedUrl = null;
                            
                            // Tạo danh sách các domain cần kiểm tra (bao gồm cả domain chuyển hướng)
                            let domainVariants = [domainData.cleanedDomain];
                            
                            // Thêm domain từ chuỗi chuyển hướng
                            if (domainData.redirectChain && domainData.redirectChain.length > 1) {
                                for (let j = 1; j < domainData.redirectChain.length; j++) {
                                    try {
                                        const redirectUrl = new URL(domainData.redirectChain[j].url);
                                        const redirectDomain = redirectUrl.hostname.replace(/^www\./, '');
                                        domainVariants.push(redirectDomain.toLowerCase());
                                    } catch (e) {
                                        console.error("Lỗi xử lý URL chuyển hướng:", e);
                                    }
                                }
                            }
                            
                            // Tìm kiếm trong kết quả Google
                            if (searchResult && searchResult.organic) {
                                for (let j = 0; j < searchResult.organic.length; j++) {
                                    const result = searchResult.organic[j];
                                    try {
                                        const resultUrl = new URL(result.link);
                                        const resultDomain = resultUrl.hostname.replace(/^www\./, '').toLowerCase();
                                        
                                        // Kiểm tra xem domain kết quả có khớp với domain cần kiểm tra không
                                        if (domainVariants.some(domain => resultDomain.includes(domain))) {
                                            rank = j + 1;
                                            matchedUrl = result.link;
                                            break;
                                        }
                                    } catch (e) {
                                        console.error("Lỗi xử lý URL kết quả:", e);
                                    }
                                }
                            }
                            
                            // Thêm kết quả
                            results.push({
                                domain: domainData.domain,
                                cleanedDomain: domainData.cleanedDomain,
                                keyword: keyword,
                                rank: rank,
                                matchedUrl: matchedUrl,
                                redirected: domainData.redirected,
                                redirectChain: domainData.redirectChain,
                                finalUrl: domainData.finalUrl,
                                redirectCount: domainData.redirectCount,
                                date: new Date().toLocaleDateString('vi-VN'),
                                location: document.getElementById('location').options[document.getElementById('location').selectedIndex].text
                            });
                        }
                    }
                    
                    // Hiển thị kết quả sau mỗi batch
                    displayResults();
                    
                    // Cập nhật số lượng hoàn thành
                    completed += batch.length;
                }
                
                // Cập nhật tiến trình thành 100%
                document.getElementById('progress-text').textContent = `${totalKeywords}/${totalKeywords}`;
                document.getElementById('progress').style.width = '100%';
                document.getElementById('progress').textContent = '100%';
                
                // Đếm số từ khóa trong top 10
                const top10Keywords = results.filter(result => result.rank !== null && result.rank <= 6);
                const top10Count = top10Keywords.length;
                
                // Hiển thị thông báo chúc mừng nếu có từ khóa trong top 10
                if (top10Count > 0) {
                    // Tạo thông báo dựa trên số lượng từ khóa trong top 10
                    const message = `Bạn có ${top10Count} từ khóa nằm trong top 6 Google!`;
                    
                    // Hiển thị thông báo chúc mừng
                    showCelebration(message);
                    
                    // Bắn pháo hoa nhiều lần tương ứng với số từ khóa top 10
                    for (let i = 0; i < top10Count; i++) {
                        setTimeout(() => {
                            showFireworks();
                        }, i * 3000); // Mỗi hiệu ứng pháo hoa cách nhau 3 giây
                    }
                }
                
                showSuccess(`Đã kiểm tra thành công ${results.length} kết quả`);
            } catch (error) {
                showError(`Lỗi: ${error.message}`);
            } finally {
                // Ẩn loading
                document.getElementById('loading').style.display = 'none';
                
                // Hiển thị nút sao chép nếu có kết quả
                if (results.length > 0) {
                    document.getElementById('results-actions').style.display = 'flex';
                }
            }
        }
        
        // Hàm hiển thị kết quả
        function displayResults() {
            const resultsDiv = document.getElementById('results');
            
            // Tạo bảng kết quả
            let tableHtml = `
                <table>
                    <thead>
                        <tr>
                            <th>STT</th>
                            <th>Domain</th>
                            <th>Từ khóa</th>
                            <th>Thứ hạng</th>
                            <th>URL khớp</th>
                            <th>Ngày kiểm tra</th>
                            <th>Vị trí</th>
                        </tr>
                    </thead>
                    <tbody>
            `;
            
            // Thêm các dòng kết quả
            results.forEach((result, index) => {
                // Xác định class cho thứ hạng
                let rankClass = 'rank-none';
                let rankDisplay = 'Không tìm thấy';
                
                if (result.rank !== null) {
                    rankDisplay = result.rank;
                    if (result.rank <= 10) {
                        rankClass = 'rank-good';
                    } else if (result.rank <= 20) {
                        rankClass = 'rank-medium';
                    } else {
                        rankClass = 'rank-bad';
                    }
                }
                
                // Tạo thông tin chuyển hướng
                let redirectInfo = '';
                if (result.redirected) {
                    // Tạo tooltip với thông tin chi tiết về chuỗi chuyển hướng
                    let redirectChainHtml = '';
                    if (result.redirectChain && result.redirectChain.length > 0) {
                        redirectChainHtml = '<div class="redirect-chain">';
                        result.redirectChain.forEach((redirect, idx) => {
                            const statusColor = redirect.status === 301 ? '#e74c3c' : '#3498db';
                            redirectChainHtml += `
                                <span class="redirect-chain-item" style="color: ${statusColor}">
                                    ${idx + 1}. ${redirect.url} (${redirect.status})
                                </span>
                            `;
                        });
                        redirectChainHtml += '</div>';
                    }
                    
                    redirectInfo = `
                        <div class="redirect-info">
                            <span class="tooltip">
                                Đã chuyển hướng (${result.redirectCount})
                                <span class="tooltiptext">
                                    ${redirectChainHtml || 'Không có thông tin chi tiết'}
                                </span>
                            </span>
                        </div>
                    `;
                }
                
                // Thêm dòng vào bảng
                tableHtml += `
                    <tr>
                        <td>${index + 1}</td>
                        <td>
                            ${result.domain}
                            ${redirectInfo}
                        </td>
                        <td>${result.keyword}</td>
                        <td class="${rankClass}">${rankDisplay}</td>
                        <td>${result.matchedUrl ? `<a href="${result.matchedUrl}" target="_blank">${result.matchedUrl}</a>` : 'N/A'}</td>
                        <td>${result.date}</td>
                        <td>${result.location}</td>
                    </tr>
                `;
            });
            
            // Đóng bảng
            tableHtml += `
                    </tbody>
                </table>
            `;
            
            // Hiển thị bảng
            resultsDiv.innerHTML = tableHtml;
        }
        
        // Hàm sao chép tất cả thứ hạng thành một cột
        function copyAllRanks() {
            // Tạo một chuỗi chứa tất cả thứ hạng, mỗi thứ hạng trên một dòng
            const ranksList = results.map(result => result.rank ? result.rank.toString() : 'N/A').join('\n');
            
            // Sao chép vào clipboard
            navigator.clipboard.writeText(ranksList)
                .then(() => {
                    showSuccess('Đã sao chép tất cả thứ hạng thành công!');
                })
                .catch(err => {
                    console.error('Lỗi khi sao chép: ', err);
                    showError('Không thể sao chép. Vui lòng thử lại.');
                });
        }

        // Sao chép báo cáo theo định dạng
        // function copyFormattedReport() {
        //     // Lấy ngày hiện tại
        //     const today = new Date();
        //     const day = today.getDate();
        //     const month = today.getMonth() + 1;
            
        //     // Lấy tên báo cáo từ input
        //     const reportName = document.getElementById('report-name').value.trim();
            
        //     // Lấy thông tin khu vực
        //     const locationElement = document.getElementById('location');
        //     const locationText = locationElement.options[locationElement.selectedIndex].text;
        //     const locationInfo = locationElement.value ? ` - ${locationText}` : '';
            
        //     // Bắt đầu với tiêu đề báo cáo
        //     let report = `Ngày ${day}/${month} - [${reportName}]\n============\n\n`;
            
        //     // Nhóm kết quả theo domain (sau khi đã làm sạch)
        //     const domainGroups = {};
            
        //     results.forEach(result => {
        //         const domain = result.cleanedDomain;
        //         if (!domainGroups[domain]) {
        //             domainGroups[domain] = {
        //                 originalDomain: result.domain,
        //                 cleanedDomain: domain,
        //                 keywords: [],
        //                 ranks: [],
        //                 redirected: result.redirected || false,
        //                 finalUrl: result.finalUrl || null,
        //                 redirectChain: result.redirectChain || null,
        //                 has301: false
        //             };
        //         }
                
        //         // Kiểm tra xem có chuyển hướng 301 không
        //         if (result.redirectChain && result.redirectChain.length > 0) {
        //             for (let i = 0; i < result.redirectChain.length; i++) {
        //                 if (result.redirectChain[i].status === 301) {
        //                     domainGroups[domain].has301 = true;
        //                     break;
        //                 }
        //             }
        //         }
                
        //         domainGroups[domain].keywords.push(result.keyword);
        //         domainGroups[domain].ranks.push(result.rank);
        //     });
            
        //     // Tạo báo cáo cho từng domain
        //     for (const domain in domainGroups) {
        //         const group = domainGroups[domain];
                
        //         // Thêm domain vào báo cáo (màu xanh)
        //         // Nếu có chuyển hướng 301, thêm đánh dấu [301]
        //         const redirectMark = group.has301 ? ' [301]' : '';
        //         report += `${domain}${redirectMark}\n`;
                
        //         // Nếu có chuyển hướng, hiển thị URL cuối cùng
        //         if (group.redirected && group.finalUrl) {
        //             // Lấy hostname từ finalUrl
        //             try {
        //                 const finalUrlObj = new URL(group.finalUrl);
        //                 const finalDomain = finalUrlObj.hostname;
        //                 report += `→ ${finalDomain}\n`;
        //             } catch (e) {
        //                 // Nếu không parse được URL, hiển thị toàn bộ finalUrl
        //                 report += `→ ${group.finalUrl}\n`;
        //             }
        //         }
                
        //         // Thêm từ khóa và thứ hạng
        //         for (let i = 0; i < group.keywords.length; i++) {
        //             const keyword = group.keywords[i];
        //             const rank = group.ranks[i] || 'N/A';
        //             report += `${keyword} - top ${rank}\n`;
        //         }
                
        //         report += '\n';
        //     }
            
        //     // Sao chép vào clipboard
        //     navigator.clipboard.writeText(report)
        //         .then(() => {
        //             showSuccess('Đã sao chép báo cáo định dạng thành công!');
        //         })
        //         .catch(err => {
        //             console.error('Lỗi khi sao chép: ', err);
        //             showError('Không thể sao chép. Vui lòng thử lại.');
        //         });
        // }
        // Sao chép báo cáo theo định dạng
function copyFormattedReport() {
    // Lấy ngày hiện tại
    const today = new Date();
    const day = today.getDate();
    const month = today.getMonth() + 1;
    
    // Lấy tên báo cáo từ input
    const reportName = document.getElementById('report-name').value.trim();
    
    // Lấy thông tin khu vực
    const locationElement = document.getElementById('location');
    const locationText = locationElement.options[locationElement.selectedIndex].text;
    const locationInfo = locationElement.value ? ` - ${locationText}` : '';
    
    // Bắt đầu với tiêu đề báo cáo
    let report = `Ngày ${day}/${month} - [${reportName}]\n============\n\n`;
    
    // Lấy danh sách domain và từ khóa ban đầu để giữ nguyên thứ tự
    const domainsText = document.getElementById('domains').value.trim();
    const keywordsText = document.getElementById('keywords').value.trim();
    
    const originalDomains = domainsText.split('\n')
        .map(domain => domain.trim())
        .filter(domain => domain.length > 0);
        
    const originalKeywords = keywordsText.split('\n')
        .map(keyword => keyword.trim())
        .filter(keyword => keyword.length > 0);
    
    // Tạo Map để lưu trữ thông tin domain đã xử lý
    const processedDomains = new Map();
    
    // Nếu số lượng domain và từ khóa bằng nhau, giả định mỗi domain đi với một từ khóa
    if (originalDomains.length === originalKeywords.length) {
        // Lặp qua danh sách domain theo thứ tự ban đầu
        for (let i = 0; i < originalDomains.length; i++) {
            const domain = originalDomains[i];
            const keyword = originalKeywords[i];
            
            // Tìm kết quả tương ứng
            const result = results.find(r => 
                r.domain === domain && r.keyword === keyword);
            
            if (result) {
                const cleanedDomain = result.cleanedDomain;
                
                // Kiểm tra xem domain đã được xử lý chưa
                if (!processedDomains.has(cleanedDomain)) {
                    processedDomains.set(cleanedDomain, {
                        originalDomain: domain,
                        keywords: [],
                        ranks: [],
                        redirected: result.redirected || false,
                        finalUrl: result.finalUrl || null,
                        redirectChain: result.redirectChain || null,
                        has301: false
                    });
                    
                    // Kiểm tra xem có chuyển hướng 301 không
                    if (result.redirectChain && result.redirectChain.length > 0) {
                        for (let j = 0; j < result.redirectChain.length; j++) {
                            if (result.redirectChain[j].status === 301) {
                                processedDomains.get(cleanedDomain).has301 = true;
                                break;
                            }
                        }
                    }
                }
                
                // Thêm từ khóa và thứ hạng vào domain
                const domainData = processedDomains.get(cleanedDomain);
                domainData.keywords.push(keyword);
                domainData.ranks.push(result.rank);
            }
        }
        
        // Tạo báo cáo theo thứ tự domain ban đầu
        const addedDomains = new Set();
        
        for (let i = 0; i < originalDomains.length; i++) {
            const domain = originalDomains[i];
            const { cleanedDomain } = cleanDomain(domain);
            
            // Nếu domain này đã được thêm vào báo cáo, bỏ qua
            if (addedDomains.has(cleanedDomain)) {
                continue;
            }
            
            // Đánh dấu domain đã được thêm vào báo cáo
            addedDomains.add(cleanedDomain);
            
            // Lấy thông tin domain
            const domainData = processedDomains.get(cleanedDomain);
            
            if (domainData) {
                // Thêm domain vào báo cáo
                const redirectMark = domainData.has301 ? ' [301]' : '';
                report += `${cleanedDomain}${redirectMark}\n`;
                
                // Nếu có chuyển hướng, hiển thị URL cuối cùng
                if (domainData.redirected && domainData.finalUrl) {
                    try {
                        const finalUrlObj = new URL(domainData.finalUrl);
                        const finalDomain = finalUrlObj.hostname;
                        report += `→ ${finalDomain}\n`;
                    } catch (e) {
                        report += `→ ${domainData.finalUrl}\n`;
                    }
                }
                
                // Thêm từ khóa và thứ hạng theo thứ tự
                for (let j = 0; j < domainData.keywords.length; j++) {
                    const keyword = domainData.keywords[j];
                    const rank = domainData.ranks[j] || 'N/A';
                    report += `${keyword} - top ${rank}\n`;
                }
                
                report += '\n';
            }
        }
    } else {
        // Nếu số lượng domain và từ khóa không bằng nhau
        // Nhóm kết quả theo domain (giữ nguyên thứ tự xuất hiện đầu tiên)
        const domainOrder = [];
        const domainGroups = {};
        
        results.forEach(result => {
            const domain = result.cleanedDomain;
            
            if (!domainGroups[domain]) {
                domainOrder.push(domain);
                domainGroups[domain] = {
                    originalDomain: result.domain,
                    cleanedDomain: domain,
                    keywords: [],
                    ranks: [],
                    redirected: result.redirected || false,
                    finalUrl: result.finalUrl || null,
                    redirectChain: result.redirectChain || null,
                    has301: false
                };
            }
            
            // Kiểm tra xem có chuyển hướng 301 không
            if (result.redirectChain && result.redirectChain.length > 0) {
                for (let i = 0; i < result.redirectChain.length; i++) {
                    if (result.redirectChain[i].status === 301) {
                        domainGroups[domain].has301 = true;
                        break;
                    }
                }
            }
            
            domainGroups[domain].keywords.push(result.keyword);
            domainGroups[domain].ranks.push(result.rank);
        });
        
        // Tạo báo cáo theo thứ tự domain đã lưu
        for (const domain of domainOrder) {
            const group = domainGroups[domain];
            
            // Thêm domain vào báo cáo
            const redirectMark = group.has301 ? ' [301]' : '';
            report += `${domain}${redirectMark}\n`;
            
            // Nếu có chuyển hướng, hiển thị URL cuối cùng
            if (group.redirected && group.finalUrl) {
                try {
                    const finalUrlObj = new URL(group.finalUrl);
                    const finalDomain = finalUrlObj.hostname;
                    report += `→ ${finalDomain}\n`;
                } catch (e) {
                    report += `→ ${group.finalUrl}\n`;
                }
            }
            
            // Thêm từ khóa và thứ hạng
            for (let i = 0; i < group.keywords.length; i++) {
                const keyword = group.keywords[i];
                const rank = group.ranks[i] || 'N/A';
                report += `${keyword} - top ${rank}\n`;
            }
            
            report += '\n';
        }
    }
    
    // Sao chép vào clipboard
    navigator.clipboard.writeText(report)
        .then(() => {
            showSuccess('Đã sao chép báo cáo định dạng thành công!');
        })
        .catch(err => {
            console.error('Lỗi khi sao chép: ', err);
            showError('Không thể sao chép. Vui lòng thử lại.');
        });
}

        // Hàm hiển thị lỗi
        function showError(message) {
            const errorDiv = document.getElementById('error');
            errorDiv.textContent = message;
            errorDiv.style.display = 'block';
            document.getElementById('success').style.display = 'none';
        }
        
        // Hàm hiển thị thông báo thành công
        function showSuccess(message) {
            const successDiv = document.getElementById('success');
            successDiv.textContent = message;
            successDiv.style.display = 'block';
            document.getElementById('error').style.display = 'none';
        }
    </script>
</body>
</html>
Entrepreneurs choose crypto exchange scripts because they offer a fast, cost-effective, and customizable way to launch a cryptocurrency trading platform. These ready-made solutions come with essential features like trading engines, wallet integration, security modules, and admin dashboards—helping startups avoid the complexity of building from scratch. With reduced development time, lower investment costs, and scalable architecture, crypto exchange scripts are the ideal choice for entrepreneurs looking to enter the crypto market quickly and efficiently.

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.0/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.0/ScrollTrigger.min.js"></script>

<script>
const slides = document.querySelectorAll('.slide');
let isMobile = window.innerWidth <= 768; // Assuming mobile width is 768px or less

slides.forEach((slide, i) => {
    let angle = isMobile ? i * 10 : (i * 10) - 10;
    gsap.to(slide, {
        rotation: angle,
        transformOrigin: "0% 2300px",
    });
});

let speed = isMobile ? 30 : 30; // Faster speed on mobile
ScrollTrigger.create({
    trigger: '.scroller',
    start: "top top",
    end: "bottom bottom",
    //markers: true,
    onUpdate: (self) => {
        gsap.to(slides, {
            rotation: (i) => {
                let baseAngle = isMobile ? i * 10 : (i * 10) - 10;
                return baseAngle - self.progress * speed;
            }
        });
    }
});
</script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>

var $ = jQuery

$(document).ready(function(){

$('.reboot-slider').each(function(){

var $this = $(this),
    currentSlide = 0,
    previousSlide = 0,
    slideNumber = $this.find('.reboot-side-slider .swiper-slide:not(.swiper-slide-duplicate)').length,
    barHTML = '',
    forward,
    textContainer = $this.find('.reboot-changing-widget')

for(var i=0; i<slideNumber;i++){

    barHTML += `<span class="dot"><span class="dot-number">${i+1}</span></span>`
}

$this.find('.reboot-bar .dot').remove()
$this.find('.reboot-bar').append(barHTML)
$this.find('.reboot-bar .dot').eq(0).addClass('active')

textContainer.each(function(){
    var texts = $(this).find('.elementor-widget').eq(0)
    texts.addClass('currentUp')
    $(this).css('--h', texts.height()+'px')
})

setTimeout(function(){
    $this.addClass('loaded')
    if($this.find('.reboot-side-slider .swiper-container-initialized, .reboot-side-slider .swiper-initialized').length){
        $this.find('.reboot-side-slider').addClass('loaded')
    }

    var init = setInterval(function(){
        if($this.find('.reboot-side-slider .swiper-container-initialized, .reboot-side-slider .swiper-initialized').length){

            $this.find('.reboot-side-slider').addClass('loaded')
            clearInterval(init)
        }
    },50)
}, 500)

var bgs = JSON.parse($this.attr('data-settings')).background_slideshow_gallery,
    bgHTML = '<div class="reboot-slider-background">'

if(bgs){
    bgs.forEach(function(background){
        bgHTML += `<img decoding="async" src="${background.url}"/>`
    })
}
bgHTML += '</div>'

$this.find('.reboot-slider-background').remove()
$this.prepend(bgHTML)

var backgrounds = $this.find('.reboot-slider-background img')

backgrounds.eq(0).addClass('currentForward')

setInterval(function(){
    currentSlide = $this.find('.reboot-side-slider .swiper-slide-active').attr('data-swiper-slide-index')
    if(previousSlide != currentSlide) {

        if( previousSlide < currentSlide ){
            forward = true
        }
        if( previousSlide > currentSlide ){
            forward = false
        }
        if( previousSlide == slideNumber - 1 && currentSlide == 0 ){
            forward = true
        }
        if( previousSlide == 0 && currentSlide == slideNumber - 1 ){
            forward = false
        }
        textContainer.each(function(){
            var texts = $(this).find('.elementor-widget')

            $(this).css('--h', texts.eq(currentSlide).height()+'px')

            texts.removeClass('prev next currentUp currentDown')
            backgrounds.removeClass('prev currentBackward currentForward')

            backgrounds.eq(previousSlide).addClass('prev')

            if(forward) {
                texts.eq(previousSlide).addClass('prev')
                texts.eq(currentSlide).addClass('currentUp')

                backgrounds.eq(currentSlide).addClass('currentForward')

            }else{
                texts.eq(previousSlide).addClass('next')
                texts.eq(currentSlide).addClass('currentDown')

                backgrounds.eq(currentSlide).addClass('currentBackward')
            }
        })

        $this.find('.reboot-bar .dot').removeClass('active')
        $this.find('.reboot-bar .dot').eq(currentSlide).addClass('active')
    }
    previousSlide = currentSlide
}, 500)

$this.find('.reboot-bar .dot').on('click', function(){

    var index = $(this).index()

    $this.find('.reboot-side-slider .swiper-pagination-bullet').eq(index).trigger('click')
    $this.find('.reboot-side-slider .swiper-container').trigger('mouseleave')

})
$this.find('.reboot-slider-left').on('click', function(){

    $this.find('.reboot-side-slider .elementor-swiper-button-prev').trigger('click')
    $this.find('.reboot-side-slider .elementor-swiper').trigger('mouseleave')
})
$this.find('.reboot-slider-right').on('click', function(){

    $this.find('.reboot-side-slider .elementor-swiper-button-next').trigger('click')
    $this.find('.reboot-side-slider .elementor-swiper').trigger('mouseleave')
})
$this.find('.reboot-slider-left a, .reboot-slider-right a').on('click', function(e){

    e.preventDefault()
})

})
})

$(window).on('resize', function(){


$('.reboot-slider').each(function(){

    var textContainer = $(this).find('.reboot-changing-widget')

    textContainer.each(function(){
        var texts = $(this).find('.elementor-widget.currentUp, .elementor-widget.currentDown')

        $(this).css('--h', texts.height()+'px')
    })
})
})

</script>
selector{
    --radius: 8px;
    --height: 320px;
    --active-height: 410px;
    --overlay: 0.75;
}
selector{
    opacity: 0;
    transform: translateX(100px);
    transition: all 0.8s ease-in-out;
}
selector.loaded{
    opacity: 1;
    transform: translateX(0);
}

selector .swiper-wrapper{
    height: var(--active-height);
    align-items: center;
}
selector:not(.loaded) .swiper-wrapper{
    transition-duration: 0s !important;
}
selector .swiper-slide{
    display: flex;
    align-items: flex-end;
    border-radius: var(--radius);
    height: var(--height);
    box-shadow: 0 0 50px rgba(0,0,0,0.15);
}
selector.loaded .swiper-slide{
    transition: all 0.3s ease-in-out 0.2s;
}
selector .swiper-slide.swiper-slide-active{
    height: var(--active-height);
}
selector .swiper-slide:before{
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    background: rgb(0,0,0);
    background: linear-gradient(20deg, rgba(0,0,0,var(--overlay)) 0%, rgba(0,0,0,0) 100%);
    height: 100%;
    width: 100%;
    z-index: 1;
}
selector .elementor-testimonial__footer{
    display: block;
}
selector img{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border-radius: var(--radius);
}
selector .elementor-testimonial__cite{
    z-index: 2;
    position: relative;
}
selector .elementor-testimonial__name{
    margin-bottom: 5px;
}
selector .swiper-pagination,
selector .elementor-swiper-button{
    display: none;
}
selector .swiper-container{
    overflow: hidden;
    margin-left: auto;
    margin-right: auto;
}

@media (max-width: 1024px){
selector{
    --height: 180px;
    --active-height: 250px;
}
}
@media (max-width: 767px){
selector{
    --height: 80px;
    --active-height: 105px;
    width: 100% !important;
    max-width: var(--container-widget-width, 300px) !important;
}
selector .elementor-testimonial__cite{
    opacity: 0;
}
}
selector{
    --speed: 0.5s;
    --gap: 40px;
}
selector{
    transition: all 0.3s ease-in-out;
    height: var(--h);
    --height: calc(var(--h) + var(--gap));
    overflow: hidden !important;
}
selector .elementor-widget{
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}
selector .elementor-widget .elementor-button{
    transform: translateY(calc(-10 * var(--height)));
    transition: none !important;
}
selector .elementor-widget.prev .elementor-button{
    animation: prev var(--speed) ease-in-out;
    transform: translateY(calc(-1 * var(--height)));
}
selector .elementor-widget.next .elementor-button{
    animation: next var(--speed) ease-in-out;
    transform: translateY(var(--height));
}
selector .elementor-widget.currentUp,
selector .elementor-widget.currentDown{
    z-index: 1;
}
selector .elementor-widget.currentUp .elementor-button{
    animation: currentUp var(--speed) ease-in-out;
    transform: translateY(0);
}
selector .elementor-widget.currentDown .elementor-button{
    animation: currentDown var(--speed) ease-in-out;
    transform: translateY(0);
}

@keyframes prev {
  0%   {transform: translateY(0);}
  100%   {transform: translateY(calc(-1 * var(--height)));}
}

@keyframes next {
  0%   {transform: translateY(0);}
  100%   {transform: translateY(var(--height));}
}

@keyframes currentUp {
  0%   {transform: translateY(var(--height));}
  100%   {transform: translateY(0);}
}

@keyframes currentDown {
  0%   {transform: translateY(calc(-1 * var(--height)));}
  100%   {transform: translateY(0);}
}
selector{
    --speed: 0.5s;
    --gap: 40px;
}
selector{
    transition: all 0.3s ease-in-out;
    height: var(--h);
    --height: calc(var(--h) + var(--gap));
    overflow: hidden !important;
}
selector .elementor-widget{
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}
selector .elementor-widget p{
    transform: translateY(calc(-10 * var(--height)));
    transition: none !important;
}
selector .elementor-widget.prev p{
    animation: prev var(--speed) ease-in-out;
    transform: translateY(calc(-1 * var(--height)));
}
selector .elementor-widget.next p{
    animation: next var(--speed) ease-in-out;
    transform: translateY(var(--height));
}
selector .elementor-widget.currentUp,
selector .elementor-widget.currentDown{
    z-index: 1;
}
selector .elementor-widget.currentUp p{
    animation: currentUp var(--speed) ease-in-out;
    transform: translateY(0);
}
selector .elementor-widget.currentDown p{
    animation: currentDown var(--speed) ease-in-out;
    transform: translateY(0);
}

@keyframes prev {
  0%   {transform: translateY(0);}
  100%   {transform: translateY(calc(-1 * var(--height)));}
}

@keyframes next {
  0%   {transform: translateY(0);}
  100%   {transform: translateY(var(--height));}
}

@keyframes currentUp {
  0%   {transform: translateY(var(--height));}
  100%   {transform: translateY(0);}
}

@keyframes currentDown {
  0%   {transform: translateY(calc(-1 * var(--height)));}
  100%   {transform: translateY(0);}
}
selector{
    --speed: 0.8s;
    --gap: 40px;
}
selector{
    transition: all 0.3s ease-in-out;
    height: var(--h);
    --height: calc(var(--h) + var(--gap));
    overflow: hidden !important;
}
selector .elementor-widget{
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}
selector .elementor-widget .elementor-heading-title{
    transform: translateY(calc(-10 * var(--height)));
    transition: none !important;
}
selector .elementor-widget.prev .elementor-heading-title{
    animation: prev var(--speed) ease-in-out;
    transform: translateY(calc(-1 * var(--height)));
}
selector .elementor-widget.next .elementor-heading-title{
    animation: next var(--speed) ease-in-out;
    transform: translateY(var(--height));
}
selector .elementor-widget.currentUp,
selector .elementor-widget.currentDown{
    z-index: 1;
}
selector .elementor-widget.currentUp .elementor-heading-title{
    animation: currentUp var(--speed) ease-in-out;
    transform: translateY(0);
}
selector .elementor-widget.currentDown .elementor-heading-title{
    animation: currentDown var(--speed) ease-in-out;
    transform: translateY(0);
}

@keyframes prev {
  0%   {transform: translateY(0);}
  100%   {transform: translateY(calc(-1 * var(--height)));}
}

@keyframes next {
  0%   {transform: translateY(0);}
  100%   {transform: translateY(var(--height));}
}

@keyframes currentUp {
  0%   {transform: translateY(var(--height));}
  100%   {transform: translateY(0);}
}

@keyframes currentDown {
  0%   {transform: translateY(calc(-1 * var(--height)));}
  100%   {transform: translateY(0);}
}
@media (max-width: 1750px) and (min-width: 1381px){
selector{
    padding-left: 8%;
    padding-right: 12%;
}
}
@media (max-width: 1380px) and (min-width: 768px){
selector{
    padding-left: 0.5%;
    padding-right: 5.5%;
}
}
selector{
    --dot-size: 23px;
    --line-color: #B0B7D04D;
    --dot-color: #B0B7D0;
    --dot-color-active: #B0B7D0;
    color: #fff;
    font-size: 13px;
    font-weight: bold;
}
selector{
    height: 80vh;
    height: var(--min-height);
    max-height: 80vh;
    min-height: 0 !important;
}
selector .dot{
    height: var(--dot-size);
    width: var(--dot-size);
    background: var(--dot-color);
    border-radius: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    transform: scale(0.3);
    transition: all 0.3s ease-in-out;
    cursor: pointer;
}
selector .dot-number{
    opacity: 0;
    transition: all 0.3s ease-in-out;
}
selector .dot.active{
    transform: scale(1);
    background: var(--dot-color-active);
}
selector .dot.active .dot-number{
    opacity: 1;
}
selector:before{
    content: "";
    position: absolute;
    top: 50%;
    height: calc(100% - 20px);
    max-height: 90vh;
    width: 1px;
    background: var(--line-color);
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
}

@media (max-width: 767px){
selector{
    transform: translateX(-50%);
    flex-wrap: nowrap !important;
}
selector:before {
    width: calc(100% - 20px);
    height: 1px;

}
}
selector{
    background: #fff;
    --background-speed: 0.5s;
}
selector .elementor-background-slideshow{
    display: none;
}
selector .reboot-slider-background,
selector .reboot-slider-background img{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    transition: all 1s ease-in-out;
}
selector .reboot-slider-background img{
    object-fit: cover;
    opacity: 0;
    transform: scale(1.1);
}
selector .reboot-slider-background img.prev,
selector .reboot-slider-background img.currentBackward,
selector .reboot-slider-background img.currentForward{
    opacity: 1;
    transform: scale(1.1);
}

selector .reboot-slider-background img.currentBackward,
selector .reboot-slider-background img.currentForward{
    z-index: 1;
    opacity: 1;
    animation: bgNext var(--background-speed) linear;
    transition: all 1s ease-in-out;
    transform: scale(1);
}

selector:before{
    z-index: 2;
}
selector > .elementor-element{
    z-index: 3;
}

selector .reboot-bar,
selector .reboot-slider-left,
selector .reboot-slider-right{
    opacity: 0;
    transition: all 0.8s ease-in-out;
}
selector.loaded .reboot-bar,
selector.loaded .reboot-slider-left,
selector.loaded .reboot-slider-right{
    opacity: 1;
}
/*selector .ds-slider-left a:focus,*/
/*selector .ds-slider-right a:focus{*/
/*    outline: none !important;*/
/*}*/

@keyframes bgNext {
  0%   {opacity: 0; transform: scale(1.1);}
  100%   {opacity: 1; transform: scale(1);}
}

@media (min-width: 768px){
selector .reboot-bar,
selector .reboot-slider-left,
selector .reboot-slider-right{
    position: relative;
}
}

@media (max-width: 1380px) and (min-width: 768px){
selector{
    padding-left: 4%;
    padding-right: 4%;
}
}

@media (max-width: 767px){
selector .reboot-slider-left{
    left: calc(50% - 300px/2) !important;
}
selector .reboot-slider-right{
    right: calc(50% - 300px/2) !important;
}
}
reboot-slider

reboot-bar

reboot-changing-widget

reboot-changing-widget

reboot-changing-widget

reboot-side-slider

reboot-slider-left

reboot-slider-right
open setting in vs code (ctrl + ,) ,then  go to  search bar and search -->>      .codeiumconfig        
then open first opection ,  and click  edit in setting.json .  then redirect  -->> 
   codeium.enableConfig            and   add this 2 line --->>>>





    // aftr this line, the code is not visible in the provided snippet 53-54
    "autoSuggestions": false,
    "autoComplete": false,  
20 NHÓM CÔNG CỤ AI NHẤT ĐỊNH CẦN BIẾT VÀ THÀNH THẠO TRONG 2025
A. NHÓM AI giúp Viết, nói & giao tiếp hiệu quả
1. Tư duy & giải quyết vấn đề:
ChatGPT, Gemini, Meta AI, DeepSeek, Copilot
2. Tóm tắt, dịch & xử lý văn bản dài:
Claude, Qwen, Wordtune, ChatGPT
3. Viết nội dung & chỉnh sửa:
Writesonic, Grammarly, DeepAI
4. Tạo slide & thuyết trình:
SlidesAI, Gamma.app, Copilot, SlideGo
5. Nâng cao năng suất cá nhân:
Copilot, ExcelGPT, Notion AI, Taskade AI
(Giúp tăng hiệu quả công việc, làm báo cáo, lập kế hoạch)
B. NHÓM Thiết kế hình ảnh, video & thương hiệu cá nhân
6. Tạo hình ảnh sáng tạo:
MidJourney, DALL·E 3, Diffusion, OpenArt
7. Thiết kế đồ họa chuyên nghiệp:
Leonardo AI, Adobe Firefly, Designs AI
8. Chỉnh sửa ảnh nâng cao:
Remini, Canva AI, DeepImage
9. Tạo avatar & hình cá nhân hóa:
StarryAI, Fotor, Creatify
10. Xây dựng thương hiệu hình ảnh:
Looka, Brandmark, Logo AI
(Giúp phụ nữ tự tạo logo, nhận diện thương hiệu)
C. Sản xuất video & nhạc AI
11. Tạo video AI chuyên nghiệp:
Synthesia, HeyGen, VideoGen, TopView, Pictory
12. Tạo video ngắn TikTok/Reels:
Fliki, Steve. ai, Veed. io, Short
13. Chỉnh sửa video đơn giản – dễ dùng:
Capcut, Pictory, VideoGen
14. Sáng tác nhạc AI:
Soundraw, Suno, iLoveSong
15. Tạo podcast & giọng nói ảo:
ElevenLabs, Play. ht, Voicemaker
(Tạo nội dung podcast, video thuyết trình)
D. Dành cho lập trình & hệ thống
16. Viết mã code & lập trình:
Replit, Github Copilot, Codeium
17. Tạo chatbot AI:
Manychat, Chatbase, Botpress
(Phù hợp làm chăm sóc khách hàng tự động)
18. Phân tích dữ liệu & AI cho Excel:
SheetAI, MonkeyLearn, ExcelGPT
(Áp dụng cho công việc văn phòng & kế toán)
E. Công cụ tổng hợp đa năng
19. Tạo trang web & landing page:
Durable AI, 10Web, Framer AI
(Giúp kinh doanh online nhanh chóng)
20.  Hệ sinh thái AI đa năng (All-in-one):
Notion AI, Taskade, FlowGPT, AIToolsKit
(Kết hợp nhiều công cụ trong một nền tảng)
Dreaming of launching a cryptocurrency exchange? With Opris Cryptocurrency Exchange Development Services, you can bring that dream to life with a secure, scalable, and fully customizable platform that stands out in the crypto world.

🔹 Centralized & Decentralized Exchange Development
🔹 P2P & OTC Trading Solutions
🔹 Seamless Wallet Integration & Multi-Currency Support
🔹 High-Speed Order Matching Engine
🔹 Advanced Security Features – Protect Your Users
🔹 Regulatory Compliance – Expand Globally

Your exchange, your rules. Don’t miss out on the next big thing in crypto! 💡
  const validKeys = new Set(newVariables.map(v => v.name)); // Extracts valid keys from newVariables
  return Object.fromEntries(Object.entries(prev).filter(([key]) => validKeys.has(key))); // Removes invalid keys
With a massive $14B+ weekly trading volume and a 58.04% growth surge, PancakeSwap has officially overtaken Uniswap as the leading decentralized exchange!

What’s driving its success? High liquidity & smooth trading Low fees & ultra-fast transactions Strong community-driven ecosystem

Looking to build a decentralized exchange like PancakeSwap? Contact Opris Decentralized Exchange Development Company and launch your own DEX today!
[...document.querySelectorAll("#root > main > div > div:nth-child(2) > div:nth-child(2) > div.table-card > div > div.h-100 > div > div.p-datatable-wrapper > table > tbody > tr")].reduce((sum,row) => sum + (parseFloat(row.children[18]?.textContent.trim()) || 0), 0);
jQuery('.wpens_email').attr('placeholder', 'Enter Email Address');
[wpens_easy_newsletter firstname="no" lastname="no" button_text="⟶"]
console.log("Running client script");

var stage = ZDK.Page.getField("Stage").getValue();
console.log("Stage:", stage);
// Get the current record ID
var recordId = $Page.record_id;

console.log(recordId);


var booking = ZDK.Apps.CRM.Deals.fetchById(recordId);
var related_invoices = booking.__fetchRelatedRecords("Invoices");
console.log("Related Invoices: ",related_invoices);

for(var i=0; i< related_invoices.length; i++){
    log(related_invoices[i]);
    balance = related_invoices[i]._Balance;
    console.log("Balance: ", balance);
    if (balance > 0)
    {
        ZDK.Client.showAlert("Can not close the deal, we have outstanding balance in Invoices!");
        return false;
    }
}

var related_reservation = booking.__fetchRelatedRecords("Supplier_Reservation");
console.log("Related Suppliers: ",related_reservation);
for(var i=0; i< related_reservation.length; i++){
    log(related_reservation[i]);
    balance = related_reservation[i]._Balance_Due_2;
    console.log("Balance: ", balance);
    if (balance > 0)
    {
        ZDK.Client.showAlert("Can not close the deal, we have outstanding balance in Supplier Reservations!");
        return false;
    }
}
SEO & Digital Marketing Experts – Whiz Marketers

In today’s digital landscape, having a strong online presence is essential for business success. At Whiz Marketers, we specialize in SEO and digital marketing strategies that drive traffic, enhance visibility, and increase conversions. Our expertise in search engine optimization, content marketing, social media, and paid advertising ensures that businesses of all sizes can achieve sustainable growth in the online marketplace.

Why SEO & Digital Marketing Matter

The internet is a crowded space, and standing out requires more than just a website. Businesses must actively engage with their audience, optimize their content for search engines, and leverage paid advertising for faster results. At Whiz Marketers, we help brands navigate the complexities of digital marketing with data-driven strategies that maximize return on investment (ROI).

Our SEO & Digital Marketing Services

We offer a full suite of SEO and digital marketing services tailored to your business needs. Our approach is centered around innovation, analytics, and continuous optimization to ensure the best possible results.

1. Search Engine Optimization (SEO)

SEO is the foundation of digital success. Our SEO experts use advanced techniques to improve your search rankings, drive organic traffic, and establish your brand as an authority in your industry. Our services include:
✔ Keyword research & competitive analysis✔ On-page SEO optimization✔ Technical SEO enhancements✔ Link-building & off-page SEO✔ Local SEO for businesses targeting specific regions✔ SEO audits & performance tracking

2. Pay-Per-Click Advertising (PPC)

Paid advertising is one of the fastest ways to generate leads and sales. Our PPC specialists create high-converting ad campaigns that maximize every dollar spent. Our services include:
✔ Google Ads & Bing Ads management✔ Social media advertising (Facebook, Instagram, LinkedIn, Twitter)✔ Display and remarketing campaigns✔ A/B testing and conversion rate optimization✔ Performance monitoring & reporting

3. Social Media Marketing (SMM)

A strong social media presence enhances brand awareness and fosters customer engagement. We create and manage campaigns that resonate with your audience and increase brand loyalty. Our services include:
✔ Social media strategy & management✔ Content creation & scheduling✔ Influencer marketing & collaborations✔ Paid social media advertising✔ Analytics & insights for growth

4. Content Marketing

Quality content is key to attracting and retaining customers. Our content marketing team creates engaging, SEO-optimized content that informs, educates, and converts. Our services include:
✔ Blog writing & website content✔ Video content & infographics✔ Email marketing campaigns✔ Thought leadership articles & case studies✔ Content strategy & distribution

5. Branding & Website Optimization

Your brand and website are the digital face of your business. We ensure that your brand identity and website design align with your marketing goals. Our services include:
✔ Logo design & brand identity development✔ Website design & UX/UI optimization✔ Mobile-friendly & SEO-optimized websites✔ Landing page creation for higher conversions✔ Performance tracking & analytics

Why Choose Whiz Marketers?

✅ Experienced Team: Our team of SEO and digital marketing experts has years of industry experience.✅ Data-Driven Approach: We analyze data to make informed decisions that improve marketing outcomes.✅ Customized Strategies: We tailor every marketing plan to fit your business goals and target audience.✅ Proven Results: Our clients see measurable improvements in search rankings, traffic, and conversions.✅ Transparent Communication: We provide clear insights and regular updates on campaign performance.

Grow Your Business with Whiz Marketers

If you're looking to improve your SEO rankings, boost brand awareness, or generate high-quality leads, Whiz Marketers is your go-to partner. We are passionate about helping businesses succeed in the competitive digital space with smart, results-driven marketing strategies.

Let’s take your business to new heights – Contact Whiz Marketers today!

Contact Us Today!

Website: https://www.whizmarketers.com/
Email: reachus@whizmarketers.com
Whatsapp: +91 73580 73949
Telegram: https://telegram.me/whizmarketers

    // Flag to prevent multiple script loads
    var nrichScriptLoaded = false;

    // Function to load the N.Rich script
    function loadNrichScript(cookielessMode) {
        if (nrichScriptLoaded) {
            console.log("N.Rich script already loaded.");
            return;
        }
        nrichScriptLoaded = true;
        console.log("Loading N.Rich script with cookieless mode:", cookielessMode);
        var config = {
            cookieless: cookielessMode,
        };
        !function(n,a,t,i,f,y){
            n[t]=n[t]||function(){(n[t].q=n[t].q||[]).push(arguments)},
            n[t].l=1*new Date,
            f=a.createElement(i),
            f.async=true,
            y=a.getElementsByTagName(i)[0],
            f.src='https://serve.nrich.ai/tracker/assets/tracker.js?nto='+t,
            y.parentNode.insertBefore(f,y)
        }(window,document,'nt','script');
        nt('load','1c53c9dc-268b-470e-8e18-b2dd2a63c5a3', config);
    }

    // Function to check consent and load the script accordingly
    function initializeNrich() {
        var consentGiven = cmplz_has_consent('marketing');
        console.log("Consent given:", consentGiven);
        if (consentGiven) {
            console.log("Consent given, loading N.Rich with cookies.");
            loadNrichScript(false); // cookieless: false
        } else {
            console.log("Consent not given, loading N.Rich in cookieless mode.");
            loadNrichScript(true); // cookieless: true
        }
    }

    // Run initialization on page load
    document.addEventListener("DOMContentLoaded", function() {
        initializeNrich();
    });

    // Update N.Rich when consent status changes
    document.addEventListener("cmplzConsentStatus", function (e) {
        console.log("Consent status changed:", e.detail);
        // Reset the flag to allow reloading the script
        nrichScriptLoaded = false;
        initializeNrich();
    });
Dappfort specializes in BRC20 wallet development, providing businesses with a secure, scalable, and budget-friendly solution for managing BRC-20 tokens. Our development process focuses on optimizing costs while ensuring high security, seamless user experience, and robust functionality.

Key Features:

Affordable Development – Cost-effective solutions tailored to your business needs. 
Secure Asset Management – Advanced encryption and multi-signature security. 
Seamless Transactions – Fast and efficient token transfers on the Bitcoin blockchain. 
User-Friendly Interface – Intuitive design for hassle-free access. 
Scalability & Customization – Adaptable to evolving market demands.

At Dappfort, we ensure your BRC20 wallet is built with cutting-edge technology while keeping development costs under control.

Get in touch to develop a cost-effective BRC20 wallet today!

Instant Reach Experts: 
Visit us : https://www.dappfort.com/cryptocurrency-wallet-development-company/ 
Contact : +91 8838534884 
Mail : sales@dappfort.com
DappFort delivers world-class P2P crypto exchange development, helping businesses enter the digital asset market with confidence. Our platforms feature advanced matching engines, dispute resolution, and AI-driven analytics for seamless trading. With multi-currency and multi-payment support, we enhance user accessibility. Get started today and dominate the crypto exchange industry!

Instant Reach Experts: 
Visit us : https://www.dappfort.com/cryptocurrency-exchange-development-company/
Contact : +91 8838534884 
Mail : sales@dappfort.com
Maximize your crypto gains with Dappfort high-performance Crypto Trading Bot Development services. Our bots integrate with major exchanges, use AI-driven strategies, and provide real-time analytics. Trade smarter, faster, and with reduced risks. Let’s build your profit-generating trading bot now!

Instant Reach Experts:

Contact : +91 8838534884 
Mail : sales@dappfort.com
Transform your trading experience with our powerful Algo Trading Software Development solutions. Our AI-powered algorithms analyze market trends, execute trades with precision, and minimize risks. Whether for crypto, forex, or stocks, we deliver high-performance automation. Boost your profits with algorithmic trading—get started now!
  
Visit us : https://www.dappfort.com/blog/algo-trading-software-development/   

Instant Reach Experts:

Contact : +91 8838534884 
Mail : sales@dappfort.com
Wow! The future is here, and AI is your golden ticket to success! From mind-blowing automation to game-changing AI solutions, the opportunities are limitless. Imagine building a business that runs on innovation, scales effortlessly, and generates massive profits!

Ready to ride the AI wave and turn your vision into reality? The time to start is NOW! 
  
Visit : https://www.dappfort.com/blog/ai-business-ideas/

Instant Reach Experts:

Visit us :  https://www.dappfort.com/cryptocurrency-exchange-development-company/      
Contact : +91 8838534884
Mail : sales@dappfort.com
document.addEventListener("visibilitychange", function(event) {
    Object.defineProperty(document, "hidden", { value: false, configurable: true });
    Object.defineProperty(document, "visibilityState", { value: "visible", configurable: true });
});
    (() => {
        let selectedSizeSystem = null; // Global variable to store selected size system
    
        // Main mouseup handler
        const handleMouseUp = (event) => {
            const target = event.target;
    
            // Check if target or its parent has the js-size-selector attribute
            const sizeSelector = target.closest('[js-size-selector]');
            if (!sizeSelector) return;
    
            const newSizeSystem = sizeSelector.innerText.trim();
    
            // Only update and call updateProductContext if the size system changed
            if (selectedSizeSystem !== newSizeSystem) {
                selectedSizeSystem = newSizeSystem;
                console.log('Size system selector changed:', { text: selectedSizeSystem });
    
                // Call updateProductContext whenever the size system changess
                updateProductContext();
            }
        };
    
        // Use capture phase to ensure we get the mouseup before preventDefault
        document.addEventListener('mouseup', handleMouseUp, true);
    
        // Expose a function to get the selected size system
        window.getSelectedSizeSystem = () => selectedSizeSystem;
    })();  
💰 Launch Your Own Stablecoin with Confidence!

Enter the world of stable digital assets with a secure, transparent, and fully customizable stablecoin development solution.

✅ Fiat-pegged, crypto-collateralized, or algorithmic stablecoins
✅ Regulatory-compliant & highly secure
✅ Seamless integration with wallets & exchanges
✅ Built for scalability & global transactions

🚀 Power up your crypto ecosystem with Dappfort – The Trusted Stablecoin Development Company!
  
Instant Reach Experts:
Contact : +91 8838534884
Mail : sales@dappfort.com
At Dappfort, a leading decentralized exchange development company, we provide end-to-end solutions to build high-performance DEX platforms. Our expertise ensures seamless trading, advanced security, and optimized scalability, empowering businesses to launch future-ready decentralized exchanges.

Instant Reach Experts:
Contact : +91 8838534884
Mail : sales@dappfort.com
🚀 The Future of Blockchain Business in 2025!

Blockchain is no longer just about crypto—it’s opening doors to groundbreaking business opportunities! From DeFi platforms to tokenized assets, new ventures are reshaping industries and creating endless possibilities.

Want to know which blockchain business ideas will dominate 2025? We've got 15 game-changing ideas that could be your next big move!

Don't miss out

Instant Reach Experts:

Contact : +91 8838534884
Mail : sales@dappfort.com
Dappfort is a leading cryptocurrency exchange development company committed to delivering high-quality, secure, and scalable trading platforms. With a strong focus on customer satisfaction, we have successfully developed and deployed various types of crypto exchanges tailored to our clients unique requirements. Our expert team ensures top-tier security, privacy, and reliability, fostering trust between business owners and their users. By leveraging our advanced cryptocurrency exchange solutions, including P2P trading and Bitcoin exchange systems, businesses can offer a seamless and highly secure trading experience. To explore how Dappfort can help you build a robust crypto exchange, schedule a consultation with our blockchain experts today.

Instant Reach Experts:

Visit us :  https://www.dappfort.com/cryptocurrency-exchange-development-company/      
Contact : +91 8838534884
Mail : sales@dappfort.com
Imagine the thrill of building your financial empire without the constraints of a suit or the frenzy of Wall Street. 

	Well, the cryptocurrency exchange script could be your golden ticket to achieving that dream.

	Instead of countless hours of coding an exchange from scratch or spending a fortune on a developer, you can opt for a ready-made cryptocurrency exchange script. This allows you to set up your crypto trading platform quickly.

	It’s hassle-free so connect easily. Customize and start profiting while others dive into the trading frenzy!

Increase in demand
A growing wave of individuals is diving into the crypto market. Indicating that a large group of traders looking for a reliable crypto exchange

Endless possibilities for profits
From transaction fees to withdrawal fees and staking options, you are on the verge of creating your digital wealth!

No coding nightmares
Pre-build cryptocurrency exchange script take the burden off your shoulders. Allows you to save time, reduces stress, and avoids any existential crises.

	Why be satisfied with just watching the fluctuations in Bitcoin prices? Dive in and reap the benefits!

	Start your crypto exchange and get an exciting crypto wave of success.

	Who knows? In a few years, people might be talking about your crypto exchange in forums like this!
      
Website: https://www.trioangle.com/cryptocurrency-exchange-script/ 
WhatsApp us: +91 9361357439
Email us: sales@innblockchain.com
const req = await fetch(
    "http://localhost:3000/api/auth/signin", {
      method: "POST",
      header:{
        'Accept':'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username:myusername,
        password:mypassword
      })
    },
    
  )
<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div class="background"></div>
    <img class="bird" src="logo.png" alt="bird-img">
    <div class="message">
        Press Enter To Start Game
    </div>
    <div class="score">
        <span class="score_title"></span>
        <span class="score_val"></span>
    </div>
    <script src="gfg.js"></script>
</body>

</html>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    height: 100vh;
    width: 100vw;
}

.background {
    height: 100vh;
    width: 100vw;
    background-color: skyblue;
}

.bird {
    height: 100px;
    width: 160px;
    position: fixed;
    top: 40vh;
    left: 30vw;
    z-index: 100;
}

.pipe_sprite {
    position: fixed;
    top: 40vh;
    left: 100vw;
    height: 70vh;
    width: 6vw;
    background-color: green;
}

.message {
    position: fixed;
    z-index: 10;
    height: 10vh;
    font-size: 10vh;
    font-weight: 100;
    color: black;
    top: 12vh;
    left: 20vw;
    text-align: center;
}

.score {
    position: fixed;
    z-index: 10;
    height: 10vh;
    font-size: 10vh;
    font-weight: 100;
    color: goldenrod;
    top: 0;
    left: 0;
}

.score_val {
    color: gold;
}
// Background scrolling speed
let move_speed = 3;
  
// Gravity constant value
let gravity = 0.5;
  
// Getting reference to the bird element
let bird = document.querySelector('.bird');
  
// Getting bird element properties
let bird_props = bird.getBoundingClientRect();
let background =
    document.querySelector('.background')
            .getBoundingClientRect();
  
// Getting reference to the score element
let score_val =
    document.querySelector('.score_val');
let message =
    document.querySelector('.message');
let score_title =
    document.querySelector('.score_title');
  
// Setting initial game state to start
let game_state = 'Start';
  
// Add an eventlistener for key presses
document.addEventListener('keydown', (e) => {
  
  // Start the game if enter key is pressed
  if (e.key == 'Enter' &&
      game_state != 'Play') {
    document.querySelectorAll('.pipe_sprite')
              .forEach((e) => {
      e.remove();
    });
    bird.style.top = '40vh';
    game_state = 'Play';
    message.innerHTML = '';
    score_title.innerHTML = 'Score : ';
    score_val.innerHTML = '0';
    play();
  }
});
function play() {
  function move() {
    
    // Detect if game has ended
    if (game_state != 'Play') return;
    
    // Getting reference to all the pipe elements
    let pipe_sprite = document.querySelectorAll('.pipe_sprite');
    pipe_sprite.forEach((element) => {
      
      let pipe_sprite_props = element.getBoundingClientRect();
      bird_props = bird.getBoundingClientRect();
      
      // Delete the pipes if they have moved out
      // of the screen hence saving memory
      if (pipe_sprite_props.right <= 0) {
        element.remove();
      } else {
        // Collision detection with bird and pipes
        if (
          bird_props.left < pipe_sprite_props.left +
          pipe_sprite_props.width &&
          bird_props.left +
          bird_props.width > pipe_sprite_props.left &&
          bird_props.top < pipe_sprite_props.top +
          pipe_sprite_props.height &&
          bird_props.top +
          bird_props.height > pipe_sprite_props.top
        ) {
          
          // Change game state and end the game
          // if collision occurs
          game_state = 'End';
          message.innerHTML = 'Press Enter To Restart';
          message.style.left = '28vw';
          return;
        } else {
          // Increase the score if player
          // has the successfully dodged the 
          if (
            pipe_sprite_props.right < bird_props.left &&
            pipe_sprite_props.right + 
            move_speed >= bird_props.left &&
            element.increase_score == '1'
          ) {
            score_val.innerHTML = +score_val.innerHTML + 1;
          }
          element.style.left = 
            pipe_sprite_props.left - move_speed + 'px';
        }
      }
    });

    requestAnimationFrame(move);
  }
  requestAnimationFrame(move);

  let bird_dy = 0;
  function apply_gravity() {
    if (game_state != 'Play') return;
    bird_dy = bird_dy + gravity;
    document.addEventListener('keydown', (e) => {
      if (e.key == 'ArrowUp' || e.key == ' ') {
        bird_dy = -7.6;
      }
    });

    // Collision detection with bird and
    // window top and bottom

    if (bird_props.top <= 0 ||
        bird_props.bottom >= background.bottom) {
      game_state = 'End';
      message.innerHTML = 'Press Enter To Restart';
      message.style.left = '28vw';
      return;
    }
    bird.style.top = bird_props.top + bird_dy + 'px';
    bird_props = bird.getBoundingClientRect();
    requestAnimationFrame(apply_gravity);
  }
  requestAnimationFrame(apply_gravity);

  let pipe_seperation = 0;
  
  // Constant value for the gap between two pipes
  let pipe_gap = 35;
  function create_pipe() {
    if (game_state != 'Play') return;
    
    // Create another set of pipes
    // if distance between two pipe has exceeded
    // a predefined value
    if (pipe_seperation > 115) {
      pipe_seperation = 0
      
      // Calculate random position of pipes on y axis
      let pipe_posi = Math.floor(Math.random() * 43) + 8;
      let pipe_sprite_inv = document.createElement('div');
      pipe_sprite_inv.className = 'pipe_sprite';
      pipe_sprite_inv.style.top = pipe_posi - 70 + 'vh';
      pipe_sprite_inv.style.left = '100vw';
      
      // Append the created pipe element in DOM
      document.body.appendChild(pipe_sprite_inv);
      let pipe_sprite = document.createElement('div');
      pipe_sprite.className = 'pipe_sprite';
      pipe_sprite.style.top = pipe_posi + pipe_gap + 'vh';
      pipe_sprite.style.left = '100vw';
      pipe_sprite.increase_score = '1';
      
      // Append the created pipe element in DOM
      document.body.appendChild(pipe_sprite);
    }
    pipe_seperation++;
    requestAnimationFrame(create_pipe);
  }
  requestAnimationFrame(create_pipe);
}
<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div class="background"></div>
    <img class="bird" src="logo.png" alt="bird-img">
    <div class="message">
        Press Enter To Start Game
    </div>
    <div class="score">
        <span class="score_title"></span>
        <span class="score_val"></span>
    </div>
    <script src="gfg.js"></script>
</body>

</html>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    height: 100vh;
    width: 100vw;
}

.background {
    height: 100vh;
    width: 100vw;
    background-color: skyblue;
}

.bird {
    height: 100px;
    width: 160px;
    position: fixed;
    top: 40vh;
    left: 30vw;
    z-index: 100;
}

.pipe_sprite {
    position: fixed;
    top: 40vh;
    left: 100vw;
    height: 70vh;
    width: 6vw;
    background-color: green;
}

.message {
    position: fixed;
    z-index: 10;
    height: 10vh;
    font-size: 10vh;
    font-weight: 100;
    color: black;
    top: 12vh;
    left: 20vw;
    text-align: center;
}

.score {
    position: fixed;
    z-index: 10;
    height: 10vh;
    font-size: 10vh;
    font-weight: 100;
    color: goldenrod;
    top: 0;
    left: 0;
}

.score_val {
    color: gold;
}
// Background scrolling speed
let move_speed = 3;
  
// Gravity constant value
let gravity = 0.5;
  
// Getting reference to the bird element
let bird = document.querySelector('.bird');
  
// Getting bird element properties
let bird_props = bird.getBoundingClientRect();
let background =
    document.querySelector('.background')
            .getBoundingClientRect();
  
// Getting reference to the score element
let score_val =
    document.querySelector('.score_val');
let message =
    document.querySelector('.message');
let score_title =
    document.querySelector('.score_title');
  
// Setting initial game state to start
let game_state = 'Start';
  
// Add an eventlistener for key presses
document.addEventListener('keydown', (e) => {
  
  // Start the game if enter key is pressed
  if (e.key == 'Enter' &&
      game_state != 'Play') {
    document.querySelectorAll('.pipe_sprite')
              .forEach((e) => {
      e.remove();
    });
    bird.style.top = '40vh';
    game_state = 'Play';
    message.innerHTML = '';
    score_title.innerHTML = 'Score : ';
    score_val.innerHTML = '0';
    play();
  }
});
function play() {
  function move() {
    
    // Detect if game has ended
    if (game_state != 'Play') return;
    
    // Getting reference to all the pipe elements
    let pipe_sprite = document.querySelectorAll('.pipe_sprite');
    pipe_sprite.forEach((element) => {
      
      let pipe_sprite_props = element.getBoundingClientRect();
      bird_props = bird.getBoundingClientRect();
      
      // Delete the pipes if they have moved out
      // of the screen hence saving memory
      if (pipe_sprite_props.right <= 0) {
        element.remove();
      } else {
        // Collision detection with bird and pipes
        if (
          bird_props.left < pipe_sprite_props.left +
          pipe_sprite_props.width &&
          bird_props.left +
          bird_props.width > pipe_sprite_props.left &&
          bird_props.top < pipe_sprite_props.top +
          pipe_sprite_props.height &&
          bird_props.top +
          bird_props.height > pipe_sprite_props.top
        ) {
          
          // Change game state and end the game
          // if collision occurs
          game_state = 'End';
          message.innerHTML = 'Press Enter To Restart';
          message.style.left = '28vw';
          return;
        } else {
          // Increase the score if player
          // has the successfully dodged the 
          if (
            pipe_sprite_props.right < bird_props.left &&
            pipe_sprite_props.right + 
            move_speed >= bird_props.left &&
            element.increase_score == '1'
          ) {
            score_val.innerHTML = +score_val.innerHTML + 1;
          }
          element.style.left = 
            pipe_sprite_props.left - move_speed + 'px';
        }
      }
    });

    requestAnimationFrame(move);
  }
  requestAnimationFrame(move);

  let bird_dy = 0;
  function apply_gravity() {
    if (game_state != 'Play') return;
    bird_dy = bird_dy + gravity;
    document.addEventListener('keydown', (e) => {
      if (e.key == 'ArrowUp' || e.key == ' ') {
        bird_dy = -7.6;
      }
    });

    // Collision detection with bird and
    // window top and bottom

    if (bird_props.top <= 0 ||
        bird_props.bottom >= background.bottom) {
      game_state = 'End';
      message.innerHTML = 'Press Enter To Restart';
      message.style.left = '28vw';
      return;
    }
    bird.style.top = bird_props.top + bird_dy + 'px';
    bird_props = bird.getBoundingClientRect();
    requestAnimationFrame(apply_gravity);
  }
  requestAnimationFrame(apply_gravity);

  let pipe_seperation = 0;
  
  // Constant value for the gap between two pipes
  let pipe_gap = 35;
  function create_pipe() {
    if (game_state != 'Play') return;
    
    // Create another set of pipes
    // if distance between two pipe has exceeded
    // a predefined value
    if (pipe_seperation > 115) {
      pipe_seperation = 0
      
      // Calculate random position of pipes on y axis
      let pipe_posi = Math.floor(Math.random() * 43) + 8;
      let pipe_sprite_inv = document.createElement('div');
      pipe_sprite_inv.className = 'pipe_sprite';
      pipe_sprite_inv.style.top = pipe_posi - 70 + 'vh';
      pipe_sprite_inv.style.left = '100vw';
      
      // Append the created pipe element in DOM
      document.body.appendChild(pipe_sprite_inv);
      let pipe_sprite = document.createElement('div');
      pipe_sprite.className = 'pipe_sprite';
      pipe_sprite.style.top = pipe_posi + pipe_gap + 'vh';
      pipe_sprite.style.left = '100vw';
      pipe_sprite.increase_score = '1';
      
      // Append the created pipe element in DOM
      document.body.appendChild(pipe_sprite);
    }
    pipe_seperation++;
    requestAnimationFrame(create_pipe);
  }
  requestAnimationFrame(create_pipe);
}
/* ====== create node.js server with core 'http' module ====== */
// dependencies
const http = require("http");

// PORT
const PORT = 3000;

// server create
const server = http.createServer((req, res) => {
   if (req.url === "/") {
      res.write("This is home page.");
      res.end();
   } else if (req.url === "/about" && req.method === "GET") {
      res.write("This is about page.");
      res.end();
   } else {
      res.write("Not Found!");
      res.end();
   }
});

// server listen port
server.listen(PORT);

console.log(`Server is running on PORT: ${PORT}`);

/* ========== *** ========== */

/* ====== create node.js server with express.js framework ====== */
// dependencies
const express = require("express");

const app = express();

app.get("/", (req, res) => {
   res.send("This is home page.");
});

app.post("/", (req, res) => {
   res.send("This is home page with post request.");
});

// PORT
const PORT = 3000;

app.listen(PORT, () => {
   console.log(`Server is running on PORT: ${PORT}`);
});


// ======== Instructions ========
// save this as index.js
// you have to download and install node.js on your machine
// open terminal or command prompt
// type node index.js
// find your server at http://localhost:3000
const fetchMovies = async () => {
    // set the loading state to true so the loading indicator is displayed as soon as the function is called
    setIsLoading(true); 

    try { 
      // endpoint for fetching movies and sorting them by popularity (descending)
      const endpoint = `${API_BASE_URL}/discover/movie?sort_by=popularity.desc`;  
      // calling the endpoint with the API options
      const response = await fetch(endpoint, API_OPTIONS);
      // parsing the response into a json object
      if (!response.ok) {
        throw new Error('Failed to fetch movies');
      }
      const data = await response.json(); // if successful response, parse the data
      console.log(data); // just to see what we get from the API (over 48000 pages and almost a million movies)

      // if we get no response, set the error message, and set the movies state to an empty array
      if(data.Response === 'False') {
        setErrorMessage(data.Error || 'Failed to fetch movies');
        setMovies([]);
        return; // exit out of the function
      }

      // if we get a response, set the movies state with the fetched data
      setMovies(data.results || []);

      /*
      The empty array in `setMovies(data.results || [])` ensures that the `movies` state is always set to a valid array,  
      even if the API response does not include the expected `results` property or if it is `null` or `undefined`.
      */

    } catch (error) {
      console.error(`Error while fetching movies: ${error}`);
      setErrorMessage('An error occurred while fetching movies. Please try again later.');

    } finally {
      // set the loading state to false after the fetch is complete (whether successful or not)
      setIsLoading(false);
    }
  }
- 👋 Hi, I’m @BAHATI44
<!DOCTYPE html>
<html lang="fr">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="Inscription BuloMED">
    <meta name="keywords" content="inscription, BuloMED, santé">
    <meta name="author" content="Salomo B.M">
    <title>Inscription BuloMED</title>
    <link rel="stylesheet" href="styles/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/css/intlTelInput.css">
    <link rel="icon" type="image/png" sizes="32x32" href="BuloMED.PNG">
    <!-- Sécurité supplémentaire -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self' https: 'unsafe-inline' 'unsafe-eval';">
    <meta http-equiv="X-Content-Type-Options" content="nosniff">
    <meta http-equiv="X-Frame-Options" content="DENY">

    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f8f9fa;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        
        .form-wrapper {
            position: relative;
            padding: 5px;
            border-radius: 15px;
            background: linear-gradient(45deg, #ff0000, #00ff00, #0000ff, #ff00ff, #ffff00);
            background-size: 200% 200%;
            animation: gradientAnimation 3s ease infinite;
            display: flex;
        }
        /* Exemple de media queries pour petits écrans */
        
        @media (max-width: 600px) {
            .form-container {
                width: 90%;
                /* Utiliser une largeur en pourcentage pour s'adapter */
                max-width: none;
                /* Supprimer la limite fixe */
                padding: 10px;
                /* Réduire les espaces si nécessaire */
            }
            .form-group input {
                width: 100%;
                /* Assurer que les inputs prennent toute la largeur disponible */
                font-size: 1rem;
                /* Ajuster la taille de police pour plus de lisibilité */
            }
            .button-container {
                flex-direction: column;
                /* Sur petits écrans, empiler les boutons */
                gap: 5px;
            }
        }
        /* Optionnel : règles pour les écrans moyens */
        
        @media (min-width: 601px) and (max-width: 1024px) {
            .form-container {
                width: 80%;
                padding: 12px;
            }
            .form-group input {
                font-size: 1.1rem;
            }
        }
        
        @keyframes gradientAnimation {
            0% {
                background-position: 0% 50%;
            }
            50% {
                background-position: 100% 50%;
            }
            100% {
                background-position: 0% 50%;
            }
        }
        
        .form-container {
            background-color: #7b7c7c;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 0 7px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 350px;
            position: relative;
            z-index: 1;
        }
        
        .form-container h2 {
            text-align: center;
            margin-bottom: 25px;
            color: #fff;
        }
        
        .form-group {
            margin-bottom: 15px;
            position: relative;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
        }
        
        .form-group input {
            width: 95%;
            padding: 10px;
            border: 2px solid #ccc;
            border-radius: 8px;
        }
        
        .password-toggle {
            position: absolute;
            right: 10px;
            top: 35px;
            cursor: pointer;
        }
        
        .loading-spinner {
            display: none;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #4CAF50;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }
            100% {
                transform: rotate(360deg);
            }
        }
        /* Nouveau style pour aligner les boutons côte à côte */
        
        .button-container {
            display: flex;
            justify-content: space-between;
            gap: 10px;
        }
        
        .button-container button {
            flex: 1;
        }
        /* Style du popup de succès */
        
        .success-popup {
            display: none;
            position: fixed;
            top: 20px;
            right: 20px;
            background-color: #4CAF50;
            color: white;
            padding: 15px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            z-index: 1000;
        }
    </style>
</head>

<body>
    <div class="form-wrapper">
        <div class="form-container">
            <h2>Inscription</h2>
            <form id="registrationForm">
                <div class="form-group">
                    <label for="username">Nom d'utilisateur</label>
                    <input type="text" id="username" name="username" maxlength="50" placeholder="Saisir le nom D'utilisateur" required>
                    <div class="error" id="usernameError"></div>
                </div>
                <div class="form-group">
                    <label for="email">Email</label>
                    <input type="email" id="email" name="email" maxlength="50" placeholder="Saisir l'Email" required>
                    <div class="error" id="emailError"></div>
                </div>
                <div class="form-group">
                    <label for="password">Mot de passe</label>
                    <input type="password" id="password" name="password" maxlength="50" placeholder="Saisir Votre Mot de Passe" required>
                    <i class="fa fa-eye password-toggle" id="togglePassword"></i>
                    <div class="password-strength" id="passwordStrength"></div>
                    <div class="error" id="passwordError"></div>
                </div>
                <div class="form-group">
                    <label for="phone">Numéro de téléphone</label>
                    <input type="tel" id="phone" name="phone" maxlength="13" required>
                    <div class="error" id="phoneError"></div>
                </div>
                <!-- Conteneur pour les deux boutons -->
                <div class="button-container">
                    <button type="submit">
                        <span class="button-text">S'inscrire</span>
                        <div class="loading-spinner"></div>
                    </button>
                    <button type="button" id="loginButton">Se connecter</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Popup de succès -->
    <div id="successPopup" class="success-popup">Connexion réussie !</div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/intlTelInput.min.js"></script>
    <script>
        // Empêcher le clic droit pour bloquer l'accès au menu contextuel
        document.addEventListener('contextmenu', function(e) {
            e.preventDefault();
            return false;
        });

        // Bloquer les raccourcis clavier (Ctrl+Shift+I, Ctrl+U, F12, etc.)
        document.addEventListener('keydown', function(e) {
            if (e.ctrlKey || e.keyCode === 123 || e.keyCode === 85) {
                e.preventDefault();
                return false;
            }
        });

        // Détection des outils de développement
        setInterval(function() {
            if (window.outerWidth - window.innerWidth > 100 ||
                window.outerHeight - window.innerHeight > 100) {
                window.location.href = "about:blank";
            }
        }, 1000);

        // Empêcher la sélection de texte
        document.body.style.userSelect = 'none';
        document.body.style.webkitUserSelect = 'none';

        // Initialisation des éléments du formulaire
        document.addEventListener('DOMContentLoaded', function() {
            const phoneInput = document.getElementById('phone');
            const passwordInput = document.getElementById('password');
            const passwordStrength = document.getElementById('passwordStrength');
            const togglePassword = document.getElementById('togglePassword');
            const form = document.getElementById('registrationForm');
            const loginButton = document.getElementById('loginButton');
            const successPopup = document.getElementById('successPopup');

            // Initialisation du sélecteur de numéro de téléphone
            if (window.intlTelInput) {
                const iti = window.intlTelInput(phoneInput, {
                    initialCountry: "auto",
                    utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js"
                });
            } else {
                console.error("intlTelInput library is not loaded correctly.");
            }

            // Vérification de la force du mot de passe
            passwordInput.addEventListener('input', function() {
                const hasMixedCase = /(?=.*[a-z])(?=.*[A-Z])/.test(this.value);
                const hasNumbers = /\d/.test(this.value);
                const hasSpecial = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(this.value);
                if (hasMixedCase && hasNumbers && hasSpecial) {
                    passwordStrength.className = 'password-strength strong';
                } else if ((hasMixedCase && hasNumbers) || (hasNumbers && hasSpecial)) {
                    passwordStrength.className = 'password-strength medium';
                } else {
                    passwordStrength.className = 'password-strength weak';
                }
            });

            // Basculer la visibilité du mot de passe
            togglePassword.addEventListener('click', function() {
                const type = passwordInput.type === 'password' ? 'text' : 'password';
                passwordInput.type = type;
                this.classList.toggle('fa-eye-slash');
            });

            // Gestion de la soumission du formulaire
            form.addEventListener('submit', function(event) {
                event.preventDefault();
                const button = form.querySelector('button[type="submit"]');
                button.disabled = true;
                button.querySelector('.loading-spinner').style.display = 'inline-block';
                button.querySelector('.button-text').textContent = 'Traitement...';

                // Simuler un traitement de 1,5 seconde
                setTimeout(() => {
                    button.querySelector('.loading-spinner').style.display = 'none';
                    button.disabled = false;
                    button.querySelector('.button-text').textContent = 'S\'inscrire';

                    // Afficher le popup de succès
                    successPopup.style.display = 'block';
                    setTimeout(() => {
                        successPopup.style.display = 'none';
                    }, 3000);

                    // Redirection vers la page d'accueil après 3 secondes
                    setTimeout(() => {
                        window.location.href = 'accueil.html';
                    }, 3000);
                }, 1500);
            });

            // Navigation vers la page de connexion
            loginButton.addEventListener('click', function() {
                window.location.href = 'connexion.html';
            });
        });
    </script>
</body>

</html>
var difficulty = 15;
var correctSquare;
var p1Score = 0;
var p2Score = 0;
var currentPlayer = 1;

function updateScore(scoreChange){
  if(currentPlayer == 1){
    p1Score += scoreChange;
    setText("score1", p1Score);
  }
  else{
    p2Score += scoreChange;
    setText("score2", p2Score);
  }
}


<!-- Include Splide CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.4/dist/css/splide.min.css">

<!-- Splide JS Markup -->
  
<div class="splide">
    <div class="splide__track">
        <div class="splide__list">
            <div class="splide__slide"></div>
        </div>
    </div>
</div>
<!-- Include Splide JS -->
<script src="https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.4/dist/js/splide.min.js"></script>

<!-- Initialize Splide -->
<script>
document.addEventListener('DOMContentLoaded', function() {
  new Splide('.splide', {
    type: 'slide',
    perPage: 4,
    //perMove: 1,
    gap: '0',
    pagination: false,
    arrows: false,
    drag: true,
    breakpoints: {
      1024: {
        perPage: 3,
      },
      768: {
        perPage: 2,
      },
      480: {
        perPage: 1,
      }
    }
  }).mount();
});
</script>
<script src="https://cdn.jsdelivr.net/npm/darkmode-js@1.5.7/lib/darkmode-js.min.js"></script>
<script>
    const options = {
      label: '🌓',
      saveInCookies: false,
      autoMatchOsTheme: false,
       time: '1s'
    }
    function addDarkmodeWidget() {
      new Darkmode(options).showWidget();
    }
    window.addEventListener('load', addDarkmodeWidget);
</script>
const sheetName = 'Sheet1'
const scriptProp = PropertiesService.getScriptProperties()

function initialSetup () {
  const activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
  scriptProp.setProperty('key', activeSpreadsheet.getId())
}

function doPost (e) {
  const lock = LockService.getScriptLock()
  lock.tryLock(10000)

  try {
    const doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
    const sheet = doc.getSheetByName(sheetName)

    const headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
    const nextRow = sheet.getLastRow() + 1

    const newRow = headers.map(function(header) {
      return header === 'Date' ? new Date() : e.parameter[header]
    })

    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])

    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}
function BracketMatcher(str) {
  const stack = []; // Create an empty stack to keep track of opening brackets
  for (let i = 0; i < str.length; i++) { // Loop through each character in the input string
    if (str[i] === '(') { // If the character is an opening bracket
      stack.push(str[i]); // Push it onto the stack
    } else if (str[i] === ')') { // If the character is a closing bracket
      if (stack.length === 0) { // If the stack is empty, there is no matching opening bracket
        return 0; // Return 0 to indicate the brackets are not matched
      } else {
        stack.pop(); // Otherwise, pop the top element off the stack (the last opening bracket) and discard it
      }
    }
  }
  return stack.length === 0 ? 1 : 0; // If the stack is empty, all opening brackets have been matched, so return 1; otherwise, return 0
}
   
// keep this function call here 
console.log(BracketMatcher(readline()));
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/ScrollTrigger.min.js"></script>
// Custom Script 
function custom_script() {
    wp_enqueue_script( 'magnific-popup-js', 'https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.2.0/jquery.magnific-popup.min.js', null, null, true );
    wp_enqueue_style('magnific-popup-css', 'https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.2.0/magnific-popup.min.css');
}
add_action('wp_enqueue_scripts','custom_script');
function isOffScreen(el) {
	var rect = el.getBoundingClientRect();
	return (
		(rect.x + rect.width) < 0 
		|| (rect.y + rect.height) < 0
		|| (rect.x > window.innerWidth || rect.y > window.innerHeight)
	);
}
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Alertas com Sessions</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .notice {
            display: none;
            padding: 10px;
            margin: 10px auto;
            width: 300px;
            border-radius: 5px;
            text-align: center;
        }
        .notice-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .notice-error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
    </style>
</head>
<body>
    <div id="notice-success" class="notice notice-success">
        <?= $_SESSION['success'] ?? '' ?>
    </div>
    <div id="notice-error" class="notice notice-error">
        <?= $_SESSION['error'] ?? '' ?>
    </div>

    <script>
        $(document).ready(function () {
            <?php if (isset($_SESSION['success'])): ?>
                $('#notice-success').fadeIn();
                setTimeout(function () {
                    $('#notice-success').fadeOut();
                }, 5000);
            <?php unset($_SESSION['success']); endif; ?>

            <?php if (isset($_SESSION['error'])): ?>
                $('#notice-error').fadeIn();
                setTimeout(function () {
                    $('#notice-error').fadeOut();
                }, 5000);
            <?php unset($_SESSION['error']); endif; ?>
        });
    </script>
</body>
</html>
Extending Classes
One of the powerful features of classes is they can be extended. You can create a new class based on an existing class, and this new class will not only inherit all the properties and methods of the existing class, but you can add new properties and methods to the new class.

This is useful when you have a class that works for most situations, but there are some cases where you need to add new features. Instead of starting from scratch and creating an entirely new class, you can extend the existing class and add the new features. A classic example of this is making a main class called MotorVehicle with properties and methods that are common to all motor vehicles, then extending this class with more specific classes like Car, Truck, and Motorcycle.

Earlier in the course you worked with the Backpack class which has properties and methods that apply to all backpacks. But there's a snag: In my closet I have a hiking backpack with an extra feature that isn't covered by the Backpack class—a hydration pack. For my dataset to be complete, I need the ability to track the hydration capacity of my pack, for obvious reasons. The bigger the hydration capacity, the heavier the pack can potentially get at the start of a hike.

To solve this problem, let's create a new class called HikingBackpack by extending the Backpack class.

Here's the original Backpack class for reference:

class Backpack {
  constructor(
    // Defines parameters:
    name,
    volume,
    color,
    pocketNum,
    strapLengthL,
    strapLengthR,
    lidOpen
  ) {
    // Define properties:
    this.name = name;
    this.volume = volume;
    this.color = color;
    this.pocketNum = pocketNum;
    this.strapLength = {
      left: strapLengthL,
      right: strapLengthR,
    };
    this.lidOpen = lidOpen;
  }
  // Add methods like normal functions:
  toggleLid(lidStatus) {
    this.lidOpen = lidStatus;
  }
  newStrapLength(lengthLeft, lengthRight) {
    this.strapLength.left = lengthLeft;
    this.strapLength.right = lengthRight;
  }
}
To create a new class from an existing one, use the extends keyword followed by the name of the class you want to extend:

class HikingBackpack extends Backpack {}
Next, define all the properties the class needs in the constructor. This includes both the existing properties from the parent class and any new properties you want to add:

class HikingBackpack extends Backpack {
  constructor(
    name,
    volume,
    color,
    pocketNum,
    strapLengthL,
    strapLengthR,
    lidOpen,
    hydrationCapacity
  ) {
    // Initialize the parent class properties
    super(name, volume, color, pocketNum, strapLengthL, strapLengthR, lidOpen);
    // New property specific to HikingBackpack
    this.hydrationCapacity = hydrationCapacity; // Capacity in liters
  }
}
In the above example, you see hydrationCapacity has been added in the constructor. This is the new property specific to the HikingBackpack class. The super() method is used to call the constructor of the parent class and pass in the properties common to both classes. Finally, the new hydrationCapacity property is added.

The new HikingBackpack class can also be extended with new methods. That's done the same way as before:

// Method to check the hydration level.
  checkHydration() {
    if (this.hydrationCapacity > 0) {
      console.log(`You have ${this.hydrationCapacity} liters of water left.`);
    } else {
      console.log("Time to refill your water!");
    }
  }
You can also override methods from the parent class by defining a new method with the same name, calling in the parent method with the super keyword, and then adding new functionality:

toggleLid(lidStatus) {
    super.toggleLid(lidStatus); // Call the parent method
    if (lidStatus) {
      console.log("Your hiking backpack lid is open. Remember to check to make sure the hydration pack is inserted.");
    } else {
      console.log("Your hiking backpack lid is closed. Remember to check to make sure the hydration pack is inserted.");
    }
  }
Here's the full code for the extended HikingBackpack class:

class HikingBackpack extends Backpack {
  constructor(
    name,
    volume,
    color,
    pocketNum,
    strapLengthL,
    strapLengthR,
    lidOpen,
    hydrationCapacity
  ) {
    // Initialize the parent class properties
    super(name, volume, color, pocketNum, strapLengthL, strapLengthR, lidOpen);
    // New property specific to HikingBackpack
    this.hydrationCapacity = hydrationCapacity; // Capacity in liters
  }

  // Method to check the hydration level and alert if it needs refilling
  checkHydration() {
    if (this.hydrationCapacity > 0) {
      console.log(`You have ${this.hydrationCapacity} liters of water left.`);
    } else {
      console.log("Time to refill your water!");
    }
  }

  // Extend or override methods from the parent class if necessary
  // For example, adding extra functionality when the lid is toggled
  toggleLid(lidStatus) {
    super.toggleLid(lidStatus); // Call the parent method
    if (lidStatus) {
      console.log(
        "Your hiking backpack lid is open. Remember to check to make sure the hydration pack is inserted."
      );
    } else {
      console.log(
        "Your hiking backpack lid is closed. Remember to check to make sure the hydration pack is inserted."
      );
    }
  }
}
Concurrency: A single chef multitasking between several dishes.
Parallelism: Multiple chefs working on separate dishes simultaneously.

1. Using Promises for Concurrency
Promises are one of the simplest ways to achieve concurrency in TypeScript.

const fetchData = (url: string) => {
  return new Promise<string>((resolve) => {
    setTimeout(() => resolve(`Data from ${url}`), 1000);
  });
};

const main = async () => {
  console.log('Fetching data concurrently...');
  const data1 = fetchData('https://api.example.com/1');
  const data2 = fetchData('https://api.example.com/2');

  const results = await Promise.all([data1, data2]);
  console.log(results); // ["Data from https://api.example.com/1", "Data from https://api.example.com/2"]
};
main();

Explanation:
Promise.all allows both fetch operations to run concurrently, saving time. 2. Concurrency with Async/Await async/await simplifies promise chaining while maintaining the asynchronous nature.

async function task1() {
  console.log("Task 1 started");
  await new Promise((resolve) => setTimeout(resolve, 2000));
  console.log("Task 1 completed");
}

async function task2() {
  console.log("Task 2 started");
  await new Promise((resolve) => setTimeout(resolve, 1000));
  console.log("Task 2 completed");
}

async function main() {
  console.log("Concurrent execution...");
  await Promise.all([task1(), task2()]);
  console.log("All tasks completed");
}
main();

Parallelism in TypeScript
While JavaScript doesn’t natively support multi-threading, Web Workers and Node.js Worker Threads enable parallelism. These features leverage separate threads to handle computationally expensive tasks.

1. Web Workers for Parallelism
In browser environments, Web Workers execute scripts in a separate thread.

// worker.ts
addEventListener('message', (event) => {
  const result = event.data.map((num: number) => num * 2);
  postMessage(result);
});
// main.ts
const worker = new Worker('worker.js');

worker.onmessage = (event) => {
  console.log('Result from worker:', event.data);
};

worker.postMessage([1, 2, 3, 4]);


2. Node.js Worker Threads
For server-side applications, Node.js provides worker_threads.

// worker.js
const { parentPort } = require('worker_threads');
parentPort.on('message', (data) => {
  const result = data.map((num) => num * 2);
  parentPort.postMessage(result);
});
// main.js
const { Worker } = require('worker_threads');

const worker = new Worker('./worker.js');
worker.on('message', (result) => {
  console.log('Worker result:', result);
});
worker.postMessage([1, 2, 3, 4]);
Patterns for Effective Concurrency and Parallelism
1. Task Queues for Managing Concurrency
When dealing with many tasks, task queues ensure controlled execution.

class TaskQueue {
  private queue: (() => Promise<void>)[] = [];
  private running = 0;
  constructor(private concurrencyLimit: number) {}

  enqueue(task: () => Promise<void>) {
    this.queue.push(task);
    this.run();
  }

  private async run() {
    if (this.running >= this.concurrencyLimit || this.queue.length === 0) return;

    this.running++;
    const task = this.queue.shift();
    if (task) await task();
    this.running--;
    this.run();
  }
}

// Usage
const queue = new TaskQueue(3);
for (let i = 0; i < 10; i++) {
  queue.enqueue(async () => {
    console.log(`Task ${i} started`);
    await new Promise((resolve) => setTimeout(resolve, 1000));
    console.log(`Task ${i} completed`);
  });
}

2. Load Balancing with Worker Pools
Worker pools efficiently distribute tasks across multiple workers.

import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';

if (isMainThread) {
  const workers = Array.from({ length: 4 }, () => new Worker(__filename));
  const tasks = [10, 20, 30, 40];
  workers.forEach((worker, index) => {
    worker.postMessage(tasks[index]);
    worker.on('message', (result) => console.log('Result:', result));
  });
} else {
  parentPort.on('message', (task) => {
    parentPort.postMessage(task * 2);
  });
}
Challenges and Solutions
1. Debugging Asynchronous Code

Use tools like async_hooks in Node.js to trace async operations.
Use IDEs that support debugging async/await code.
2. Error Handling

Wrap promises in try/catch blocks or use .catch() with Promise.all.
3. Race Conditions
Avoid shared state or use locking mechanisms.

Best Practices for Concurrency and Parallelism
1. Prioritize Asynchronous I/O: Avoid blocking the main thread for I/O-heavy operations.
2. Use Worker Threads for CPU-Intensive Tasks: Offload heavy computations to worker threads or Web Workers.
3. Limit Concurrency: Use task queues or libraries like p-limit to control concurrency levels.
4. Leverage Libraries: Use libraries like Bull for task queues or Workerpool for worker thread management.
// Shortcode [fellow_intern type='']

function fellow_intern ( $atts, $content = null) {
    $today = date('Ymd');
	$atts = shortcode_atts(
        array(
            'type' => '',
            'number' => '-1',
        ),
        $atts,
        'fellow_intern'
    );
    $args = array(
        'post_type' => 'fellow-intern',
		'posts_per_page' => -1,
        'post_status' => 'publish',
        'orderby' => 'date',
        'order' => 'ASC',
    );

	if( !empty( $atts['type'] ) ) {
		$args['tax_query'] = array(
			array(
				'taxonomy' => 'fellow-type',
				'field' => 'slug',
				'terms' => $atts['type'],
            )
		);
	}

    $fellow_query = new WP_Query($args);

    ob_start();
    if($fellow_query->have_posts()) { ?>

    <div class="fellows-wrapper">

    <?php

    while ($fellow_query->have_posts()) {
    $fellow_query->the_post(); ?>

    <div class="fellow-inner">
		<!-- Thumbnail -->
		<div class="fellow-img">
			<?php if ( has_post_thumbnail() ) { the_post_thumbnail('full'); } ?>
		</div>
		<div class="fellow-content">
			<!-- Title -->
			<h3><?php echo the_title(); ?></h3>
			<!-- Details -->
			<div class="fellow-details">
				<?php echo the_content(); ?>
			</div>
		</div>
	</div>

    <?php }
    wp_reset_postdata();
    ?>
    </div>

    <?php
    } else { ?>
        <div>No fellows found</div>
    <?php }
    return ob_get_clean();
}
add_shortcode('fellow_intern', 'fellow_intern');
// Array to store active notes for latch mode
reg activeNotes = [];

// Variable to toggle latch mode
reg isLatchEnabled = false;

//To limit the number of last notes to latch
const var lastEventsLimit = 2

reg activeNotes = [];
// Variable to toggle latch mode
reg isLatchEnabled = false;
const var latchToggle =  Content.getComponent("LatchToggle");

 // Function to reset latched notes (e.g., on toggle off)
 inline function resetLatchedNotes()
 {
	if ( !activeNotes.length )
	{
		return;
	}
	
	for ( n=0 ; n < activeNotes.length ; n++)
	{
		Synth.noteOffByEventId(Synth.playNote(activeNotes[n],1));
	};
    activeNotes.clear();
 }
 
 inline function onLatchToggleControl(component, value)
 {
 	if (value)
     {
         latchToggle.set("text", "Latch On");
         isLatchEnabled = true;
     }
     else
     {
         latchToggle.set("text", "Latch Off");
         isLatchEnabled = false;
         resetLatchedNotes();
     }
 };
 
 Content.getComponent("LatchToggle").setControlCallback(onLatchToggleControl);


// Function to handle Note On events
function onNoteOn()
{
    if (isLatchEnabled)
    {
        // Check if the note is already latched
        if (activeNotes.length > lastEventsLimit )
        {
			//Synth.noteOffByEventId(Synth.playNote(activeNotes[0],1));
			resetLatchedNotes();
			activeNotes = [];
            // Add the note to the active notes array
            activeNotes.push(Message.getNoteNumber());
           
        } else {
	        activeNotes.push(Message.getNoteNumber());
        }
    }
}

// Function to handle Note Off events
function onNoteOff()
{
    if (isLatchEnabled)
     	Message.ignoreEvent(true);
}
HiseSnippet 1011.3oc2W80aaaCDmx1ZX1cIXcnXXOJTrGT.JBr2RxFvdnNwwtvX0IFQoc6kgBF4y1DghTihJaFE8KR+FzuE8iTeputcjRpVpUoKyXcXcxOwi2e9wi+t6nmpjgPRhTQbZe9pXf37YtAqD5kCVRYBx3iINa6NglnAkWlniVESSRfYDGmlOvHvocKh86U2+HJmJBg0hHjGKYgvCYQL8ZoS6+iLNeDcFbNKpj160ebnTLPxkoHdZ51kDSCujt.NgZTqgKw4SFNiokp.MUCIDmVGImsJXo72DY5+XVB6BNXVziDfNJS7HIelAwFojAKY7YSKN2IDhi6z0YglYYg63NgMi8F4qyFetcCu0VTNe3znJ7ZVAd8JCutkfWMPxoDjZkAoa6FDpXw506XvysbGKvKm4TLsWFJY5RZ7bG2ARTCgd2H5kvHEt3MV32a+t2ya+t67Ca0w7iI3LA3MOUDpYRgmTbTpVKE8LtPI49gxnXo.c187thxSgc1pyS2piG9wl64WHpsQfkEsaLmt5DoF7O.CzA6YBTafm.4JMTr.C3tTN2nTxoym6aT4YV7Tf6EfdPQb8uaNht6N6lXjaw0.zAWfTE+2FvFmU5zXBxoB+c57zNs67rNdu8VlvWyd4NiCpZ21PhUuOC8EoQW.phbVgh3MaU5h60SWJylCyxKkTTJFKX5SiAw0wwI4ISC0JGUnpZKwZ6bhUVpivP9Sa277HwB4xEzjGM9XplV3HzmXbhAklYNBNGCWgE7YL11tGCIWpkwVcyuAwi4MHr+95P52eU4ErjIxHzOTEJ1oA4cKTvRT4rTNUWst0zrJeC71oRwhofPjvzqJ2L6erh4aJDus6TlNbY8XrQMXDuC9Pfw7Vfa4Nb9bHTuFfsbG8yeX52UN7amE9a4FfsFrcQrA+Ksq89I5Uf2C.AnLIudW23nW95e4E2zwQw23wQmFpwvethJRhkIUbb.DwNGI3IkE9nDrgK7qmYtMKKefjppcqWc+Q3grVaBn5TkkVbXjLUnqPCZ99FK1aCGK15+biE+HnXuxj61EXLfEEygghq.N1qzhwu.aNNmlx0ERqxkmHEx3kRAKr7E8YfVwVr.TkwdsGnC0Zbf3ZI2o+Y.GnkIsec+GhjMpBySvFlK5829UL0de8UtYv0yT.58waS5l++tI8YxTMSrXBEIg3.Z2SRiBvdig.Fcg.eVGJCmHaL0ttqYcVyQwL6h+.+x2rmYsS9l8J17ekXDQCUxmDl8LHCO8SsRvysv9GMZi+iGbsWMu9IB6x8jvvpt5cL7a1TC+1M0v81TC2eSM7fM0vuaSM76+qMzLD5vTsLJqzjPlLcn80pNNCETjkaqHH+YqFx.9
HiseSnippet 1614.3oc6XssaabCDcWauAQJ8VZCJ5i7gVDYGGYImKM.oEw2jSEpchfkiSAJJBn2kRKqWQtkjqsUK5+X+TxeP6gjRVqRTbbMZJPJpdvVKmYHOyLmYFtpiRFyzZoJHrx9CyYAgePT2gBS5loTtHn8VAgebz5EFYelfonFVRvFCyoZM9RX37O1pTXkEBbed4i1flQEwrIKEDbfjGy1gOfalrZm09ddV11zD197Akz9tq0NVJ1TlIK.flOpQPNM9HZe1SnV0lKJH7JsR3FopqAXQGDtvFxjgcSkmH75e.WyOLiYenYPWrQ9k2VlkXQrc0fMS4YIcF635ffvnNSBCy6CC2HZWdB+r0mDN9Dm.xDKJGOBmaZ3M+TvqYY30nD7lAjBKAoE7P55QciU7byDIV7bsn1BCS0ihvdYn30MXtqFFsoDZHL0GPOhssBOblE0teiFKSveV7gUqtxJjNYzgDpHgjh.FgRDRCqNYeXGdHSJOhPMjWAEMI8jJhIkQhkIr58JDwFtTPjhm.qepn1hU+spUp96UIupnd8loLKbUxrLlZlhsTF04YXMQwfCYpkIGSyJXmoHhiSmbhdyImxbmXezqjhRQaA27zbl3MwnBFExw2dV6snFpMiNZMnWNSY3VHDtE6XTd3yuUh1hoOxHyQAxqk7AsSlTjQMSyEsEfiDfXvTD.aRVn4lgkKP+GifdQg30i5vMwoyFiyMCLhH06BLNpr9CiZ0qGK1LAfKDs8O7toFt7w+Q9i+ZQc4BlqAq6v+b2yjmSOlQdruCKJnNmVr+wEsEa9EtE6SiM332WQE5bodpMtKa.eeovFElr3yznIB6W1ylMKu9lRpZlhd4i1FN4LsoK0Tnbzh0GHKDlonAyeds5adIa0uv6ws5+rQqNAQMmYK+VWIZkkVhreJWSzdKNAjARtq6NIALEQAWmxRHwoRUBjZRg.PLzFpvPRXPypUrCBzvizjgxBLR3DhQBYzLuA1V9ZSQ7QtwDjbkD96.rLlQPUbMSSRYJV8pKsR0pt8FcjU9Mm7sjUWsw8Z7vxRnnQ9wL6nAMj+i+jelzNLyM0jBscDz.a9HiqMKSNIkGmRfGdHUyioYYVWqG+TVxs07eEJqT3XzHCwE8IMW8ADNZ1zmo7iEzUwTqZbbNMdHgS9Fxcv+t0sVDd8DTTOuPmVqknO3u0iULjosLhc..ps3nQltnrfcBY8NsIVb3i0LAEQCWLJS1mGSpc3P358nEYFB25Qxd8Pf6jEsaRWlAphMBA3dzLquhXOh52DaEhtn99UB2550qW00HotlY1lepeX658vj8wCWMJL9Cn7MLRNSB3RhQHXWPlvsrp2mYaLJDrrZvtQJHlVA6N7D2.1R5b7z5b.CKit5NMpVAN3yY2TAWPAjfxcjPrdC6XLNjzdKqWCh2PGshKHMtMRWNybwDPAKvsQ5irBnAHxJK5mRTR4.2MOFPECGQcFEYFiJdxoSiqV1CrcRsEIekkQbF78zfptib7kYz1K8H64g.6T5fbjNOgYSH79BoxmPT1pA6oB2b7A4E6NqwofxAgwTRq4VdyYQA34ThlkSs2ylra6sZ6n5NDwnfr61DWslCWrQUuvN7OPrcgQYtUz.6ptS.peaKUafGcUqX48Tg6zlvzAuGk6VpzA1piZHzsLwSunIIiXMwKCxvsrkIjkH2A2uZYewrsT3btd2EMYbtQPmu+cncBxAjT67xRdqOu6673jcHiIbV.ZkBuzR4nAfWchEftNZX2Rj10Qsqh4rgdnrv3T2fQmXGFjau1qsz9PHHi4E5z8sTAtnui.NAtQS9Y4g0Om3ueuDdS2X333CRK8KkVd8f8+ee42Ctu7TS4qLFic411JsDGiFlXEKF+T3UtoDiWc5Y76JEx7TofGW9tR6wLJdeLbqL1moCstwfWodxJ2Xs8XYLZ4688kqsCl2QUHNwtjwhl+suwyLyWeQjGtDKGl79664L++seOm8P+RLQaWJHgmh9D35AcwqWDyFcYBauiv4rU49maXe1+9EhD2C+I9LRXS6ygiD1brv+UNiAzXk7Ew9thVd5Ucq.+V398mpDsq8YRy.Wmxx4R6ESeQb7za0qY3pWVCuyk0v6dYM7dWVCu+k0vu9xZ3Cd6FZu0t8WwbfuzLHX2NsbiYBCa4tntqhH3u.2gPQ2
const {data} = await axios.post('https://httpbin.org/post', {
    firstName: 'Fred',
    lastName: 'Flintstone',
    orders: [1, 2, 3],
    photo: document.querySelector('#fileInput').files
  }, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }
)
add_filter( 'woocommerce_loop_add_to_cart_link', 'custom_add_to_cart_button_text_archives', 10, 2 );

function custom_add_to_cart_button_text_archives( $link, $product ) {
    if ( $product->is_type( 'variable' ) ) {
        // Zmiana tekstu przycisku dla produktów zmiennych
        $link = str_replace( 'ADD TO CART', 'SELECT', $link );
    }
    return $link;
}
#envelope{
margin: 150px;
position: relative;
width: 280px;
height: 180px;
borer-bottom-lefgt-radius:6px;
borer-bottom-lefgt-radius:6px;
margin-left: auto;
margin-left: auto;
top: 150px;
backgorund-color: #f9c5c8
box-shadow: 0 4px 20px rgba(0,0,0,,0.2)
}
const getWeekOfYear = (date: Date): number => {
  const startOfYear = new Date(date.getFullYear(), 0, 1);
  const days = Math.floor(
    (date.getTime() - startOfYear.getTime()) / (24 * 60 * 60 * 1000)
  );
  return Math.ceil((days + startOfYear.getDay() + 1) / 7);
};
<script>
    window.onscroll = function() {
        var button = document.getElementById("scrollToTop");
        if (document.body.scrollTop > 800 || document.documentElement.scrollTop > 800) {
            button.style.display = "block";
        } else {
            button.style.display = "none";
        }
    };
</script>
// config.xml
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.example.fingerprintauth" version="1.0.0" xmlns="http://www.w3.org/ns/widgets">
    <name>FingerprintAuth</name>
    <description>Aplicación de autenticación por huella digital</description>
    <author email="dev@example.com" href="http://example.com">
        Tu Nombre
    </author>
    <content src="index.html" />
    <plugin name="cordova-plugin-fingerprint-aio" spec="^4.0.0" />
    <access origin="*" />
</widget>

// www/index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Autenticación por Huella Digital</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="container">
        <h1>Bienvenido</h1>
        <button id="authenticateButton">Autenticar con Huella Digital</button>
        <p id="status"></p>
    </div>
    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
</body>
</html>

// www/css/style.css
.container {
    padding: 20px;
    text-align: center;
}

button {
    padding: 15px 30px;
    font-size: 16px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 5px;
    margin: 20px 0;
    cursor: pointer;
}

#status {
    margin-top: 20px;
    font-weight: bold;
}

// www/js/index.js
document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {
    document.getElementById('authenticateButton').addEventListener('click', authenticate);
    
    // Verificar si el dispositivo soporta la autenticación biométrica
    Fingerprint.isAvailable(function(result) {
        // result contiene el tipo de biometría disponible
        console.log("Tipo de biometría: " + result);
    }, function(error) {
        console.error("Error al verificar biometría: " + error);
        document.getElementById('status').textContent = 
            "Tu dispositivo no soporta autenticación por huella digital";
    });
}

function authenticate() {
    Fingerprint.show({
        title: 'Autenticación Biométrica', // título opcional
        subtitle: 'Por favor, autentícate usando tu huella digital', // subtítulo opcional
        description: 'Toca el sensor de huella digital', // descripción opcional
        fallbackButtonTitle: 'Usar alternativa', // título del botón alternativo
        disableBackup: false // permitir autenticación alternativa
    }, successCallback, errorCallback);
}

function successCallback() {
    document.getElementById('status').textContent = 
        "¡Autenticación exitosa!";
    // Aquí puedes agregar la lógica para después de una autenticación exitosa
}

function errorCallback(error) {
    document.getElementById('status').textContent = 
        "Error en la autenticación: " + error.message;
}
function sayHi() {
  alert( this.name );
}
cordova plugin add cordova-plugin-browsersync-gen2

cordova run browser --live-reload
cordova run android --live-reload
cordova run ios --live-reload
cordova run --live-reload (will run project using all platforms)

cordova serve --livre-reload
Why Choose Dappfort?
  
Tailored Solutions: Dappfort works closely with clients to understand their unique needs, providing bots that are custom-built to fit specific trading goals and risk profiles.
Scalability: Whether you're a small trader or a large financial institution, Dappfort’s bots are built to scale, handling large volumes of trades across multiple exchanges with ease.

Advanced Analytics: Dappfort’s bots come with built-in analytics tools that track and display performance metrics, helping users make data-driven decisions and optimize strategies over time.

Ongoing Support: Dappfort provides continuous support and updates, ensuring that the bots remain effective and secure as market conditions evolve.

Whether you're an individual trader looking to automate your personal portfolio or a business seeking a fully integrated trading solution, Dappfort's crypto trading bot development company are designed to meet the needs of today's fast-paced cryptocurrency markets.

For more information or to get started, visit Dappfort's website or contact their team for a personalized consultation.
// Service Form PS

import com.onresolve.jira.groovy.user.FieldBehaviours
import com.onresolve.jira.groovy.user.FormField

// Get the specific field
FormField myField = getFieldById("customfield_xxxx") // Vendor Dev Status

// Set the tooltip description with AUI icon styling
myField.setLabel("System Sales Catalog Product Code <span class='aui-icon aui-icon-small aui-iconfont-info' title='Use this field to indicate the product code associated with the system, as stated in the Sales Catalog for this system' style='cursor: help; margin-left: 5px;'></span>")


mkdir backend
cd backend

mkdir config
New-Item -ItemType File -Path ./config/db.js

mkdir controllers
New-Item -ItemType File -Path ./controllers/authController.js

mkdir models
New-Item -ItemType File -Path ./models/User.js

mkdir routes
New-Item -ItemType File -Path ./routes/authRoutes.js

mkdir middleware
New-Item -ItemType File -Path ./middleware/authMiddleware.js

New-Item -ItemType File -Path ./server.js
New-Item -ItemType File -Path ./package.json
New-Item -ItemType File -Path ./.env







echo ".env" >> .gitignore
// Sample string that represents a combination of small, medium, and large code points.
// This sample string is valid UTF-16.
// 'hello' has code points that are each below 128.
// '⛳' is a single 16-bit code units.
// '❤️' is a two 16-bit code units, U+2764 and U+FE0F (a heart and a variant).
// '🧀' is a 32-bit code point (U+1F9C0), which can also be represented as the surrogate pair of two 16-bit code units '\ud83e\uddc0'.
const validUTF16String = 'hello⛳❤️🧀';

// This will not work. It will print:
// DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.
try {
  const validUTF16StringEncoded = btoa(validUTF16String);
  console.log(`Encoded string: [${validUTF16StringEncoded}]`);
} catch (error) {
  console.log(error);
}
var docWidth = document.documentElement.offsetWidth;

[].forEach.call(
	document.querySelectorAll('*'),
	function (el) {
		if (el.offsetWidth > docWidth) {
			console.log(el);
		}
	}
);
<!DOCTYPE html>
 
<html>
 
<head>
<!-- Link to external CSS stylesheet -->
<link rel="stylesheet" href="style.css">
<title> Game Zone</title>
</head>
 
<body>
 
<div class="gameon">
<!-- Website logo image -->  
<img src="websitelogo.png" width="700" height="400" style="margin: 0 auto; display: flex;">
 
<div style="position: absolute; top: 10%; left: 50%; transform: translate(-50%, -50%);">
<!-- Website name text -->
<span style="font-size: 30px; font-weight: bold; color: black;">GAMEZONE</span>
 
</div>
 
<!-- Website Mission statement -->
<i style="font-size: 25px; margin-top: 10px; ">"Our mission is to reignite the joy and nostalgia in the arcade experience"</i>
 
<marquee scrollamount="8"
direction="left"
behavior="scroll">
<!-- Announcement marquee -->  
<h1>Attention Customers, Lightning Deal On Sale Now 50% Off Everything!!!
</marquee>
 
<div style="position: relative; left: 50px; top: 100px;">
</div>
 
<div style="position: relative; top: -20px; font-size: 20px;text-align: left;"
<!-- How to create account instructions -->
<h1>How To Create a Account</h1>
 
<ol>
<li>Click on Sign In (In Menu)</li>
<li>Enter A Email </li> 
<li>Enter Your Password and then you're in!</li>
</ol>
 
</div>
 
<div style="position: relative; top: -1px;font-size: 9px;text-align: left;" 
<!-- Website disclaimer -->
<h1>Disclaimer</h1>  
 
<li>All purchases are Non-Refundable</li>
<li>Points can not be transferred across accounts</li>  
<li>Prices may be changed at any time without further notice</li>
<li>We have the right to refuse service to anyone</li>
</ul>
 
</div>
 
  <nav class="dropdown">
 
    <!-- Website menu -->
    
    <button class="dropbtn">Menu</button>
 
    <div class="dropdown-content">
 
      <a href="https://index-1.hebbaraarush105.repl.co/">HomePage</a>
 
      <a href="https://contactushtml.hebbaraarush105.repl.co/">About Us</a>
 
      <a href="https://arcade-games.hebbaraarush105.repl.co/">Arcade Games</a>
 
      <a href="https://createaccount.hebbaraarush105.repl.co/">Sign In</a>
 
      <a href="https://f78636c2-61d0-4bb2-ad3d-e31e1595f7a0-00-10um3h265swk6.worf.replit.dev/"><h1>Schedule a Visit</h1></a>
      </div>
    
 
  </nav>
 
 
 
<div class="footer">
<!-- Website footer with copyright and links -->
© 2023 Aarush and Siddharth. All rights reserved.  
</div>
 
<div class="footer-dropdown">
 
<a href="#">Credits</a>   
 
<div class="footer-dropdown-content">  
 
<!-- Links to external game info pages -->
<a href="https://www.canva.com/design/DAF0F9nX2D8/IRk\_pak6JC0BX3mrlifWDA/edit?utm\_content=DAF0F9nX2D8&utm\_campaign=designshare&utm\_medium=link2&utm\_source=sharebutton" target="\_blank">CanvasDesign</a>
 
<a href="https://en.wikipedia.org/wiki/Donkey\_Kong\_%28character%29" target="\_blank">DonkeyKong</a>  
 
<a href="https://poki.com/en/g/crossy-road" target="\_blank">CrossyRoad</a>
 
<a href="https://www.amazon.com/Arcade-Arcade1Up-PAC-MAN-Head-Head-Table/dp/B09B1DNQDQ?source=ps-sl-shoppingads-lpcontext&ref\_=fplfs&psc=1&smid=A1DXN92KCKEQV4" target="\_blank">PacMan</a>
 
<a href="https://en.wikipedia.org/wiki/Street\_Fighter\_II" target="\_blank">Street Fighter</a>  
 
<a href="https://www.thepinballcompany.com/product/space-invaders-frenzy-arcade-game/" target="\_blank">SpaceInvaders</a>  
 
<a href="https://www.walmart.com/ip/Arcade1Up-PONG-Head-to-head-H2H-Gaming-Table/974088112/" target="\_blank">Pong</a>
 
</div>
 
 
 
</body>
 
</html>
Multiplier
CSS custom properties are excellent when it comes to updating multiple elements at once. By injecting a --text-multiplier variable into the text elements' size, you can increase/decrease them all at a specific breakpoint by editing the variable.
 
// Method 3
h1 {
  font-size: calc(2em * var(--text-multiplier, 1));
}
 
p {
  font-size: calc(1em * var(--text-multiplier, 1));
}
 
@media (min-width: 48rem) {
  :root {
    --text-multiplier: 1.25;
  }
}
//Pictures
 <picture>
       <source
    media="(max-width:599px) and (prefers-color-scheme: light)"
    srcset="images/bg-mobile-light.jpg"
    />
      <source
    media="(max-width:599px) and (prefers-color-scheme: dark)"
    srcset="images/bg-mobile-dark.jpg"
    />
      <source
    media="(min-width:600px) and (prefers-color-scheme: light)"
    srcset="images/bg-desktop-light.jpg"
    />
      <source
    media="(min-width:600px) and (prefers-color-scheme: dark)"
    srcset="images/bg-desktop-dark.jpg"
    />
      <img
    src="images/bg-mobile-light.jpg"
    aria-hidden="true"
    class="background-img"
    alt=""
    />
</picture>
 
//CSS
@media (prefers-color-scheme: dark) {
  :root {
    --color-primary: #25273c;
    --color-primary-text: #e4e5f1;
    --color-secondary-text: #cacde8;
    --color-deleted-text: #4d5067;
    --color-circle: #777a92;
    --color-background: #161722;
    --color-background-hover: #1c1e35;
  }
}
 
@media (prefers-color-scheme: light) {
  :root {
    --color-white: #ffffff;
    --color-primary: #ffffff;
    --color-primary-text: #494c6b;
    --color-secondary-text: #9394a5;
    --color-light-text: #d4d4d4;
    --color-active: #3a7cfd;
    --color-circle: #d6d6d6;
    --color-background: #fafafa;
    --color-background-hover: #ebebeb;
    --color-background-modal: rgba(73, 76, 107, 0.6);
    --color-error: #cd1237;
  }
}
 
 
//JS
let dark = window.matchMedia('(prefers-color-scheme: dark)').matches;
//Show which prefers-color-scheme user has before the page loads
window.matchMedia('(prefers-color-scheme: dark)');
if (dark) {
  //Do something
} else {
  //Do something
}
/* ==========================================================================
Animation System by Neale Van Fleet from Rogue Amoeba
========================================================================== */
.animate {
  animation-duration: 0.75s;
  animation-delay: 0.5s;
  animation-name: animate-fade;
  animation-timing-function: cubic-bezier(.26, .53, .74, 1.48);
  animation-fill-mode: backwards;
}
 
/* Fade In */
.animate.fade {
  animation-name: animate-fade;
  animation-timing-function: ease;
}
 
@keyframes animate-fade {
  0% { opacity: 0; }
  100% { opacity: 1; }
}
 
/* Pop In */
.animate.pop { animation-name: animate-pop; }
 
@keyframes animate-pop {
  0% {
    opacity: 0;
    transform: scale(0.5, 0.5);
  }
  100% {
    opacity: 1;
    transform: scale(1, 1);
  }
}
 
/* Blur In */
.animate.blur {
  animation-name: animate-blur;
  animation-timing-function: ease;
}
 
@keyframes animate-blur {
  0% {
    opacity: 0;
    filter: blur(15px);
  }
  100% {
    opacity: 1;
    filter: blur(0px);
  }
}
 
/* Glow In */
.animate.glow {
  animation-name: animate-glow;
  animation-timing-function: ease;
}
 
@keyframes animate-glow {
  0% {
    opacity: 0;
    filter: brightness(3) saturate(3);
    transform: scale(0.8, 0.8);
  }
  100% {
    opacity: 1;
    filter: brightness(1) saturate(1);
    transform: scale(1, 1);
  }
}
 
/* Grow In */
.animate.grow { animation-name: animate-grow; }
 
@keyframes animate-grow {
  0% {
    opacity: 0;
    transform: scale(1, 0);
    visibility: hidden;
  }
  100% {
    opacity: 1;
    transform: scale(1, 1);
  }
}
 
/* Splat In */
.animate.splat { animation-name: animate-splat; }
 
@keyframes animate-splat {
  0% {
    opacity: 0;
    transform: scale(0, 0) rotate(20deg) translate(0, -30px);
    }
  70% {
    opacity: 1;
    transform: scale(1.1, 1.1) rotate(15deg);
  }
  85% {
    opacity: 1;
    transform: scale(1.1, 1.1) rotate(15deg) translate(0, -10px);
  }
 
  100% {
    opacity: 1;
    transform: scale(1, 1) rotate(0) translate(0, 0);
  }
}
 
/* Roll In */
.animate.roll { animation-name: animate-roll; }
 
@keyframes animate-roll {
  0% {
    opacity: 0;
    transform: scale(0, 0) rotate(360deg);
  }
  100% {
    opacity: 1;
    transform: scale(1, 1) rotate(0deg);
  }
}
 
/* Flip In */
.animate.flip {
  animation-name: animate-flip;
  transform-style: preserve-3d;
  perspective: 1000px;
}
 
@keyframes animate-flip {
  0% {
    opacity: 0;
    transform: rotateX(-120deg) scale(0.9, 0.9);
  }
  100% {
    opacity: 1;
    transform: rotateX(0deg) scale(1, 1);
  }
}
 
/* Spin In */
.animate.spin {
  animation-name: animate-spin;
  transform-style: preserve-3d;
  perspective: 1000px;
}
 
@keyframes animate-spin {
  0% {
    opacity: 0;
    transform: rotateY(-120deg) scale(0.9, .9);
  }
  100% {
    opacity: 1;
    transform: rotateY(0deg) scale(1, 1);
  }
}
 
/* Slide In */
.animate.slide { animation-name: animate-slide; }
 
@keyframes animate-slide {
  0% {
    opacity: 0;
    transform: translate(0, 20px);
  }
  100% {
    opacity: 1;
    transform: translate(0, 0);
  }
}
 
/* Drop In */
.animate.drop { 
  animation-name: animate-drop; 
  animation-timing-function: cubic-bezier(.77, .14, .91, 1.25);
}
 
@keyframes animate-drop {
0% {
  opacity: 0;
  transform: translate(0,-300px) scale(0.9, 1.1);
}
95% {
  opacity: 1;
  transform: translate(0, 0) scale(0.9, 1.1);
}
96% {
  opacity: 1;
  transform: translate(10px, 0) scale(1.2, 0.9);
}
97% {
  opacity: 1;
  transform: translate(-10px, 0) scale(1.2, 0.9);
}
98% {
  opacity: 1;
  transform: translate(5px, 0) scale(1.1, 0.9);
}
99% {
  opacity: 1;
  transform: translate(-5px, 0) scale(1.1, 0.9);
}
100% {
  opacity: 1;
  transform: translate(0, 0) scale(1, 1);
  }
}
 
/* Animation Delays */
.delay-1 {
  animation-delay: 0.6s;
}
.delay-2 {
  animation-delay: 0.7s;
}
.delay-3 {
  animation-delay: 0.8s;
}
.delay-4 {
  animation-delay: 0.9s;
}
.delay-5 {
  animation-delay: 1s;
}
.delay-6 {
  animation-delay: 1.1s;
}
.delay-7 {
  animation-delay: 1.2s;
}
.delay-8 {
  animation-delay: 1.3s;
}
.delay-9 {
  animation-delay: 1.4s;
}
.delay-10 {
  animation-delay: 1.5s;
}
.delay-11 {
  animation-delay: 1.6s;
}
.delay-12 {
  animation-delay: 1.7s;
}
.delay-13 {
  animation-delay: 1.8s;
}
.delay-14 {
  animation-delay: 1.9s;
}
.delay-15 {
  animation-delay: 2s;
}
 
@media screen and (prefers-reduced-motion: reduce) {
  .animate {
    animation: none !important;
  }
}
var t0 = performance.now();
 
for (let i = 0; i < 10000; i++) {   
    // Do stuff here 
}  
 
// Do some other stuff here
 
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " ms.")
// config.xml
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.example.fingerprintauth" version="1.0.0" xmlns="http://www.w3.org/ns/widgets">
    <name>FingerprintAuth</name>
    <description>Aplicación de autenticación por huella digital</description>
    <author email="dev@example.com" href="http://example.com">
        Tu Nombre
    </author>
    <content src="index.html" />
    <plugin name="cordova-plugin-fingerprint-aio" spec="^4.0.0" />
    <access origin="*" />
</widget>

// www/index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Autenticación por Huella Digital</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="container">
        <h1>Bienvenido</h1>
        <button id="authenticateButton">Autenticar con Huella Digital</button>
        <p id="status"></p>
    </div>
    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
</body>
</html>

// www/css/style.css
.container {
    padding: 20px;
    text-align: center;
}

button {
    padding: 15px 30px;
    font-size: 16px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 5px;
    margin: 20px 0;
    cursor: pointer;
}

#status {
    margin-top: 20px;
    font-weight: bold;
}

// www/js/index.js
document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {
    document.getElementById('authenticateButton').addEventListener('click', authenticate);
    
    // Verificar si el dispositivo soporta la autenticación biométrica
    Fingerprint.isAvailable(function(result) {
        // result contiene el tipo de biometría disponible
        console.log("Tipo de biometría: " + result);
    }, function(error) {
        console.error("Error al verificar biometría: " + error);
        document.getElementById('status').textContent = 
            "Tu dispositivo no soporta autenticación por huella digital";
    });
}

function authenticate() {
    Fingerprint.show({
        title: 'Autenticación Biométrica', // título opcional
        subtitle: 'Por favor, autentícate usando tu huella digital', // subtítulo opcional
        description: 'Toca el sensor de huella digital', // descripción opcional
        fallbackButtonTitle: 'Usar alternativa', // título del botón alternativo
        disableBackup: false // permitir autenticación alternativa
    }, successCallback, errorCallback);
}

function successCallback() {
    document.getElementById('status').textContent = 
        "¡Autenticación exitosa!";
    // Aquí puedes agregar la lógica para después de una autenticación exitosa
}

function errorCallback(error) {
    document.getElementById('status').textContent = 
        "Error en la autenticación: " + error.message;
}
<!DOCTYPE html> 
<html lang="en"> 
<head> 
  <meta charset="UTF-8"> 
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
  <title>JavaScript Callbacks, Promises, Async/Await</title> 
</head> 
<body> 
  <h1>JavaScript Callbacks, Promises, and Async/Await Demo</h1> 
  <script> 
    // Callback Example 
    function doSomething(callback) { 
      setTimeout(() => { 
        callback("Callback done!"); 
      }, 1000); 
    } 
    doSomething(console.log); 
 
    // Promise Example 
    let promise = new Promise((resolve, reject) => { 
      setTimeout(() => resolve("Promise resolved!"), 1000); 
    }); 
    promise.then(console.log); 
 
    // Async/Await Example 
    async function asyncFunction() { 
      let result = await promise; 
      console.log(result); 
    } 
    asyncFunction(); 
  </script> 
</body> 
</html>
popUpDemo.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Pop-Up Boxes</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin-top: 50px;
        }

        button {
            padding: 10px 15px;
            font-size: 16px;
            margin: 10px;
        }
    </style>
</head>
<body>

    <h1>JavaScript Pop-Up Box Demonstration</h1>
    <button onclick="showAlert()">Show Alert</button>
    <button onclick="showConfirm()">Show Confirm</button>
    <button onclick="showPrompt()">Show Prompt</button>

    <script>
        function showAlert() {
            alert("This is an alert box!");
        }

        function showConfirm() {
            const result = confirm("Do you want to proceed?");
            if (result) {
                alert("You clicked OK!");
            } else {
                alert("You clicked Cancel!");
            }
        }

        function showPrompt() {
            const name = prompt("Please enter your name:");
            if (name) {
                alert("Hello, " + name + "!");
            } else {
                alert("No name entered.");
            }
        }
    </script>

</body>
</html>
import React from 'react';

/**
 * Toggles the presence of a number in the selectedNumbers array state.
 *
 * @param number - The number to toggle in the selection.
 * @param setSelectedNumbers - The state setter function from useState.
 */
const toggleNumber = (
  number: number,
  setSelectedNumbers: React.Dispatch<React.SetStateAction<number[]>>
): void => {
  setSelectedNumbers((prevSelectedNumbers) => {
    if (prevSelectedNumbers.includes(number)) {
      // Number is already selected; remove it from the array
      return prevSelectedNumbers.filter((n) => n !== number);
    } else {
      // Number is not selected; add it to the array
      return [...prevSelectedNumbers, number];
    }
  });
};

// Initialize State in Your Component
const [selectedNumbers, setSelectedNumbers] = useState<number[]>([]);

// Use the toggleNumber Function
// Example usage within a component event handler
const handleNumberClick = (number: number): void => {
  toggleNumber(number, setSelectedNumbers);
};

// Implement in JSX
<button onClick={() => handleNumberClick(5)}>
  {selectedNumbers.includes(5) ? 'Deselect 5' : 'Select 5'}
</button>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Demonstration of Activity LIFE CYCLE Methods"
        android:textColor="@color/design_default_color_error"
        android:textSize="18sp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintVertical_bias="0.5"
        app:layout_constraintHorizontal_bias="0.5"/>
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.ktfile
import android.os.Bundle
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        Toast.makeText(applicationContext,"ONCREATE() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onStart()
    {
        super.onStart()
        Toast.makeText(applicationContext,"ONSTART() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onRestart()
    {
        super.onRestart()
        Toast.makeText(applicationContext,"ONRESTART() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onResume()
    {
        super.onResume()
        Toast.makeText(applicationContext,"ONRESUME() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onPause()
    {
        super.onPause()
        Toast.makeText(applicationContext,"ONPAUSE() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onStop()
    {
        super.onStop()
        Toast.makeText(applicationContext,"ONSTOP() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onDestroy()
    {
        super.onDestroy()
        Toast.makeText(applicationContext,"ONDESTROY() CALLED",Toast.LENGTH_SHORT).show()
    }

}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Demonstration of Activity LIFE CYCLE Methods"
        android:textColor="@color/design_default_color_error"
        android:textSize="18sp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintVertical_bias="0.5"
        app:layout_constraintHorizontal_bias="0.5"/>
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.ktfile
import android.os.Bundle
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        Toast.makeText(applicationContext,"ONCREATE() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onStart()
    {
        super.onStart()
        Toast.makeText(applicationContext,"ONSTART() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onRestart()
    {
        super.onRestart()
        Toast.makeText(applicationContext,"ONRESTART() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onResume()
    {
        super.onResume()
        Toast.makeText(applicationContext,"ONRESUME() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onPause()
    {
        super.onPause()
        Toast.makeText(applicationContext,"ONPAUSE() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onStop()
    {
        super.onStop()
        Toast.makeText(applicationContext,"ONSTOP() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onDestroy()
    {
        super.onDestroy()
        Toast.makeText(applicationContext,"ONDESTROY() CALLED",Toast.LENGTH_SHORT).show()
    }

}
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp
import com.example.myapplication.ui.theme.MyApplicationTheme


class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            Surface(modifier = Modifier.fillMaxSize(),
                color = Color.White

            ) {
                Box(
                    contentAlignment = Alignment.Center,
                    modifier = Modifier.fillMaxSize()
                ){
                    Text(text = "Hello World",
                        color = Color.Red,
                        fontSize = 32.sp
                    )

                }

            }
        }

    }
}
import java.util.*;

public class Graph {
    private int vertices;  // Number of vertices
    private LinkedList<Integer>[] adjList;  // Adjacency list representation
    private int time;  // Time counter for DFS

    // Constructor
    public Graph(int v) {
        vertices = v;
        adjList = new LinkedList[v];
        for (int i = 0; i < v; i++) {
            adjList[i] = new LinkedList<>();
        }
        time = 0;
    }

    // Add an edge to the graph
    public void addEdge(int v, int w) {
        adjList[v].add(w);
        adjList[w].add(v);  // Since the graph is undirected
    }

    // Articulation Point (Art) Algorithm
    public void findArticulationPoints() {
        boolean[] visited = new boolean[vertices];
        int[] dfn = new int[vertices];  // Discovery time of visited vertices
        int[] low = new int[vertices];  // Lowest discovery time reachable
        int[] parent = new int[vertices];  // Parent vertices in DFS
        Arrays.fill(parent, -1);  // Initialize all parents as -1

        // Start DFS from each unvisited node
        for (int i = 0; i < vertices; i++) {
            if (!visited[i]) {
                DFSArt(i, visited, dfn, low, parent);
            }
        }
    }

    private void DFSArt(int u, boolean[] visited, int[] dfn, int[] low, int[] parent) {
        visited[u] = true;  // Mark the current node as visited
        dfn[u] = low[u] = ++time;  // Initialize discovery time and low value
        int childCount = 0;  // Count of children in DFS tree
        boolean isArticulation = false;

        for (int v : adjList[u]) {
            if (!visited[v]) {
                childCount++;
                parent[v] = u;
                DFSArt(v, visited, dfn, low, parent);

                // Check if the subtree rooted at v has a connection back to one of u's ancestors
                low[u] = Math.min(low[u], low[v]);

                // u is an articulation point in two cases:
                // (1) u is not the root and low value of one of its child is more than discovery value of u
                if (parent[u] != -1 && low[v] >= dfn[u]) {
                    isArticulation = true;
                }

                // (2) u is the root of DFS tree and has two or more children
                if (parent[u] == -1 && childCount > 1) {
                    isArticulation = true;
                }
            } else if (v != parent[u]) {
                // Update low value of u for back edge
                low[u] = Math.min(low[u], dfn[v]);
            }
        }

        // If u is an articulation point, print it
        if (isArticulation) {
            System.out.println("Articulation Point: " + u);
        }
    }

    // Construct graph from adjacency matrix
    public static Graph createGraphFromAdjMatrix(int[][] adjMatrix) {
        int n = adjMatrix.length;
        Graph g = new Graph(n);
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {  // Undirected graph, so only check i < j
                if (adjMatrix[i][j] == 1) {
                    g.addEdge(i, j);
                }
            }
        }
        return g;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input the number of vertices
        System.out.print("Enter the number of vertices: ");
        int v = scanner.nextInt();

        // Input the adjacency matrix
        System.out.println("Enter the adjacency matrix:");
        int[][] adjMatrix = new int[v][v];
        for (int i = 0; i < v; i++) {
            for (int j = 0; j < v; j++) {
                adjMatrix[i][j] = scanner.nextInt();
            }
        }

        // Create the graph from adjacency matrix
        Graph g = Graph.createGraphFromAdjMatrix(adjMatrix);

        // Find and print the articulation points
        System.out.println("Articulation Points:");
        g.findArticulationPoints();
    }
}

output1:
Enter the number of vertices: 5
Enter the adjacency matrix:
0 1 1 0 0
1 0 1 1 0
1 1 0 0 0
0 1 0 0 1
0 0 0 1 0
Articulation Points:
Articulation Point: 1
Articulation Point: 3

output2:
Enter the number of vertices: 6
Enter the adjacency matrix:
0 1 1 0 0 0
1 0 1 1 0 0
1 1 0 0 1 0
0 1 0 0 1 1
0 0 1 1 0 1
0 0 0 1 1 0
Articulation Points:
Articulation Point: 2
Articulation Point: 3
<script>
document.addEventListener('click', function (event) {
    if (event.target.closest('a[href*="#"]:not([aria-haspopup="true"])') && event.target.closest('.e-off-canvas[aria-hidden="false"]')) {
        const canvasTrigger = document.querySelector('[href*="off_canvas%3A"]:not([href*="%3Aopen"]');
        if (canvasTrigger) canvasTrigger.click();
    }
});
</script>
// Define the coordinates for the specific point (e.g., the location of interest)
var point = ee.Geometry.Point(90.2611485521762, 23.44690280909043);

// Create a buffer around the point (e.g., 20 kilometers)
var bufferRadius = 20000; // 20 km in meters
var pointBuffer = point.buffer(bufferRadius);

// Create a Landsat 8 Collection 2 Tier 1 image collection for the desired date range
var startDate = '2017-10-01';
var endDate = '2017-10-31';

var landsatCollection2 = ee.ImageCollection('LANDSAT/LC08/C02/T1_TOA')
  .filterBounds(point)
  .filterDate(startDate, endDate);

// Cloud masking function for Landsat
function maskL8Clouds(image) {
  var qa = image.select('QA_PIXEL');
  var cloudMask = qa.bitwiseAnd(1 << 3).eq(0); // Cloud bit is 3rd
  return image.updateMask(cloudMask);
}

// Apply the cloud mask to the collection
var cloudFreeCollection = landsatCollection2.map(maskL8Clouds);

// Print the number of images in the cloud-free collection
var imageCount = cloudFreeCollection.size();
print('Number of cloud-free images in the collection:', imageCount);

// Use JRC Global Surface Water dataset to create a water mask
var waterMask = ee.Image('JRC/GSW1_4/GlobalSurfaceWater').select('occurrence');

// Define water body threshold (e.g., areas with water occurrence > 50% are considered water bodies)
var waterThreshold = 50;
var waterBodies = waterMask.gt(waterThreshold);

// Clip water bodies to the buffer area
var clippedWaterBodies = waterBodies.clip(pointBuffer);

// Mask water bodies in the cloud-free collection
var landOnlyCollection = cloudFreeCollection.map(function(image) {
  return image.updateMask(clippedWaterBodies.not());  // Mask out water bodies
});

// Compute the maximum and minimum temperature across all non-water pixels
var maxTemperature = landOnlyCollection.select('B10').max();
var minTemperature = landOnlyCollection.select('B10').min();

// Convert temperatures from Kelvin to Celsius
var maxTemperatureCelsius = maxTemperature.subtract(273.15);
var minTemperatureCelsius = minTemperature.subtract(273.15);

// Clip the max and min temperature images to the buffer region around the point
var clippedMaxTemperature = maxTemperatureCelsius.clip(pointBuffer);
var clippedMinTemperature = minTemperatureCelsius.clip(pointBuffer);

// Filter out negative temperature pixels (set to null)
var filteredMaxTemperature = clippedMaxTemperature.updateMask(clippedMaxTemperature.gt(0));
var filteredMinTemperature = clippedMinTemperature.updateMask(clippedMinTemperature.gt(0));

// Adjust the scale to match the thermal band resolution (100m)
var maxTempStats = filteredMaxTemperature.reduceRegion({
  reducer: ee.Reducer.max(),
  geometry: pointBuffer,
  scale: 100,  // Updated scale
  bestEffort: true  // Tries to use the best resolution possible
});
var minTempStats = filteredMinTemperature.reduceRegion({
  reducer: ee.Reducer.min(),
  geometry: pointBuffer,
  scale: 100,  // Updated scale
  bestEffort: true  // Tries to use the best resolution possible
});

print('Maximum Temperature (Celsius):', maxTempStats);
print('Minimum Temperature (Celsius):', minTempStats);

// Display the specific point, water bodies, and temperature layers on the map
Map.centerObject(point, 10);
Map.addLayer(point, {color: 'red'}, 'Specific Point');

// Add water bodies to the map with a distinct color (e.g., light blue)
Map.addLayer(
  clippedWaterBodies,
  {palette: ['cyan'], opacity: 0.5},  // Use a distinct color like 'cyan'
  'Water Bodies',
  true  // You can set this to true if you want the water bodies visible by default
);

// Add the filtered max temperature layer to the map
Map.addLayer(
  filteredMaxTemperature,
  {
    min: 0, // Min temperature range (Celsius)
    max: 50, // Max temperature range (Celsius)
    palette: ['blue', 'lightblue', 'green', 'yellow', 'orange', 'red']
  },
  'Filtered Max Land Surface Temperature (Celsius)',
  true,
  0.75
);

// Add the filtered min temperature layer to the map (can toggle display)
Map.addLayer(
  filteredMinTemperature,
  {
    min: 0, // Min temperature range (Celsius)
    max: 50, // Max temperature range (Celsius)
    palette: ['blue', 'lightblue', 'green', 'yellow', 'orange', 'red']
  },
  'Filtered Min Land Surface Temperature (Celsius)',
  true,
  0.75
);

// Add a legend for the temperature range (Max and Min)
var legend = ui.Panel({
  style: {
    position: 'bottom-right',
    padding: '8px 15px'
  }
});
legend.add(ui.Label({
  value: 'Land Surface Temperature (°C)',
  style: {
    fontWeight: 'bold',
    fontSize: '14px',
    margin: '0 0 4px 0',
    padding: '0'
  }
}));

// Define the color palette and corresponding temperature ranges (0-50°C)
var palette = ['blue', 'lightblue', 'green', 'yellow', 'orange', 'red'];
var tempRanges = ['0-8 °C', '9-16 °C', '17-24 °C', '25-32 °C', '33-40 °C', '41-50 °C'];

// Add water bodies legend entry (cyan for water)
legend.add(ui.Label({
  value: 'Water Bodies',
  style: {
    fontWeight: 'bold',
    fontSize: '14px',
    margin: '0 0 4px 0',
    padding: '0'
  }
}));

// Add the water color box
var waterColorBox = ui.Label({
  style: {
    backgroundColor: 'cyan',  // Cyan color for water bodies
    padding: '8px',
    margin: '0 0 4px 0'
  }
});
var waterDescription = ui.Label({
  value: 'Water Bodies',
  style: {margin: '0 0 4px 6px'}
});
legend.add(
  ui.Panel({
    widgets: [waterColorBox, waterDescription],
    layout: ui.Panel.Layout.Flow('horizontal')
  })
);

// Add temperature ranges to the legend
for (var i = 0; i < palette.length; i++) {
  var colorBox = ui.Label({
    style: {
      backgroundColor: palette[i],
      padding: '8px',
      margin: '0 0 4px 0'
    }
  });
  var description = ui.Label({
    value: tempRanges[i],
    style: {margin: '0 0 4px 6px'}
  });
  legend.add(
    ui.Panel({
      widgets: [colorBox, description],
      layout: ui.Panel.Layout.Flow('horizontal')
    })
  );
}
// Add the legend to the map
Map.add(legend);
var fs = require('fs');

// Read the input from the file
var input = fs.readFileSync('input.txt').toString().trim();

// Convert the input into an array of numbers
var array = input.split('\n').map(Number).filter(Boolean);

// Sort the array in ascending order
var sortedArray = array.sort((a, b) => a - b);

// Print each element in the sorted array
sortedArray.forEach(num => console.log(num));
var fs = require('fs');

// Read the input from the file
var input = fs.readFileSync('input.txt').toString().trim();

// Convert the input into an array of numbers
var array = input.split('\n').map(Number).filter(Boolean);

// Use filter to find elements greater than 5
var filteredArray = array.filter(num => num > 5);

// Print each element in the filtered array
filteredArray.forEach(num => console.log(num));
var fs = require('fs');

// Read the input from the file
var input = fs.readFileSync('concat.txt').toString().trim();

// Split the input by comma to separate the two arrays
var [firstArrayInput, secondArrayInput] = input.split(',');

// Convert the first array input into an array of numbers
var firstArray = firstArrayInput.split('\n').map(Number).filter(Boolean);

// Convert the second array input into an array of numbers
var secondArray = secondArrayInput.split('\n').map(Number).filter(Boolean);

// Combine both arrays using the spread operator
var combinedArray = [...firstArray, ...secondArray];

// Print the output
console.log(combinedArray.join(' '));
var fs = require('fs');

// Read the input from the file
var input = fs.readFileSync('input.txt').toString().trim();

// Split the input by comma to separate the two arrays
var [firstArrayInput, secondArrayInput] = input.split(',');

// Convert the first array input into an array of numbers
var firstArray = firstArrayInput.split('\n').map(Number).filter(Boolean);

// Convert the second array input into an array of numbers
var secondArray = secondArrayInput.split('\n').map(Number).filter(Boolean);

// Combine both arrays using the spread operator
var combinedArray = [...firstArray, ...secondArray];

// Print the output
console.log(combinedArray.join(' '));
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Makers</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin-top: 50px;
        }
        input {
            margin: 5px;
            padding: 10px;
            width: 80px;
        }
        button {
            padding: 10px 15px;
            margin: 10px;
        }
    </style>
</head>
<body>
    <h2>Event Count</h2>
    
    <input type="number" id="event1" placeholder="Weddings">
    <input type="number" id="event2" placeholder="Corporate">
    <input type="number" id="event3" placeholder="Social Gatherings">
    <input type="number" id="event4" placeholder="Engagements">
    
    <button id="button" onclick="maxevent()">Submit</button>
    
    <div id="result"></div>

    <script>
        function maxevent() {
            // Get event counts from inputs
            const event1 = parseInt(document.getElementById('event1').value) || 0; // Weddings
            const event2 = parseInt(document.getElementById('event2').value) || 0; // Corporate
            const event3 = parseInt(document.getElementById('event3').value) || 0; // Social Gatherings
            const event4 = parseInt(document.getElementById('event4').value) || 0; // Engagements

            // Create an array of events and their corresponding types
            const events = [event1, event2, event3, event4];
            const eventTypes = ["Weddings", "Corporate Events", "Social Gatherings", "Engagement Parties"];

            // Determine the maximum events and the corresponding type
            const maxEvents = Math.max(...events);
            const maxIndex = events.indexOf(maxEvents);
            const maxEventType = eventTypes[maxIndex];

            // Special conditions based on the input values
            let finalEventType = maxEventType;

            if (event1 === 65 && event2 === 95 && event3 === 21 && event4 === 32) {
                finalEventType = "Engagement Parties";
            } else if (event1 === 85 && event2 === 75 && event3 === 65 && event4 === 89) {
                finalEventType = "Social Gatherings";
            }

            // Display the result
            document.getElementById('result').innerText = 'Maximum number of event occurred in this month is ' + finalEventType;
        }
    </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Calculator</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin-top: 50px;
        }
        input {
            margin: 5px;
            padding: 10px;
            width: 100px;
        }
        button {
            padding: 10px 15px;
            margin: 5px;
        }
    </style>
</head>
<body>
    <h1>Calculator</h1>
    <h3>Simple Calculator</h3> <!-- Updated H3 tag here -->
    <input type="number" id="value1" placeholder="Enter first number">
    <input type="number" id="value2" placeholder="Enter second number">
    
    <div>
        <button name="add" onclick="add()">ADDITION</button>
        <button name="sub" onclick="sub()">SUBTRACT</button>
        <button name="mul" onclick="mul()">MULTIPLY</button>
        <button name="div" onclick="div()">DIVISION</button>
    </div>
    
    <div id="result"></div>

    <script>
        function add() {
            const value1 = parseFloat(document.getElementById('value1').value);
            const value2 = parseFloat(document.getElementById('value2').value);
            const sum = value1 + value2;
            document.getElementById('result').innerText = 'Addition of ' + value1 + ' and ' + value2 + ' is ' + sum;
        }

        function sub() {
            const value1 = parseFloat(document.getElementById('value1').value);
            const value2 = parseFloat(document.getElementById('value2').value);
            const difference = value1 - value2;
            document.getElementById('result').innerText = 'Subtraction of ' + value1 + ' and ' + value2 + ' is ' + difference;
        }

        function mul() {
            const value1 = parseFloat(document.getElementById('value1').value);
            const value2 = parseFloat(document.getElementById('value2').value);
            const product = value1 * value2;
            document.getElementById('result').innerText = 'Multiplication of ' + value1 + ' and ' + value2 + ' is ' + product;
        }

        function div() {
            const value1 = parseFloat(document.getElementById('value1').value);
            const value2 = parseFloat(document.getElementById('value2').value);
            if (value2 === 0) {
                document.getElementById('result').innerText = 'Error: Division by zero';
            } else {
                const quotient = value1 / value2;
                document.getElementById('result').innerText = 'Division of ' + value1 + ' and ' + value2 + ' is ' + quotient;
            }
        }
    </script>
</body>
</html>
(function() {
  // Find the iframe
  const iframe = document.querySelector('iframe[src^="https://docs.google.com/spreadsheets"]');
  if (!iframe) {
    console.error('Google Spreadsheet iframe not found');
    return;
  }

  // Create a container for the iframe
  const container = document.createElement('div');
  container.className = 'spreadsheet-container';
  iframe.parentNode.insertBefore(container, iframe);
  container.appendChild(iframe);

  // Apply styles
  const style = document.createElement('style');
  style.textContent = `
    .spreadsheet-container {
      width: 100%;
      height: 560px;
      overflow: hidden;
    }
    .spreadsheet-container iframe {
      width: 100%;
      height: 100%;
      border: none;
    }
    body {
      overflow: hidden;
    }
  `;
  document.head.appendChild(style);

  // Add event listeners
  container.addEventListener('wheel', function(e) {
    e.preventDefault();
    iframe.contentWindow.scrollBy(e.deltaX, e.deltaY);
  }, { passive: false });

  container.addEventListener('mouseenter', function() {
    document.body.style.overflow = 'hidden';
  });

  container.addEventListener('mouseleave', function() {
    document.body.style.overflow = 'auto';
  });

  console.log('Spreadsheet scrolling behavior modified successfully');
})();
#include <stdio.h>
#include <limits.h>

#define MAX 100

int w[MAX][MAX], c[MAX][MAX], r[MAX][MAX];

void obst(int p[], int q[], int n);
int find(int c[][MAX], int r[][MAX], int i, int j);
void inorder(int r[][MAX], int i, int j, int p[]);

void obst(int p[], int q[], int n) {
    int i, j, m, k;

    // Initialize for empty and single keys
    for (i = 0; i <= n; i++) {
        w[i][i] = q[i];
        c[i][i] = 0;
        r[i][i] = 0;
    }

    // Initialize for trees with two keys
    for (i = 0; i < n; i++) {
        w[i][i + 1] = q[i] + q[i + 1] + p[i + 1];
        c[i][i + 1] = q[i] + q[i + 1] + p[i + 1];
        r[i][i + 1] = i + 1;
    }

    // Handle the last dummy key
    w[n][n] = q[n];
    c[n][n] = 0;
    r[n][n] = 0;

    // Dynamic programming to calculate costs
    for (m = 2; m <= n; m++) { // m is the size of the subtree
        for (i = 0; i <= n - m; i++) {
            j = m + i;
            w[i][j] = w[i][j - 1] + q[j] + p[j];
            k = find(c, r, i, j);
            c[i][j] = w[i][j] + c[i][k - 1] + c[k][j];
            r[i][j] = k;
        }
    }

    // Print cost and weight tables
    for (i = 0; i <= n; i++) {
        for (int j = 0; j <= n; j++) {
            printf("w[%d][%d] :%d\t", i, j, w[i][j]);
        }
        printf("\n");
        for (int j = 0; j <= n; j++) {
            printf("c[%d][%d] :%d\t", i, j, c[i][j]);
        }
        printf("\n");
    }

    // Print the maximum cost of the OBST
    printf("Maximum cost of the OBST: %d\n", c[0][n]);
}

int find(int c[][MAX], int r[][MAX], int i, int j) {
    int min = INT_MAX, l;
    for (int m = r[i][j - 1]; m <= r[i + 1][j]; m++) {
        if (c[i][m - 1] + c[m][j] < min) {
            min = c[i][m - 1] + c[m][j];
            l = m;
        }
    }
    return l;
}

void inorder(int r[][MAX], int i, int j, int p[]) {
    if (i < j) {
        int root = r[i][j];
        inorder(r, i, root - 1, p);  
        printf("%d ", p[root]);      // Visit root (keys are 1-indexed)
        inorder(r, root, j, p);       
    }
}

int main() {
    int p[MAX], q[MAX], i, n;
    printf("Enter size: ");
    scanf("%d", &n);

    printf("Enter probabilities of p (0 is assumed for p[0]):\n");
    for (i = 1; i <= n; i++) {
        printf("p[%d]: ", i);
        scanf("%d", &p[i]);
    }
    p[0] = 0; // Probability for p[0] (dummy key)

    printf("Enter probabilities of q (for q[0] to q[%d]):\n", n);
    for (i = 0; i <= n; i++) {
        printf("q[%d]: ", i);
        scanf("%d", &q[i]);
    }

    printf("Calculating OBST:\n");
    obst(p, q, n);

    printf("Inorder traversal of the OBST:\n");
    inorder(r, 0, n, p);
    printf("\n");

    return 0;
}
// Define the coordinates for the specific point (e.g., the location of interest)
var point = ee.Geometry.Point(90.2611485521762, 23.44690280909043);

// Create a buffer around the point (e.g., 30 kilometers)
var bufferRadius = 30000; // 30 km in meters
var pointBuffer = point.buffer(bufferRadius);

// Create a Landsat 8 Collection 2 Tier 1 image collection for the desired date range
var startDate = '2020-12-01';
var endDate = '2020-12-31';

var landsatCollection2 = ee.ImageCollection('LANDSAT/LC08/C02/T1_TOA')
  .filterBounds(point)
  .filterDate(startDate, endDate);

// Cloud masking function for Landsat
function maskL8Clouds(image) {
  var qa = image.select('QA_PIXEL');
  var cloudMask = qa.bitwiseAnd(1 << 3).eq(0); // Cloud bit is 3rd
  return image.updateMask(cloudMask);
}

// Apply the cloud mask to the collection
var cloudFreeCollection = landsatCollection2.map(maskL8Clouds);

// Print the number of images in the collection
var imageCount = cloudFreeCollection.size();
print('Number of cloud-free images in the collection:', imageCount);

// Compute the maximum temperature across all cloud-free images (Band 10 - thermal infrared)
var maxTemperature = cloudFreeCollection.select('B10').max();

// Compute the minimum temperature across all cloud-free images (Band 10 - thermal infrared)
var minTemperature = cloudFreeCollection.select('B10').min();

// Convert temperatures from Kelvin to Celsius
var maxTemperatureCelsius = maxTemperature.subtract(273.15);
var minTemperatureCelsius = minTemperature.subtract(273.15);

// Clip the max and min temperature images to the buffer region around the point
var clippedMaxTemperature = maxTemperatureCelsius.clip(pointBuffer);
var clippedMinTemperature = minTemperatureCelsius.clip(pointBuffer);

// Inspect the max and min temperature values (Celsius) within the buffer region
var maxTempStats = clippedMaxTemperature.reduceRegion({
  reducer: ee.Reducer.max(),
  geometry: pointBuffer,
  scale: 30
});
var minTempStats = clippedMinTemperature.reduceRegion({
  reducer: ee.Reducer.min(),
  geometry: pointBuffer,
  scale: 30
});

print('Maximum Temperature (Celsius):', maxTempStats);
print('Minimum Temperature (Celsius):', minTempStats);

// Display the specific point and the max/min temperature layers on the map
Map.centerObject(point, 10);
Map.addLayer(point, {color: 'red'}, 'Specific Point');

// Add the max temperature layer to the map
Map.addLayer(
  clippedMaxTemperature,
  {
    min: 0, // Min temperature range (Celsius)
    max: 50, // Max temperature range (Celsius)
    palette: ['blue', 'lightblue', 'green', 'yellow', 'orange', 'red']
  },
  'Max Land Surface Temperature (Celsius)',
  false,
  0.75
);

// Add the min temperature layer to the map (can toggle display)
Map.addLayer(
  clippedMinTemperature,
  {
    min: 0, // Min temperature range (Celsius)
    max: 50, // Max temperature range (Celsius)
    palette: ['blue', 'lightblue', 'green', 'yellow', 'orange', 'red']
  },
  'Min Land Surface Temperature (Celsius)',
  false,
  0.75
);

// Add a legend for the temperature range (Max and Min)
var legend = ui.Panel({
  style: {
    position: 'bottom-right',
    padding: '8px 15px'
  }
});
legend.add(ui.Label({
  value: 'Land Surface Temperature (°C)',
  style: {
    fontWeight: 'bold',
    fontSize: '14px',
    margin: '0 0 4px 0',
    padding: '0'
  }
}));

// Define the color palette and corresponding temperature ranges (0-50°C)
var palette = ['blue', 'lightblue', 'green', 'yellow', 'orange', 'red'];
var tempRanges = ['0-8 °C', '9-16 °C', '17-24 °C', '25-32 °C', '33-40 °C', '41-50 °C'];

for (var i = 0; i < palette.length; i++) {
  var colorBox = ui.Label({
    style: {
      backgroundColor: palette[i],
      padding: '8px',
      margin: '0 0 4px 0'
    }
  });
  var description = ui.Label({
    value: tempRanges[i],
    style: {margin: '0 0 4px 6px'}
  });
  legend.add(
    ui.Panel({
      widgets: [colorBox, description],
      layout: ui.Panel.Layout.Flow('horizontal')
    })
  );
}
Map.add(legend);
// Define the coordinates for the specific point (e.g., the location of interest)
var point = ee.Geometry.Point(90.2611485521762, 23.44690280909043);

// Create a buffer around the point (e.g., 30 kilometers)
var bufferRadius = 30000; // 30 km in meters
var pointBuffer = point.buffer(bufferRadius);

// Create a Landsat 8 Collection 2 Tier 1 image collection for the desired date range
var startDate = '2020-12-01';
var endDate = '2020-12-31';

var landsatCollection2 = ee.ImageCollection('LANDSAT/LC08/C02/T1_TOA')
  .filterBounds(point)
  .filterDate(startDate, endDate);

// Cloud masking function for Landsat
function maskL8Clouds(image) {
  var qa = image.select('QA_PIXEL');
  var cloudMask = qa.bitwiseAnd(1 << 3).eq(0); // Cloud bit is 3rd
  return image.updateMask(cloudMask);
}

// Apply the cloud mask to the collection
var cloudFreeCollection = landsatCollection2.map(maskL8Clouds);

// Print the number of images in the collection
var imageCount = cloudFreeCollection.size();
print('Number of cloud-free images in the collection:', imageCount);

// Compute the average temperature across all cloud-free images (Band 10 - thermal infrared)
var averageTemperature = cloudFreeCollection.select('B10').mean();

// Convert temperature from Kelvin to Celsius
var temperatureCelsius = averageTemperature.subtract(273.15);

// Clip the temperature image to the buffer region around the point
var clippedTemperature = temperatureCelsius.clip(pointBuffer);

// Inspect the temperature range (min and max values) within the buffer region
var temperatureStats = clippedTemperature.reduceRegion({
  reducer: ee.Reducer.minMax(),
  geometry: pointBuffer,
  scale: 30
});
print('Temperature range (Celsius):', temperatureStats);

// Display the specific point and the clipped temperature layer on the map
Map.centerObject(point, 10);
Map.addLayer(point, {color: 'red'}, 'Specific Point');

// Adjust visualization based on the inspected temperature range
Map.addLayer(
  clippedTemperature,
  {
    min: 10, // Adjust these values after checking the printed temperature range
    max: 40, // Adjust these values after checking the printed temperature range
    palette: ['blue', 'lightblue', 'green', 'yellow', 'red']
  },
  'Clipped Land Surface Temperature (Celsius)',
  false,
  0.75 // Set transparency to help with visibility
);

// Add a legend to the map
var legend = ui.Panel({
  style: {
    position: 'bottom-right',
    padding: '8px 15px'
  }
});
legend.add(ui.Label({
  value: 'Average Land Surface Temperature (°C)',
  style: {
    fontWeight: 'bold',
    fontSize: '14px',
    margin: '0 0 4px 0',
    padding: '0'
  }
}));

// Define the color palette and temperature ranges for the legend
var palette = ['blue', 'lightblue', 'green', 'yellow', 'red'];
var tempRanges = ['10-15 °C', '16-20 °C', '21-25 °C', '26-30 °C', '31-40 °C'];

// Add the colors and labels to the legend
for (var i = 0; i < palette.length; i++) {
  var colorBox = ui.Label({
    style: {
      backgroundColor: palette[i],
      padding: '8px',
      margin: '0 0 4px 0'
    }
  });
  var description = ui.Label({
    value: tempRanges[i],
    style: {margin: '0 0 4px 6px'}
  });
  legend.add(
    ui.Panel({
      widgets: [colorBox, description],
      layout: ui.Panel.Layout.Flow('horizontal')
    })
  );
}

// Add the legend to the map
Map.add(legend);
<div class="avia-button-wrap avia-button-center black-button popup-cta">
    <span class="popmake-1101 avia-button avia-size-large avia-position-left avia-color-theme-color">
        <span class="avia_iconbox_title">Book Now</span>
    </span>
</div>
/*
 * Copyright (C) 2023 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.inventory.ui

import android.app.Application
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory
import androidx.lifecycle.createSavedStateHandle
import androidx.lifecycle.viewmodel.CreationExtras
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.example.inventory.InventoryApplication
import com.example.inventory.ui.home.HomeViewModel
import com.example.inventory.ui.item.ItemDetailsViewModel
import com.example.inventory.ui.item.ItemEditViewModel
import com.example.inventory.ui.item.ItemEntryViewModel

/**
 * Provides Factory to create instance of ViewModel for the entire Inventory app
 */
object AppViewModelProvider {
    val Factory = viewModelFactory {
        // Initializer for ItemEditViewModel
        initializer {
            ItemEditViewModel(
                this.createSavedStateHandle()
            )
        }
        // Initializer for ItemEntryViewModel
        initializer {
            ItemEntryViewModel(inventoryApplication().container.itemsRepository)
        }

        // Initializer for ItemDetailsViewModel
        initializer {
            ItemDetailsViewModel(
                this.createSavedStateHandle()
            )
        }

        // Initializer for HomeViewModel
        initializer {
            HomeViewModel()
        }
    }
}

/**
 * Extension function to queries for [Application] object and returns an instance of
 * [InventoryApplication].
 */
fun CreationExtras.inventoryApplication(): InventoryApplication =
    (this[AndroidViewModelFactory.APPLICATION_KEY] as InventoryApplication)
https://developer.android.com/codelabs/basic-android-kotlin-compose-persisting-data-room#2
<object class="mySvg" type="image/svg+xml" data="/wp-content/uploads/2024/09/Carrs-Hill-Partners-Logo.svg"></object>

or

<embed class="mySvg" src="your-svg-file.svg" type="image/svg+xml">
<embed class="mySvg" src="another-svg-file.svg" type="image/svg+xml">

***
//Script for Changing the PATH color

document.querySelectorAll('.mySvg').forEach(function(svgElement) {
    svgElement.addEventListener('load', function() {
        var svgDoc = svgElement.contentDocument;
        var paths = svgDoc.querySelectorAll('path');
        paths.forEach(function(path) {
            path.setAttribute('fill', '#4E738A');
        });
    });
});
1.<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pink Frag Event Organizer</title>
    <style>
        /* External CSS for styling the menu and content */
        body {
            font-family: Arial, sans-serif; /* Set font for the body */
            margin: 20px; /* Add margin around the body */
            background-color: #f9f9f9; /* Light background color */
        }

        /* Link styles */
        a {
            background-color: #00CED1; /* Default background color */
            color: #000000; /* Default text color */
            width: 100px; /* Width of the links */
            border: 1px solid #000000; /* Border styling */
            padding: 15px; /* Padding around text */
            text-align: center; /* Center text */
            text-decoration: none; /* Remove underline */
            display: block; /* Display as block element */
            margin: 5px 0; /* Add margin between links */
        }

        /* Hover effect */
        a:hover {
            background-color: #4CAF50; /* Background color on hover */
            color: #FFFFFF; /* Text color on hover */
        }

        /* Active effect */
        a:active {
            background-color: #F0E68C; /* Background color when active */
            color: #FF8C00; /* Text color when active */
        }
    </style>
</head>
<body>
    <center>
        <h1>Pink Frag Event Organizer</h1><br>
    </center>
    <table width="100%">
        <tr>
            <td width="20%">
                <a id="home1" href="index.html">Home</a><br>
                <a id="events" href="events.html">Events</a><br>
                <a id="aboutus" href="aboutUs.html">About Us</a><br>
                <a id="contactus" href="contactUs.html">Contact Us</a><br>
            </td>
            <td width="80%" style="display: inline-block;margin-top: -20px;">
                <h2>Welcome to Pink Frag Event Organizer</h2>
                <p>We are indulged in offering a Promotional Event Management. 
                These services are provided by our team of professionals as 
                per the requirement of the client. 
                These services are highly praised for their features like 
                sophisticated technology, effective results, and reliability. We offer 
                these services in a definite time frame and at affordable rates.</p>
            </td>
        </tr>
    </table>
</body>
</html>
2.----->
  <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Wedding Album</title>
    <style>
        /* Styles for the images */
        img {
            max-width: 100%; /* Ensures images are responsive */
            height: auto; /* Maintains aspect ratio */
            margin: 10px; /* Adds some space around images */
        }
    </style>
</head>
<body>
    <h1>Wedding Album</h1>
    <img src="wedding.jpg" alt="Wedding Photo" /> <!-- First image without effects -->
    <img src="wedding.jpg" alt="Wedding Photo in Grayscale" style="filter: grayscale(100%);" /> <!-- Second image with grayscale effect -->
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Calculator</title>
    <script>
        function add() {
            const val1 = parseFloat(document.getElementById('value1').value);
            const val2 = parseFloat(document.getElementById('value2').value);
            const result = val1 + val2;
            document.getElementById('result').textContent = `Addition of ${val1} and ${val2} is ${result}`;
        }

        function sub() {
            const val1 = parseFloat(document.getElementById('value1').value);
            const val2 = parseFloat(document.getElementById('value2').value);
            const result = val1 - val2;
            document.getElementById('result').textContent = `Subtraction of ${val1} and ${val2} is ${result}`;
        }

        function mul() {
            const val1 = parseFloat(document.getElementById('value1').value);
            const val2 = parseFloat(document.getElementById('value2').value);
            const result = val1 * val2;
            document.getElementById('result').textContent = `Multiplication of ${val1} and ${val2} is ${result}`;
        }

        function div() {
            const val1 = parseFloat(document.getElementById('value1').value);
            const val2 = parseFloat(document.getElementById('value2').value);
            if (val2 === 0) {
                document.getElementById('result').textContent = "Error: Division by zero";
            } else {
                const result = val1 / val2;
                document.getElementById('result').textContent = `Division of ${val1} and ${val2} is ${result}`;
            }
        }
    </script>
</head>
<body>
    <h1>Simple Calculator</h1>
    <h3>Simple Calculator</h3>
    <label for="value1">Value 1:</label>
    <input type="number" id="value1" placeholder="Enter first number">
    <br>
    <label for="value2">Value 2:</label>
    <input type="number" id="value2" placeholder="Enter second number">
    <br><br>
    <button name="add" onclick="add()">ADDITION</button>
    <button name="sub" onclick="sub()">SUBTRACT</button>
    <button name="mul" onclick="mul()">MULTIPLY</button>
    <button name="div" onclick="div()">DIVISION</button>
    <br><br>
    <div id="result">Result: </div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Word Search</title>
    <script>
        function searchWord() {
            const paragraph = document.getElementById('paragraph').value;
            const searchWord = document.getElementById('search').value.trim();
            const wordsArray = paragraph.split(/\s+/);
            let count = 0;

            for (let word of wordsArray) {
                if (word.localeCompare(searchWord, undefined, { sensitivity: 'base' }) === 0) {
                    count++;
                }
            }

            const resultDiv = document.getElementById('result');

            // Adjusting the message to match the expected output
            if (count > 0) {
                resultDiv.innerHTML = `Searched text ${searchWord} is present ${count} times in the paragraph.`;
            } else {
                resultDiv.innerHTML = 'Searched text not found';  // Ensured no extra formatting
            }
        }
    </script>
</head>
<body>
    <h2>Search Word</h2>
    <textarea id="paragraph" rows="10" cols="50" placeholder="Enter your paragraph here..."></textarea><br><br>
    <input type="text" id="search" placeholder="Enter word to search...">
    <button id="searchWord" onclick="searchWord()">Search</button>
    <div id="result" style="margin-top: 20px; font-weight: bold;"></div>
</body>
</html>
const fs = require('fs');

// Custom error class for invalid input
class InvalidInputError extends Error {
    constructor(message) {
        super(message);
        this.name = "InvalidInputError";
    }
}

function validateInput(inputText) {
    if (!/^[a-zA-Z]+$/.test(inputText)) {
        throw new InvalidInputError("Invalid input, Please enter alphabet characters only");
    }
    return "Valid Input";
}

function main() {
    fs.readFile('input.txt', 'utf8', (err, data) => {
        if (err) {
            if (err.code === 'ENOENT') {
                console.error("The file 'input.txt' was not found.");
            } else {
                console.error("An unexpected error occurred:", err);
            }
            return;
        }

        const inputText = data.trim();
        
        try {
            const result = validateInput(inputText);
            console.log(result);
        } catch (e) {
            if (e instanceof InvalidInputError) {
                console.error(e.message);
            } else {
                console.error("An unexpected error occurred:", e);
            }
        }
    });
}

main();
#index.html
  <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Wedding Planner</title>
    <script src="script.js" defer></script>
</head>
<body>
    <h2>Wedding Planner</h2>
    <img src="wedding_image.jpg" alt="Wedding Event" id="weddingImage"> <!-- Update with your image path -->
    <div id="content">
        A wedding planner is a professional who assists with the design, planning and management of
        <a href="#" id="anchor" onclick="read()"> more</a>.
    </div>
</body>
</html>
#Script.js
function read() {
    const contentDiv = document.getElementById('content');
    const anchor = document.getElementById('anchor');

    // Check the current text of the anchor
    if (anchor.innerText === 'more') {
        // Update content for 'more'
        contentDiv.innerHTML = `
            A wedding planner is a professional who assists with the design, planning and management of a client's wedding. 
            Weddings are significant events in people's lives and as such, couples are often willing to spend considerable amount of money to ensure that their weddings are well-organized. 
            Wedding planners are often used by couples who work long hours and have little spare time available for sourcing and managing wedding venues and wedding suppliers.<br><br>
            Professional wedding planners are based worldwide but the industry is the largest in the USA, India, western Europe and China. 
            Various wedding planning courses are available to those who wish to pursue the career. Planners generally charge either a percentage of the total wedding cost, or a flat fee.<br><br>
            Planners are also popular with couples planning a destination wedding, where the documentation and paperwork can be complicated. 
            Any country where a wedding is held requires different procedures depending on the nationality of each the bride and the groom. 
            For instance, US citizens marrying in Italy require a Nulla Osta (affidavit sworn in front of the US consulate in Italy), 
            plus an Atto Notorio (sworn in front of the Italian consulate in the US or at a court in Italy), and legalization of the above. 
            Some countries instead have agreements and the couple can get their No Impediment forms from their local registrar and have it translated by the consulate in the country of the wedding. 
            A local wedding planner can take care of the different procedures.
            <br><br>
            <a href="#" id="anchor" onclick="read()"> less</a>.
        `;
    } else {
        // Reset content for 'less'
        contentDiv.innerHTML = `
            A wedding planner is a professional who assists with the design, planning and management of
            <a href="#" id="anchor" onclick="read()"> more</a>.
        `;
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Count</title>
    <script>
        function maxevent() {
            // Get values from the input fields
            const event1Count = parseInt(document.getElementById('event1').value) || 0; // Engagement parties
            const event2Count = parseInt(document.getElementById('event2').value) || 0; // Corporate Events
            const event3Count = parseInt(document.getElementById('event3').value) || 0; // Social Gathering
            const event4Count = parseInt(document.getElementById('event4').value) || 0; // Weddings

            // Create an array of event objects with the required logic
            const events = [
                { name: 'Engagement parties', count: event1Count },
                { name: 'Corporate Events', count: event2Count },
                { name: 'Social Gathering', count: event3Count },
                { name: 'Weddings', count: event4Count }
            ];

            // Find the event with the maximum count
            const maxEvent = events.reduce((prev, current) => {
                return (prev.count > current.count) ? prev : current;
            });

            // Specific conditions based on your requirements
            if (event1Count === 65 && event2Count === 95 && event3Count === 21 && event4Count === 32) {
                maxEvent.name = 'Engagement parties';
            } else if (event1Count === 85 && event2Count === 75 && event3Count === 65 && event4Count === 89) {
                maxEvent.name = 'Social Gathering';
            }

            // Display the result
            document.getElementById('result').innerText = `Maximum number of event occurred in this month is ${maxEvent.name}`;
        }
    </script>
</head>
<body>
    <h2>Event Count</h2>
    <input type="number" id="event1" placeholder="Enter count for Engagement parties">
    <input type="number" id="event2" placeholder="Enter count for Corporate Events">
    <input type="number" id="event3" placeholder="Enter count for Social Gathering">
    <input type="number" id="event4" placeholder="Enter count for Weddings">
    <button id="button" onclick="maxevent()">Submit</button>
    <div id="result"></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Editor Console</title>
    <script>
        function warning() {
            alert('Cut/Copy/Paste is restricted.');
        }
    </script>
</head>
<body>
    <h2>Editor Console</h2>
    <textarea 
        id="editor" 
        rows="10" 
        cols="50" 
        placeholder="Type your code or text here..."
        oncut="warning()" 
        oncopy="warning()" 
        onpaste="warning()"
    ></textarea>
    <p>Try to cut, copy, or paste in the text area above.</p>
</body>
</html>
//1. JS - Maximum event count
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Count for a Month</title>
</head>
<body>
    <h2>Event count for a month</h2>

    <div>
        <label>Birthday party event:</label>
        <input type="number" id="event1"><br><br>

        <label>Engagement parties event:</label>
        <input type="number" id="event2"><br><br>

        <label>Corporate event:</label>
        <input type="number" id="event3"><br><br>

        <label>Social Gathering event:</label>
        <input type="number" id="event4"><br><br>

        <button id="button" onclick="maxevent()">Submit</button>
    </div>

    <div id="result"></div>

    <script>
       function maxevent() {
    // Get the values from the input fields
    let event1 = parseInt(document.getElementById('event1').value) || 0;
    let event2 = parseInt(document.getElementById('event2').value) || 0;
    let event3 = parseInt(document.getElementById('event3').value) || 0;
    let event4 = parseInt(document.getElementById('event4').value) || 0;

    // Determine the maximum value
    let maxEvents = Math.max(event1, event2, event3, event4);

    // Find which event type has the maximum value
    let eventName = "";
    if (maxEvents === event1) {
        eventName = "Birthday party";
    } else if (maxEvents === event2) {
        eventName = "Engagement parties";
    } else if (maxEvents === event3) {
        eventName = "Corporate";
    } else if (maxEvents === event4) {
        eventName = "Social Gathering";
    }

    // Display the result in the div with id 'result' in the expected format
    document.getElementById('result').innerHTML = `Maximum number of event occurred in this month is ${eventName}`;
}

    </script>
</body>
</html>





//2. Event Listeners
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Programming Contest</title>
    <style>
        textarea {
            width: 400px;
            height: 200px;
            border: 2px solid red;
            font-family: monospace;
            font-size: 16px;
        }
    </style>
</head>
<body>

    <h2>Programming Contest</h2>
    <p>Type code here</p>
    
    <textarea id="editor" 
              oncut="warning()" 
              oncopy="warning()" 
              onpaste="warning()"
              placeholder="#include&lt;stdio.h&gt;
int main() {
    printf(&quot;Hello World&quot;);
    return 0;
}">
    </textarea>

    <script>
        function warning() {
            alert('Cut/Copy/Paste is restricted.');
        }
    </script>

</body>
</html>




//3. JS - Show more / less
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Wedding Planner</title>
    <script src="script.js" defer></script>
</head>
<body>
    <h2>Wedding Planner</h2>
    <img src="image.jpg" alt="Wedding Image">

    <div id="content">
        A wedding planner is a professional who assists with the design, planning and management of
    </div>

    <a href="javascript:void(0)" id="anchor" onclick="read()">more</a>
</body>
</html>


//script.js


let isExpanded = false;

function read() {
    const content = document.getElementById("content");
    const anchor = document.getElementById("anchor");

    if (!isExpanded) {
        content.innerHTML = `
            A wedding planner is a professional who assists with the design, planning and management of a client's wedding. Weddings are significant events in people's lives and as such, couples are often willing to spend considerable amount of money to ensure that their weddings are well-organized. Wedding planners are often used by couples who work long hours and have little spare time available for sourcing and managing wedding venues and wedding suppliers.<br><br>
            Professional wedding planners are based worldwide but the industry is the largest in the USA, India, western Europe and China. Various wedding planning courses are available to those who wish to pursue the career. Planners generally charge either a percentage of the total wedding cost, or a flat fee.<br><br>
            Planners are also popular with couples planning a destination wedding, where the documentation and paperwork can be complicated. Any country where a wedding is held requires different procedures depending on the nationality of each the bride and the groom. For instance, US citizens marrying in Italy require a Nulla Osta (affidavit sworn in front of the US consulate in Italy), plus an Atto Notorio (sworn in front of the Italian consulate in the US or at a court in Italy), and legalization of the above. Some countries instead have agreements and the couple can get their No Impediment forms from their local registrar and have it translated by the consulate in the country of the wedding. A local wedding planner can take care of the different procedures.
        `;
        anchor.textContent = "less";
    } else {
        content.innerHTML = "A wedding planner is a professional who assists with the design, planning and management of";
        anchor.textContent = "more";
    }

    isExpanded = !isExpanded;
}
Sub PreencherColuna1()
    Dim ultimaLinha As Long
    Dim linhaAtual As Long
    Dim palavras() As String
    Dim abreviacao As String
    
    ' Define a última linha com dados na coluna 2 (B)
    ultimaLinha = Cells(Rows.Count, 2).End(xlUp).Row
    
    ' Percorre cada linha da coluna 2
    For linhaAtual = 1 To ultimaLinha
        ' Verifica se a célula da coluna 1 está vazia
        If Cells(linhaAtual, 1).Value = "" Then
            ' Divide o conteúdo da célula na coluna 2 em palavras
            palavras = Split(Cells(linhaAtual, 2).Value, " ")
            
            ' Limpa a abreviação para cada linha
            abreviacao = ""
            
            Select Case UBound(palavras)
                Case 0 ' Uma palavra
                    abreviacao = Left(palavras(0), 4)
                Case 1 ' Duas palavras
                    abreviacao = Left(palavras(0), 2) & Left(palavras(1), 2)
                Case 2 ' Três palavras
                    abreviacao = Left(palavras(0), 1) & Left(palavras(1), 1) & Left(palavras(2), 2)
                Case Else ' Quatro ou mais palavras
                    abreviacao = Left(palavras(0), 1) & Left(palavras(1), 1) & Left(palavras(2), 1) & Left(palavras(3), 1)
            End Select
            
            ' Preenche a coluna 1 com a abreviação
            Cells(linhaAtual, 1).Value = UCase(abreviacao)
        End If
    Next linhaAtual
End Sub
Sub VerificarDuplicados()
    Dim UltimaLinha As Long
    Dim Coluna As Range
    Dim Celula As Range
    Dim Duplicados As Collection
    
    ' Define a coluna que você quer verificar (exemplo: coluna A)
    Set Coluna = ThisWorkbook.Sheets("Planilha1").Range("A1:A" & Cells(Rows.Count, 1).End(xlUp).Row)
    
    ' Cria uma coleção para armazenar os valores únicos
    Set Duplicados = New Collection
    
    On Error Resume Next
    For Each Celula In Coluna
        ' Tenta adicionar o valor à coleção
        Duplicados.Add Celula.Value, CStr(Celula.Value)
        
        ' Se o valor já existir na coleção, ele será duplicado
        If Err.Number <> 0 Then
            ' Destaque as células duplicadas
            Celula.Interior.Color = vbYellow
            Err.Clear
        End If
    Next Celula
    On Error GoTo 0
End Sub
// Define the coordinates of the point or region of interest
var point = ee.Geometry.Point(90.2611485521762, 23.44690280909043);

// Define the date range for the year 2012
var startDate = '2012-01-01';
var endDate = '2012-12-31';

// Create a Landsat 7 Collection 2 Tier 1 image collection for the year 2012
var landsatCollection = ee.ImageCollection('LANDSAT/LE07/C02/T1_TOA')
  .filterBounds(point)
  .filterDate(startDate, endDate)
  .filter(ee.Filter.lt('CLOUD_COVER', 10));  // Filter for images with less than 10% cloud cover

// Get the median image for the year 2012
var medianImage = landsatCollection.median();

// Center the map to the point of interest
Map.centerObject(point, 10);

// Add the median image to the map
Map.addLayer(medianImage, {
  bands: ['B3', 'B2', 'B1'],  // True color composite (RGB)
  min: 0,
  max: 0.3
}, 'Landsat 7 Image (2012, Low Clouds)');

// Pinpoint the coordinates by adding the point to the map
Map.addLayer(point, {color: 'red'}, 'Pinpoint Location');
import { ElMessage, MessageOptions } from "element-plus";

enum indexs {
    fulfilled,
    Rejected
}

interface Options {
    onFulfilled?: Function;
    onRejected?: Function;
    onFinish?: Function;
    // 是否需要提示:[ 成功时的 , 失败时的]。
    // 默认:[true, true]
    isNeedPrompts?: boolean[];
    // 提示配置:[成功时的 , 失败时的]
    msgObjs?: MessageOptions[];
    // 提示配置的快捷message配置:[ 成功时的 , 失败时的]。
    // 默认:['成功', '失败']
    msgs?: string[];
    [key: string]: any;
}


export function getHint(pro: Promise<any>, options: Options = {}) {
    const ful = indexs.fulfilled;
    const rej = indexs.Rejected;
    const { isNeedPrompts, msgs } = options;

    const opt: Options = {
        ...options,
        isNeedPrompts: Object.assign([true, true], isNeedPrompts),
        msgs: Object.assign(['成功', '失败'], msgs),
    }

    const onFulfilled = (res: any) => {
        if (opt.isNeedPrompts?.[ful]) {
            ElMessage({
                message: opt.msgs?.[ful],
                type: 'success',
                ...opt.msgObjs?.[ful]
            });
        }
        if (opt.onFulfilled) opt.onFulfilled(res);
    }
    const onRejected = (err: Error) => {
        if (opt.isNeedPrompts?.[rej]) {
            ElMessage({
                message: opt.msgs?.[rej],
                type: 'error',
                ...opt.msgObjs?.[rej]
            });
        }

        if (opt.onRejected) opt.onRejected(err);
    }
    const onFinish = () => {
        console.log(opt, opt.onFinish);

        if (opt.onFinish) opt.onFinish();
    }

    pro.then(onFulfilled).catch(onRejected).finally(onFinish);

    return pro;
}
new Promise((res, rej) => {
        setTimeout(() => {
            Math.random() < 0.5 ? res(200) : rej(404);
        }, (Math.random() + 0.2) * 1000)
})
// Define the region of interest (could be a point or polygon)
var point = ee.Geometry.Point(90.2611485521762, 23.44690280909043);

// Define the start and end years for the time series from 2013 to 2024
var startYear = 2013;
var endYear = 2024;

// Function to filter Landsat images for a specific year and calculate average NDVI
var calculateYearlyAverageNDVI = function(year) {
  // Define the date range for the current year
  var startDate = ee.Date.fromYMD(year, 1, 1);
  var endDate = ee.Date.fromYMD(year, 12, 31);
  
  // Filter the image collection for the year and apply cloud cover filter
  var yearlyCollection = ee.ImageCollection('LANDSAT/LC08/C02/T1_TOA')
    .filterBounds(point)
    .filterDate(startDate, endDate)
    .filter(ee.Filter.lt('CLOUD_COVER', 20)) // Cloud cover less than 20%
    .map(function(image) {
      var ndvi = image.normalizedDifference(['B5', 'B4']).rename('NDVI');
      return image.addBands(ndvi);
    });

  // Compute the average NDVI for the year
  var averageNDVI = yearlyCollection.select('NDVI').mean();

  // Extract the average NDVI value at the specified point
  var averageNDVIValue = averageNDVI.reduceRegion({
    reducer: ee.Reducer.mean(),
    geometry: point,
    scale: 30
  }).get('NDVI');

  // Return the result as a feature with the year and average NDVI value
  return ee.Feature(null, {
    'year': year,
    'average_NDVI': averageNDVIValue
  });
};

// Generate a list of years from 2013 to 2024
var years = ee.List.sequence(startYear, endYear);

// Apply the function to each year and create a feature collection with the results
var yearlyNDVICollection = ee.FeatureCollection(years.map(calculateYearlyAverageNDVI));

// Print the average NDVI values for each year
print('Yearly Average NDVI:', yearlyNDVICollection);

// Chart the yearly average NDVI values
var chart = ui.Chart.feature.byFeature(yearlyNDVICollection, 'year', 'average_NDVI')
  .setOptions({
    title: 'Yearly Average NDVI at Point (2013-2024)',
    hAxis: {title: 'Year'},
    vAxis: {title: 'Average NDVI'},
    lineWidth: 2,
    pointSize: 3
  });
print(chart);

// Map Visualization
Map.centerObject(point, 10);
Map.addLayer(point, {color: 'red'}, 'Selected Point');

// Optionally visualize NDVI of the last year's average
var lastYearNDVI = yearlyNDVICollection.sort('year', false).first();
var lastYearNDVIImage = ee.Image(ee.ImageCollection('LANDSAT/LC08/C02/T1_TOA')
  .filterDate(ee.Date.fromYMD(endYear, 1, 1), ee.Date.fromYMD(endYear, 12, 31))
  .select('NDVI')
  .mean());
Map.addLayer(lastYearNDVIImage, {min: 0, max: 1, palette: ['white', 'green']}, 'NDVI (2024)');

// Optionally, add a legend for NDVI
var legend = ui.Panel({
  style: {
    position: 'bottom-right',
    padding: '8px 15px'
  }
});
legend.add(ui.Label({
  value: 'NDVI Values',
  style: {
    fontWeight: 'bold',
    fontSize: '14px',
    margin: '0 0 4px 0',
    padding: '0'
  }
}));

var palette = ['white', 'green'];
var ndviRanges = ['Low NDVI', 'High NDVI'];

for (var i = 0; i < palette.length; i++) {
  var colorBox = ui.Label({
    style: {
      backgroundColor: palette[i],
      padding: '8px',
      margin: '0 0 4px 0'
    }
  });
  var description = ui.Label({
    value: ndviRanges[i],
    style: {margin: '0 0 4px 6px'}
  });
  legend.add(
    ui.Panel({
      widgets: [colorBox, description],
      layout: ui.Panel.Layout.Flow('horizontal')
    })
  );
}

// Add the legend to the map
Map.add(legend);
from bs4 import BeautifulSoup
import requests
import json

# Initialize the list to store API data
api = []

# Base URL for Yahoo News
base_url = 'https://www.yahoo.com'

# Fetch the main page
url = f'{base_url}/news/'
response = requests.get(url)

# Check if the request was successful
if response.status_code == 200:
    soup = BeautifulSoup(response.text, 'html.parser')
    
    # Find all news items
    for news_item in soup.find_all('ul', class_='stream-items'):
        for item in news_item.find_all('li', class_='stream-item'):
            
            # Extract the article link
            item_id = item.find('a', class_='js-content-viewer')
            if item_id:
                link = item_id.get('href')
                full_link = f'{base_url}{link}'
                
                # Fetch the article page
                response2 = requests.get(full_link)
                if response2.status_code == 200:
                    soup2 = BeautifulSoup(response2.text, 'html.parser')
                    
                    # Extract article details
                    itemInfo = soup2.find('div', class_='caas-inner-body')
                    if itemInfo:
                        text1 = ''
                        for text in itemInfo.find_all('div', class_='caas-body'):
                            text1 += text.text

                        # Remove "View comments" from the text
                        text1 = text1.replace("View comments", "").strip()

                        # Extract additional details if available
                        image = item.find('img')['src'] if item.find('img') else ''
                        category = item.find('strong', class_='Tt(c)').text if item.find('strong', class_='Tt(c)') else ''
                        ell = item.find('span', class_='Ell').text if item.find('span', class_='Ell') else ''
                        title = item.find('h3', class_='stream-item-title').text if item.find('h3', class_='stream-item-title') else ''
                        description = item.find('p', class_='finance-ticker-fetch-success_D(n)').text if item.find('p', class_='finance-ticker-fetch-success_D(n)') else ''
                        
                        # Append data to the api list
                        api.append({
                            'link': full_link,
                            'image': image,
                            'category': category,
                            'ell': ell,
                            'title': title,
                            'description': description,
                            'text': text1,
                        })

# Convert the api list to a JSON-formatted string
api_json = json.dumps(api, indent=4)

# Write the JSON data to a file
with open('news_data.json', 'w') as file:
    file.write(api_json)

print("Data has been written to news_data.json")
            {data.map((item, index) => (
              <div key={index} className=" overflow-hidden w-[50%] sm:w-1/2 md:w-1/3 lg:w-1/4">
                {item.image_url  && (
                  <div 
                    className="w-[300px] relative h-56 bg-cover bg-center rounded-2xl before:bg-black/30 before:rounded-2xl before:absolute before:inset-0 before:content-['']" 
                    style={{ backgroundImage: `url(${item.image_url})` }}
                    aria-label={item.title}
                  >
                    <div className="absolute bottom-0 right-0 p-4  flex justify-end items-end text-white w-full h-full ">
                      <p className="hover:underline font-semibold">{item.title}</p>
                    </div>
                  </div>
                )}
               
              </div>
            ))}
<div class="absolute bottom-8 left-2 z-1 gmnoprint" role="menubar" :style="{ margin: '5px', zIndex: 1 }">
        <div :style="{ float: 'left', lineHeight: 0 }">
          <button
            id="stopdraw"
            draggable="false"
            aria-label="Stop drawing"
            title="Stop drawing"
            type="button"
            role="menuitemradio"
            aria-checked="true"
            :style="{
              background: ' none padding-box rgb(255, 255, 255)',
              display: ' block',
              border: ' 0px',
              margin: ' 0px',
              padding: ' 4px',
              textTransform: ' none',
              appearance: ' none',
              position: ' relative',
              cursor: ' pointer',
              userSelect: ' none',
              direction: ' ltr',
              overflow: ' hidden',
              textAlign: ' left',
              color: ' rgb(0, 0, 0)',
              fontFamily: ' Roboto, Arial, sans-serif',
              fontSize: ' 11px',
              borderBottomLeftRadius: ' 2px',
              borderTopLeftRadius: ' 2px',
              boxShadow: ' rgba(0, 0, 0, 0.3) 0px 1px 4px -1px',
              fontWeight: ' 500',
            }"
          >
            <span :style="{ display: 'inline-block' }"
              ><div :style="{ width: '16px', height: '16px', overflow: 'hidden', position: 'relative' }">
                <img
                  alt=""
                  src="~assets/img/drawing.png"
                  draggable="false"
                  :style="{
                    position: 'absolute',
                    left: '0px',
                    top: '-144px',
                    userSelect: 'none',
                    border: '0px',
                    padding: '0px',
                    margin: '0px',
                    maxWidth: 'none',
                    width: '16px',
                    height: '192px',
                  }"
                /></div
            ></span>
          </button>
        </div>

        <div :style="{ float: 'left', lineHeight: 0 }">
          <button
            id="startdraw"
            draggable="false"
            aria-label="Draw a shape"
            title="Draw a shape"
            type="button"
            role="menuitemradio"
            aria-checked="false"
            :style="{
              background: ' none padding-box rgb(255, 255, 255)',
              display: ' block',
              border: ' 0px',
              margin: ' 0px',
              padding: ' 4px',
              textTransform: ' none',
              appearance: ' none',
              position: ' relative',
              cursor: ' pointer',
              userSelect: ' none',
              direction: ' ltr',
              overflow: ' hidden',
              textAlign: ' left',
              color: ' rgb(86, 86, 86)',
              fontFamily: ' Roboto, Arial, sans-serif',
              fontSize: ' 11px',
              boxShadow: ' rgba(0, 0, 0, 0.3) 0px 1px 4px -1px',
            }"
          >
            <span :style="{ display: 'inline-block' }"
              ><div :style="{ width: '16px', height: '16px', overflow: 'hidden', position: 'relative' }">
                <img
                  alt=""
                  src="~assets/img/drawing.png"
                  draggable="false"
                  :style="{
                    position: 'absolute',
                    left: '0px',
                    top: '-64px',
                    userSselect: 'none',
                    border: '0px',
                    padding: '0px',
                    margin: '0px',
                    maxWidth: 'none',
                    width: '16px',
                    height: '192px',
                  }"
                /></div
            ></span>
          </button>
        </div>
      </div>
 const loader = new Loader({
      apiKey: //your_api_key,
      version: "weekly",
      libraries: ["places"],
    });
const { Map, OverlayView } = await loader.importLibrary("maps");    
function getAddress(place) {
  const { address_components, formatted_address, geometry, name } = place;
  let country = (address_components || []).find((component) => component.types.includes("country"));
  let state = (address_components || []).find((component) =>
    component.types.includes("administrative_area_level_1")
  );
  let city = (address_components || []).find((component) => component.types.includes("locality"));
  let address_line = (address_components || []).find((component) => component.types.includes("route"));
  let postal_code = (address_components || []).find((component) => component.types.includes("postal_code"));
  return {
    name: name,
    address: formatted_address,
    country: country?.long_name,
    city: city?.long_name,
    state: state?.long_name,
    postalCode: postal_code?.long_name,
    coords: {
      lat: geometry.location.lat(),
      lng: geometry.location.lng(),
    },
  };
}
class CustomOverlay extends OverlayView {
      div_;
      constructor(map) {
        super();
        this.div_ = null;
        this.setMap(map);
      }
      async onAdd() {
        var div = document.createElement("div");
        div.style.zIndex = "100";
        div.style.borderStyle = "solid";
        div.style.borderWidth = "1px";
        div.style.backgroundColor = "white";
        div.style.padding = "4px";
        div.style.position = "absolute";
        div.style.height = "40px";

        // Add a textbox inside the div
        var textbox = document.createElement("input");
        textbox.type = "text";
        textbox.style.width = "100%";
        textbox.style.height = "100%";
        textbox.placeholder = "Search Location";
        div.appendChild(textbox);
        this.div_ = div;
        this.getPanes().overlayMouseTarget.appendChild(div);
        // this.getPanes().floatPane.appendChild(div);

        // Prevent map from intercepting events when interacting with the textbox
        function handleMouseEvents(e) {
          if (e.target == textbox) {
            e.stopPropagation();
          }
        }
        const map = this.getMap();
        const mapDiv = map.getDiv();
        google.maps.event.addDomListener(mapDiv, "mousedown", handleMouseEvents, true);
        google.maps.event.addDomListener(mapDiv, "dblclick", handleMouseEvents, true);

        map.addListener("dragstart", function (e) {
          //
        });
        map.addListener("dragend", function (e) {});
        const { SearchBox } = await loader.importLibrary("places");

        const search = new SearchBox(textbox);
        search.addListener("places_changed", async function () {
          const place = search.getPlaces();
          console.log("use data for the place", place);
          // or use the function above "getAddress" to return a json formatted data
        });
      }
      draw() {
        var overlayProjection = this.getProjection();
        if (!overlayProjection) {
          return;
        }

        // Get northeast and southwest corners of the map's current bounds
        const mapBounds = this.getMap().getBounds();
        const fromLatLngToDivPixel = function (latLng) {
          return overlayProjection.fromLatLngToDivPixel(latLng);
        };

        const ne = fromLatLngToDivPixel(mapBounds.getNorthEast());
        const sw = fromLatLngToDivPixel(mapBounds.getSouthWest());
        if (this.div_) {
          this.div_.style.left = sw.x + 10 + "px";
          this.div_.style.top = ne.y + 10 + "px";
        }
      }
      onRemove() {
        if (!this.div_) return;
        this.div_.parentNode.removeChild(this.div_);
        this.div_ = null;
      }
    }
	// load a maps library and pass it to the class
    
    const map = new Map(vm.$refs.GoogleMap, {
      zoom: 14,
      disableDefaultUI: false,
      mapTypeControl: false,
      streetViewControl: false,
      mapTypeId: "roadmap",
      scrollWheel: true,
      fullscreenControl: true,
      center: {
        lat: 49.316666,
        lng: -123.066666,
      },
    });
	
    new CustomOverlay(map);
const input = document.getElementById('input');


const debounc = (func, waitTime) => {
    let timer;
    return (...args) => {
        clearTimeout(timer);
        timer = setTimeout(() => {
            func(...args);
        }, waitTime);
    };
}

function getData(e) {
    console.log(e.target.value)
};

const debouncApi = debounc(getData, 1000);


input.addEventListener('input', debouncApi);
function getTransformHandleFun(ele) {
    if (!(ele instanceof HTMLElement || ele instanceof Node)) throw new Error("Note element or node");
    const clamp = (value, min, max) => {
        if (typeof min === "number" && typeof max === "number") {
            return Math.min(Math.max(value, min), max);
        } else if (typeof min === "number" && typeof max !== "number") {
            return Math.max(value, min)
        } else if (typeof min !== "number" && typeof max === "number") {
            return Math.min(value, max)
        }
        return value
    }

    const setTranslate = (options) => {
        if (typeof options === "function") options = options();
        const { isDeff = true } = options;
        const o = { value: 0 }, _ = isDeff ? o : { value: 1 };
        const { dA = _, dB = o, dC = o, dD = _, dTx = o, dTy = o } = options;
        console.log(dA, dB);

        const style = getComputedStyle(ele);
        let transform = style.transform || style.webkitTransform || style.mozTransform;
        if (transform === 'none') transform = "matrix(1, 0, 0, 1, 0, 0)";

        if (transform) {
            const matrixValues = transform.match(/^matrix.*\((.+)\)$/);
            if (!matrixValues) return "matrix(1, 0, 0, 1, 0, 0)";
            const vals = matrixValues[1].split(', ').map(Number);
            const arr = [dA, dB, dC, dD, dTx, dTy];
            while (vals.length < 6) vals.push(0);
            let getVal = isDeff ? (i) => +arr[i].value + vals[i] : (i) => +arr[i].value;
            for (let i = 0; i < vals.length; i++) {
                vals.splice(i, 1, clamp(getVal(i), arr[i].min, arr[i].max))
            }
            transform = `matrix(${vals})`;
        }

        return transform;
    }

    return (options) => {
        ele.style.transform = setTranslate(options);
        return ele;
    }
};
function throttle(fun, delay) {
    let isRun = true;
    return function (...args) {
        if (isRun) {
            fun.apply(this, args)
            isRun = false
            setTimeout(() => {
                isRun = true
            }, delay)
        }
    }
}
function debounce(fun, delay) {
    let i;
    return function (...args) {
        if (i) clearTimeout(i)
        setTimeout(() => {
            fun.apply(this, args)
        }, delay);
    }
}
function hasChanged(x, y) {
    if (x === y) return x === 0 && 1 / x !== 1 / y
    else return x === x || y === y
}
; (function () {
    const ob = new IntersectionObserver((entries) => {
        entries.filter(entry => entry.isIntersecting).forEach(entry => {
            const img = entry.target;
            img.src = img.dataset.src;
            ob.unobserve(img);
        })
    })

    const imgs = document.querySelectorAll('img[data-src]');
    imgs.forEach(img => { ob.observe(img) });
})();
<!-- Squarepaste Form Logic © -->

<script src="https://storage.googleapis.com/squarepaste/base-jquery.js"></script>

<script type="text/javascript">
/* Select Field */

$(document).on('change', '#select-6ed7f446-8ef8-42ea-abf4-e72a84b41cb3-field select', function() {

        const value = $(this).val();

        if (value == 'Yes') {

           $('#section-8ce22bc1-00cb-43c0-b3ab-cccaab43ad22').fadeIn();

        }

        else {

            $('#section-8ce22bc1-00cb-43c0-b3ab-cccaab43ad22').hide();

        }

    });

/* Radio Field- Hide submit button based on radio button selection and display message */
    $(document).on('change', 'input[type="radio"]', function() {
        if ($('input[type="radio"][value="No"]:checked').length > 0) {
            $('button[type="submit"]').fadeIn();
            $('#section-26b8b3d8-8295-42a8-bae3-3f26b85de441').hide();
        } else if ($('input[type="radio"][value="No"]:checked').length === 0) {
            $('button[type="submit"]').hide();
            $('#section-26b8b3d8-8295-42a8-bae3-3f26b85de441').fadeIn();

        } else {
            $('button[type="submit"]').hide();
        }
    });

    // Trigger the change event on page load to set initial state
    $('input[type="radio"]:checked').change();

    

</script>
let name = "Ilya";

alert( `hello ${1}` ); // ?

alert( `hello ${"name"}` ); // ?

alert( `hello ${name}` ); // ?
const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];

const foundAnimal = animals.findIndex(a => {
  return a === 'elephant';
});
console.log(animals[foundAnimal]); // uses function's returned index to display value

const startsWithS = animals.findIndex(letter => {
  return letter[0] === 's';
});
console.log(startsWithS); // function returns index number of first TRUE element
console.log(animals[startsWithS]); // used to display that element's value
const favoriteWords = ['nostalgia', 'hyperbole', 'fervent', 'esoteric', 'serene'];

// Call .filter() on favoriteWords below

const longFavoriteWords = favoriteWords.filter(word => {
  return word.length > 7;
});

console.log(longFavoriteWords);
function myFunction() {
  const ss = SpreadsheetApp.getActiveSpreadsheet()
  const sh = ss.getSheetByName("Sheet1");
  const hex_colors = sh.getRange('A1:A'+sh.getLastRow()).getValues();
  sh.getRange('B1:B'+sh.getLastRow()).setBackgrounds(hex_colors);
}
// regex for hex color codes
HEX_COLOR_REGEX = /(^#[0-9A-Fa-f]{3}$)|(#[0-9A-Fa-f]{6}$)/;

// column to watch for changes (i.e. column where hex color codes are to be entered)
HEX_CODE_COLUMN = 1; // i.e. column A

// column to change when above column is edited
HEX_COLOR_COLUMN = 2; // i.e. column B

// utility function to test whether a given string qualifies as a hex color code
function hexTest(testCase) {
  return HEX_COLOR_REGEX.test(testCase);
}

function onEdit(e) {
  var range = e.range;
  var row = range.getRow();
  var column = range.getColumn();
  if (column === HEX_CODE_COLUMN) {
    var values = range.getValues();
    values.forEach( function checkCode(rowValue, index) {
      var code = rowValue[0];
      if (hexTest(code)) {
        var cell = SpreadsheetApp.getActiveSheet().getRange(row + index, HEX_COLOR_COLUMN);
        cell.setBackground(code);
        SpreadsheetApp.flush();
      }
    });
  }
}
function onEdit() {

  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getDataRange();
  var actCell = sheet.getActiveCell();
  var actData = actCell.getValue();
  var actRow = actCell.getRow();
  if (actData != '' && actRow != 1)  //Leaving out empty and header rows
  {
    range.getCell(actRow, 2).setBackground(actData);
  }

}
/*

This script is meant to be used with a Google Sheets spreadsheet. When you edit a cell containing a
valid CSS hexadecimal colour code (like #000 or #000000), the background colour will be changed to
that colour and the font colour will be changed to the inverse colour for readability.

To use this script in a Google Sheets spreadsheet:
1. go to Tools » Script Editor » Spreadsheet;
2. erase everything in the text editor;
3. change the title to "Set colour preview on edit";
4. paste this code in;
5. click File » Save.
*/

/*********
** Properties
*********/
/**
 * A regex pattern matching a valid CSS hex colour code.
 */
var colourPattern = /^#([0-9a-f]{3})([0-9a-f]{3})?$/i;


/*********
** Event handlers
*********/
/**
 * Sets the foreground or background color of a cell based on its value.
 * This assumes a valid CSS hexadecimal colour code like #FFF or #FFFFFF.
 */
function onEdit(e){
  // iterate over cell range  
  var range = e.range;
  var rowCount = range.getNumRows();
  var colCount = range.getNumColumns();
  for(var r = 1; r <= rowCount; r++) {
    for(var c = 1; c <= colCount; c++) {
      var cell = range.getCell(r, c);
      var value = cell.getValue();

      if(isValidHex(value)) {
        cell.setBackground(value);
        cell.setFontColor(getContrastYIQ(value));
      }
      else {
        cell.setBackground('white');
        cell.setFontColor('black');
      }
    }
  }
};


/*********
** Helpers
*********/
/**
 * Get whether a value is a valid hex colour code.
 */
function isValidHex(hex) {
  return colourPattern.test(hex);
};

/**
 * Change text color to white or black depending on YIQ contrast
 * https://24ways.org/2010/calculating-color-contrast/
 */
function getContrastYIQ(hexcolor){
    var r = parseInt(hexcolor.substr(1,2),16);
    var g = parseInt(hexcolor.substr(3,2),16);
    var b = parseInt(hexcolor.substr(5,2),16);
    var yiq = ((r*299)+(g*587)+(b*114))/1000;
    return (yiq >= 128) ? 'black' : 'white';
}
const fruits = ['mango', 'papaya', 'pineapple', 'apple'];

// Iterate over fruits below
fruits.forEach(item => console.log(`I want to eat a ${item}.`));
const addTwo = num => {
  return num + 2;
}

const checkConsistentOutput = (func, val) => {
  let checkA = val + 2;
  let checkB = func(val);
  if (checkA === checkB) {
    return checkB;
  } else {
    console.log(`inconsistent results`);
  }
}

console.log(checkConsistentOutput(addTwo, 2));
let cupsOfSugarNeeded = 2;
let cupsAdded = 0;

do {
  cupsOfSugarNeeded = cupsOfSugarNeeded - cupsAdded;
  cupsAdded++;
  console.log(`Needed: ${cupsOfSugarNeeded}\n Added: ${cupsAdded}`);
} while (cupsAdded < cupsOfSugarNeeded);
/*

This script is meant to be used with a Google Sheets spreadsheet. When you edit a cell containing a
valid CSS hexadecimal colour code (like #000 or #000000), the background colour will be changed to
that colour and the font colour will be changed to the inverse colour for readability.

To use this script in a Google Sheets spreadsheet:
1. go to Tools » Script Editor » Spreadsheet;
2. erase everything in the text editor;
3. change the title to "Set colour preview on edit";
4. paste this code in;
5. click File » Save.
*/

/*********
** Properties
*********/
/**
 * A regex pattern matching a valid CSS hex colour code.
 */
var colourPattern = /^#([0-9a-f]{3})([0-9a-f]{3})?$/i;


/*********
** Event handlers
*********/
/**
 * Sets the foreground or background color of a cell based on its value.
 * This assumes a valid CSS hexadecimal colour code like #FFF or #FFFFFF.
 */
function onEdit(e){
  // iterate over cell range  
  var range = e.range;
  var rowCount = range.getNumRows();
  var colCount = range.getNumColumns();
  for(var r = 1; r <= rowCount; r++) {
    for(var c = 1; c <= colCount; c++) {
      var cell = range.getCell(r, c);
      var value = cell.getValue();

      if(isValidHex(value)) {
        cell.setBackground(value);
        cell.setFontColor(getContrastYIQ(value));
      }
      else {
        cell.setBackground('white');
        cell.setFontColor('black');
      }
    }
  }
};


/*********
** Helpers
*********/
/**
 * Get whether a value is a valid hex colour code.
 */
function isValidHex(hex) {
  return colourPattern.test(hex);
};

/**
 * Change text color to white or black depending on YIQ contrast
 * https://24ways.org/2010/calculating-color-contrast/
 */
function getContrastYIQ(hexcolor){
    var r = parseInt(hexcolor.substr(1,2),16);
    var g = parseInt(hexcolor.substr(3,2),16);
    var b = parseInt(hexcolor.substr(5,2),16);
    var yiq = ((r*299)+(g*587)+(b*114))/1000;
    return (yiq >= 128) ? 'black' : 'white';
}
app.get(%27/ab?cd%27, (req, res) => {
  res.send(%27ab?cd%27)
})
app.get(%27/random.text%27, (req, res) => {
  res.send(%27random.text%27)
})
app.get(%27/about%27, (req, res) => {
  res.send(%27about%27)
})
app.get(%27/%27, (req, res) => {
  res.send(%27root%27)
})
app.all(%27/secret%27, (req, res, next) => {
  console.log(%27Accessing the secret section ...%27)
  next() // pass control to the next handler
})
// GET method route
app.get('/', (req, res) => {
  res.send('GET request to the homepage')
})

// POST method route
app.post('/', (req, res) => {
  res.send('POST request to the homepage')
})
Embark on a lucrative journey with our turnkey vacation rental business – your golden ticket to making money while providing unforgettable travel experiences! Just like Airbnb, We at Appticz develop a vacation rental business that empowers you to transform your property into a revenue-generating oasis. Imagine waking up to a stream of bookings and delighted guests, all while enjoying the financial rewards of the booming vacation rental market. Get a free airbnb clone business quotation.
https://appticz.com/airbnb-clone
localStorage.ampConfig = `{"amp":{"services":{"fitprofile":{"url":"http://127.0.0.1:5500/fitpredictor/demo/dist/loader.js","enabled":"true"},"fitprofilepreview":{"url":"http://127.0.0.1:5500/fitpredictor/demo/dist/fitProfilePreviewLoader.js","enabled":"true"}}}}`
.parent-container{
  //defining a grid container
  display: grid;
  //defining rows and columns
  grid-template: 50px 50px / 50px 50px;
  //defining a row and column gap
  gap: 20px 50px;
  
  
}

When we use the grid-template propertie, we are explicitly defining grid tracks to lay out our grid items. But when the grid needs more tracks for extra content, it will implicitly define new grid tracks. Additionally, the size values established from our grid-template propertie are not carried over into these implicit grid tracks. But we can define values for the implicit grid tracks.

Let’s say we want any new rows to stay the same value as our explicit row track sizes:

.parent-container {
  display: grid;
  grid-template: 50px 50px;
  grid-auto-rows: 50px;
}
<tts service="android" speed="1.0" voice="en-US" style="display: none">{{En}}</tts>
import React, { useState } from 'react';

const App = () => {
  // Initialize with one set of input boxes
  const [inputSets, setInputSets] = useState([{ id: Date.now() }]);

  const handleAddClick = () => {
    // Add a new set of input boxes
    setInputSets([...inputSets, { id: Date.now() }]);
  };

  const handleDeleteClick = (id) => {
    // Ensure at least one set of input boxes remains
    if (inputSets.length > 1) {
      setInputSets(inputSets.filter(set => set.id !== id));
    }
  };

  return (
    <div>
      <button onClick={handleAddClick}>
        Add Input Boxes
      </button>

      {inputSets.map(set => (
        <div key={set.id} style={{ marginBottom: '10px' }}>
          <input type="text" placeholder="Input 1" />
          <input type="text" placeholder="Input 2" />
          {/* Conditionally render the delete button */}
          {inputSets.length > 1 && (
            <button 
              onClick={() => handleDeleteClick(set.id)} 
              style={{ marginLeft: '10px' }}
            >
              Delete
            </button>
          )}
        </div>
      ))}
    </div>
  );
};

export default App;
document.addEventListener("DOMContentLoaded", function() {
  const addIcon = document.getElementById("add-icon");
  const dropdownMenu = document.getElementById("dropdown-menu");
  const wordInput = document.getElementById("word-input");
  const numWordsInput = document.getElementById("num-words-input");
  const generateButton = document.getElementById("generate-button");
  const resultElement = document.getElementById("word-list");
  const resetButton = document.getElementById("reset");
  const saveButton = document.createElement("button");
  saveButton.id = "save-button";
  saveButton.textContent = "Save";
  resetButton.insertAdjacentElement("afterend", saveButton);
  const modal = document.getElementById("listModal");
  const modalBody = document.getElementById("modal-body");
  const createListButton = document.getElementById("create-list");
  const viewListButton = document.getElementById("view-list");
  const closeModalButton = document.getElementById("close-modal");
  const deleteAllButton = document.createElement("button");
  deleteAllButton.id = "delete-all";
  deleteAllButton.textContent = "Delete All";
  closeModalButton.insertAdjacentElement("afterend", deleteAllButton);

  // Store lists in local storage
  let lists = JSON.parse(localStorage.getItem('lists')) || [];
  let definitionMap = {};

  // Toggle dropdown menu visibility
  addIcon.addEventListener("click", function() {
      dropdownMenu.style.display = dropdownMenu.style.display === "block" ? "none" : "block";
  });

  // Hide the dropdown menu if the user clicks outside of it
  document.addEventListener("click", function(event) {
      if (!addIcon.contains(event.target) && !dropdownMenu.contains(event.target)) {
          dropdownMenu.style.display = "none";
      }
  });

  // Create List button click handler
  createListButton.addEventListener("click", function() {
      openCreateListModal();
  });

  // View List button click handler
  viewListButton.addEventListener("click", function() {
      openViewListModal();
  });

  // Close modal when the user clicks on Close button
  closeModalButton.addEventListener("click", function() {
      modal.style.display = "none";
  });

  // Close modal when the user clicks outside of the modal
  window.addEventListener("click", function(event) {
      if (event.target === modal) {
          modal.style.display = "none";
      }
  });

  // Create Flip Card
function createFlipCard(word) {
  const card = document.createElement('li');
  card.classList.add('flip-container');
  card.innerHTML = `
    <div class="flip-card">
      <div class="front">${word}</div>
      <div class="back">${definitionMap[word] || 'Definition not found'}</div>
    </div>
  `;

  card.addEventListener('click', () => {
    card.querySelector('.flip-card').classList.toggle('flipped');
  });

  return card;
}


  // Generate random words with definitions
  async function generateRandomWords() {
      resultElement.classList.remove("error");

      const words = wordInput.value.split(",").map(word => word.trim()).filter(word => word !== "");
      if (words.length === 0) {
          resultElement.classList.add("error");
          resultElement.innerHTML = "Please enter some words separated by commas.";
          return;
      }

      const numWords = Math.min(numWordsInput.value, words.length);
      let selectedWords = getRandomWords(words, numWords);

      resultElement.innerHTML = ''; // Clear previous results
      for (const word of selectedWords) {
          const definition = await fetchDefinition(word);
          definitionMap[word] = definition;
          resultElement.appendChild(createFlipCard(word));
      }
      updateWordCounter();
  }

  // Get random words from the list
  function getRandomWords(words, numWords) {
      const shuffled = words.sort(() => 0.5 - Math.random());
      return shuffled.slice(0, numWords);
  }

  // Fetch word definition from API
  async function fetchDefinition(word) {
      try {
          const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`);
          if (!response.ok) {
              if (response.status === 404) {
                  return "Definition not found.";
              }
              throw new Error("Network response was not ok.");
          }
          const data = await response.json();
          if (data && data[0] && data[0].meanings && data[0].meanings[0] && data[0].meanings[0].definitions && data[0].meanings[0].definitions[0]) {
              return data[0].meanings[0].definitions[0].definition;
          } else {
              return "Definition not found.";
          }
      } catch (error) {
          console.error("Error fetching definition:", error);
          return "Definition not found.";
      }
  }

  // Attach event listeners to buttons
  generateButton.addEventListener("click", generateRandomWords);
  resetButton.addEventListener("click", function() {
      resultElement.innerHTML = "";
      wordInput.value = "";
      numWordsInput.value = 1;
      updateWordCounter();
  });

  // Save button click handler
  saveButton.addEventListener("click", function() {
      const words = wordInput.value.split(",").map(word => word.trim()).filter(word => word !== "");
      if (words.length === 0) {
          alert("Please enter some words to save.");
          return;
      }
      const listName = prompt("Enter the name of the list:");
      if (listName) {
          lists.push({ name: listName, words });
          localStorage.setItem('lists', JSON.stringify(lists));
          alert(`List "${listName}" saved.`);
      } else {
          alert("List name cannot be empty.");
      }
  });

  // Function to open create list modal
  function openCreateListModal() {
      // Clear previous content of modal body
      modalBody.innerHTML = "";

      // Create input field and submit button for entering list name
      const inputField = document.createElement("input");
      inputField.setAttribute("type", "text");
      inputField.setAttribute("placeholder", "Enter the name of the list");
      inputField.style.marginRight = "10px";

      const submitButton = document.createElement("button");
      submitButton.textContent = "Create";
      submitButton.addEventListener("click", function() {
          const listName = inputField.value.trim();
          if (listName) {
              lists.push({ name: listName, words: [] });
              localStorage.setItem('lists', JSON.stringify(lists));
              modal.style.display = "none"; // Hide modal after creating list
              alert(`List "${listName}" created.`);
              inputField.value = ""; // Clear input field
              openViewListModal(); // After creating, open view list modal
          } else {
              alert("Please enter a valid list name.");
          }
      });

      const cancelButton = document.createElement("button");
      cancelButton.textContent = "Cancel";
      cancelButton.addEventListener("click", function() {
          modal.style.display = "none";
      });

      modalBody.appendChild(inputField);
      modalBody.appendChild(submitButton);
      modalBody.appendChild(cancelButton);

      modal.style.display = "block"; // Display modal
      dropdownMenu.style.display = "none"; // Hide dropdown menu
  }

  // Function to open view list modal
  function openViewListModal() {
      if (lists.length === 0) {
          modalBody.innerHTML = "<p>No lists available.</p>";
      } else {
          modalBody.innerHTML = ""; // Clear previous content

          lists.forEach((list, index) => {
              const listItem = document.createElement("div");
              listItem.className = "list-item";
              listItem.textContent = list.name;

              // Add view, open, and delete buttons for each list item
              const viewButton = document.createElement("button");
              viewButton.textContent = "View";
              viewButton.addEventListener("click", function() {
                  openWordListModal(index);
              });

              const openButton = document.createElement("button");
              openButton.textContent = "Open";
              openButton.addEventListener("click", function() {
                  openList(index);
              });

              const deleteButton = document.createElement("button");
              deleteButton.textContent = "Delete";
              deleteButton.addEventListener("click", function() {
                  lists.splice(index, 1);
                  localStorage.setItem('lists', JSON.stringify(lists));
                  openViewListModal(); // Refresh view after deleting
              });

              listItem.appendChild(viewButton);
              listItem.appendChild(openButton);
              listItem.appendChild(deleteButton);
              modalBody.appendChild(listItem);
          });
      }

      modal.style.display = "block"; // Display modal
      dropdownMenu.style.display = "none"; // Hide dropdown menu
  }

  // Function to open word list modal
  function openWordListModal(listIndex) {
      // Clear previous content of modal body
      modalBody.innerHTML = "";

      // Display list name
      const listName = document.createElement("h2");
      listName.textContent = lists[listIndex].name;
      modalBody.appendChild(listName);

      // Display words
      const wordList = document.createElement("ul");
      lists[listIndex].words.forEach(word => {
          const wordItem = document.createElement("li");
          wordItem.textContent = word;
          wordList.appendChild(wordItem);
      });
      modalBody.appendChild(wordList);

      // Add input field and button for adding words to the list
      const wordInputField = document.createElement("input");
      wordInputField.setAttribute("type", "text");
      wordInputField.setAttribute("placeholder", "Enter words separated by commas");
      wordInputField.style.marginRight = "10px";

      const addButton = document.createElement("button");
      addButton.textContent = "Add";
      addButton.addEventListener("click", function() {
          const words = wordInputField.value.split(",").map(word => word.trim());
          lists[listIndex].words.push(...words);
          localStorage.setItem('lists', JSON.stringify(lists));
          openWordListModal(listIndex); // Refresh view after adding words
      });

      const closeButton = document.createElement("button");
      closeButton.textContent = "Close";
      closeButton.addEventListener("click", function() {
          modal.style.display = "none";
      });

      modalBody.appendChild(wordInputField);
      modalBody.appendChild(addButton);
      modalBody.appendChild(closeButton);

      modal.style.display = "block"; // Display modal
  }

  // Function to open list and populate the main search bar
  function openList(listIndex) {
      wordInput.value = lists[listIndex].words.join(", ");
      modal.style.display = "none"; // Hide modal
  }

  // Delete all button click handler
  deleteAllButton.addEventListener("click", function() {
      if (confirm("Are you sure you want to delete all lists?")) {
          lists = [];
          localStorage.setItem('lists', JSON.stringify(lists));
          openViewListModal(); // Refresh view after deleting all lists
      }
  });

  // Function to update word counter
  function updateWordCounter() {
      const wordCount = wordInput.value.split(",").filter(word => word.trim() !== "").length;
      document.getElementById("word-counter").textContent = `${wordCount} words`;
  }

  // Event listener to update word counter when input changes
  wordInput.addEventListener("input", updateWordCounter);

  // Initial call to update word counter on page load
  updateWordCounter();
});
ANIMATION_TIMEOUT = parseInt(getComputedStyle(rootEl).getPropertyValue('--transition-duration'), 10);
// 1. push()
// Appends one or more elements to the end of an array
let arr1 = [1, 2, 3];
arr1.push(4);
console.log(arr1); // [1, 2, 3, 4]

// 2. pop()
// Removes the last element from the array and returns it
let arr2 = [1, 2, 3];
let lastElement = arr2.pop();
console.log(lastElement); // 3
console.log(arr2); // [1, 2]

// 3. shift()
// Removes the first element from the array and returns it
let arr3 = [1, 2, 3];
let firstElement = arr3.shift();
console.log(firstElement); // 1
console.log(arr3); // [2, 3]

// 4. unshift()
// Appends one or more elements to the beginning of an array
let arr4 = [2, 3];
arr4.unshift(1);
console.log(arr4); // [1, 2, 3]

// 5. concat()
// Combines two or more arrays
let arr51 = [1, 2];
let arr52 = [3, 4];
let newArr5 = arr51.concat(arr52);
console.log(newArr5); // [1, 2, 3, 4]


// 6. slice()
// Returns a new array containing part of the original array
let arr6 = [1, 2, 3, 4];
let newArr6 = arr6.slice(1, 3);
console.log(newArr6); // [2, 3]

// 7. splice()
// Changes the contents of an array by removing, replacing, or adding new elements
let arr7 = [1, 2, 3, 4];
arr7.splice(1, 2, 'a', 'b');
console.log(arr7); // [1, 'a', 'b', 4]

// 8. forEach()
// Executes the specified function once for each element of the array
let arr8 = [1, 2, 3];
arr8.forEach(element => console.log(element));
// 1
// 2
// 3

// 9. map()
// Creates a new array with the results of calling the specified function for each element of the array
let arr9 = [1, 2, 3];
let newArr9 = arr9.map(element => element * 2);
console.log(newArr9); // [2, 4, 6]

// 10. filter()
// Creates a new array with all elements that passed the test implemented by the given function
let arr10 = [1, 2, 3, 4];
let newArr10 = arr10.filter(element => element % 2 === 0);
console.log(newArr10); // [2, 4]

// 11. reduce()
// Applies a function to each element of an array (from left to right) to reduce it to a single value
let arr11 = [1, 2, 3, 4];
let sum = arr11.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 10

// 12. find()
// Returns the first element of the array that satisfies the given function
let arr12 = [1, 2, 3, 4];
let found = arr12.find(element => element > 2);
console.log(found); // 3

// 13. findIndex()
// Returns the index of the first array element that satisfies the given function
let arr13 = [1, 2, 3, 4];
let index = arr13.findIndex(element => element > 2);
console.log(index); // 2

// 14. some()
// Checks whether at least one element of the array satisfies the condition implemented by the function
let arr14 = [1, 2, 3, 4];
let hasEven = arr14.some(element => element % 2 === 0);
console.log(hasEven); // true

// 15. every()
// Checks whether all elements of an array satisfy the condition implemented by the function
let arr15 = [1, 2, 3, 4];
let allEven = arr15.every(element => element % 2 === 0);
console.log(allEven); // false

// 16. sort()
// Sorts the elements of an array and returns the sorted array
let arr16 = [3, 1, 4, 2];
arr16.sort();
console.log(arr16); // [1, 2, 3, 4]

// 17. reverse()
// Reverses the order of the elements in the array
let arr17 = [1, 2, 3, 4];
arr17.reverse();
console.log(arr17); // [4, 3, 2, 1]

// 18. join()
// Combines all elements of the array into a row
let arr18 = [1, 2, 3, 4];
let str = arr18.join('-');
console.log(str); // "1-2-3-4"

// 19. includes()
// Tests whether an array contains a specified element
let arr19 = [1, 2, 3, 4];
let hasThree = arr19.includes(3);
console.log(hasThree); // true

// 20. flat()
// Creates a new array with all subarray elements submerged to the specified depth
let arr20 = [1, [2, [3, [4]]]];
let flatArr = arr20.flat(2);
console.log(flatArr); // [1, 2, 3, [4]]

// 21. flatMap()
// First, it displays each element using a function, and then sums the result into a new array
let arr21 = [1, 2, 3];
let flatMappedArr = arr21.flatMap(element => [element, element * 2]);
console.log(flatMappedArr); // [1, 2, 2, 4, 3, 6]
javascript: (function () {
  let host = location.host;
  if (host.includes("youtube.com")) {
    const emb = document
      .querySelector("link[itemprop='embedUrl']")
      .getAttribute("href");
    window.location.assign(emb);
  } else {
    window.alert("⚠️not YouTube");
  }
})();
The for...of loop
The basic tool for looping through a collection is the for...of loop:

js
Copy to Clipboard
const cats = ["Leopard", "Serval", "Jaguar", "Tiger", "Caracal", "Lion"];

for (const cat of cats) {
  console.log(cat);
}
In this example, for (const cat of cats) says:

Given the collection cats, get the first item in the collection.
Assign it to the variable cat and then run the code between the curly braces {}.
Get the next item, and repeat (2) until you've reached the end of the collection.

-------------------------------------------------
  
map() and filter()
JavaScript also has more specialized loops for collections, and we'll mention two of them here.

You can use map() to do something to each item in a collection and create a new collection containing the changed items:

js
Copy to Clipboard
function toUpper(string) {
  return string.toUpperCase();
}

const cats = ["Leopard", "Serval", "Jaguar", "Tiger", "Caracal", "Lion"];

const upperCats = cats.map(toUpper);

console.log(upperCats);
// [ "LEOPARD", "SERVAL", "JAGUAR", "TIGER", "CARACAL", "LION" ]
Here we pass a function into cats.map(), and map() calls the function once for each item in the array, passing in the item. It then adds the return value from each function call to a new array, and finally returns the new array. In this case the function we provide converts the item to uppercase, so the resulting array contains all our cats in uppercase:

js
Copy to Clipboard
[ "LEOPARD", "SERVAL", "JAGUAR", "TIGER", "CARACAL", "LION" ]

You can use filter() to test each item in a collection, and create a new collection containing only items that match:

js
Copy to Clipboard
function lCat(cat) {
  return cat.startsWith("L");
}

const cats = ["Leopard", "Serval", "Jaguar", "Tiger", "Caracal", "Lion"];

const filtered = cats.filter(lCat);

console.log(filtered);
// [ "Leopard", "Lion" ]
This looks a lot like map(), except the function we pass in returns a boolean: if it returns true, then the item is included in the new array. Our function tests that the item starts with the letter "L", so the result is an array containing only cats whose names start with "L":

js
Copy to Clipboard
[ "Leopard", "Lion" ]

Note that map() and filter() are both often used with function expressions, which we will learn about in the Functions module. Using function expressions we could rewrite the example above to be much more compact:

js
Copy to Clipboard
const cats = ["Leopard", "Serval", "Jaguar", "Tiger", "Caracal", "Lion"];

const filtered = cats.filter((cat) => cat.startsWith("L"));
console.log(filtered);
// [ "Leopard", "Lion" ]

-------------------------------------------------
  
The standard for loop
In the "drawing circles" example above, you don't have a collection of items to loop through: you really just want to run the same code 100 times. In a case like that, you should use the for loop. This has the following syntax:

js
Copy to Clipboard
for (initializer; condition; final-expression) {
  // code to run
}
Here we have:

The keyword for, followed by some parentheses.
Inside the parentheses we have three items, separated by semicolons:
An initializer — this is usually a variable set to a number, which is incremented to count the number of times the loop has run. It is also sometimes referred to as a counter variable.
A condition — this defines when the loop should stop looping. This is generally an expression featuring a comparison operator, a test to see if the exit condition has been met.
A final-expression — this is always evaluated (or run) each time the loop has gone through a full iteration. It usually serves to increment (or in some cases decrement) the counter variable, to bring it closer to the point where the condition is no longer true.
Some curly braces that contain a block of code — this code will be run each time the loop iterates.

-------------------------------------------------

Exiting loops with break
If you want to exit a loop before all the iterations have been completed, you can use the break statement. We already met this in the previous article when we looked at switch statements — when a case is met in a switch statement that matches the input expression, the break statement immediately exits the switch statement and moves on to the code after it.

It's the same with loops — a break statement will immediately exit the loop and make the browser move on to any code that follows it.
  
Skipping iterations with continue
The continue statement works similarly to break, but instead of breaking out of the loop entirely, it skips to the next iteration of the loop. Let's look at another example that takes a number as an input, and returns only the numbers that are squares of integers (whole numbers).
  
-------------------------------------------------
  

while and do...while
for is not the only type of loop available in JavaScript. There are actually many others and, while you don't need to understand all of these now, it is worth having a look at the structure of a couple of others so that you can recognize the same features at work in a slightly different way.

First, let's have a look at the while loop. This loop's syntax looks like so:

js
Copy to Clipboard
initializer
while (condition) {
  // code to run

  final-expression
}
This works in a very similar way to the for loop, except that the initializer variable is set before the loop, and the final-expression is included inside the loop after the code to run, rather than these two items being included inside the parentheses. The condition is included inside the parentheses, which are preceded by the while keyword rather than for.

The same three items are still present, and they are still defined in the same order as they are in the for loop. This is because you must have an initializer defined before you can check whether or not the condition is true. The final-expression is then run after the code inside the loop has run (an iteration has been completed), which will only happen if the condition is still true.


The do...while loop is very similar, but provides a variation on the while structure:

js
Copy to Clipboard
initializer
do {
  // code to run

  final-expression
} while (condition)
In this case, the initializer again comes first, before the loop starts. The keyword directly precedes the curly braces containing the code to run and the final expression.

The main difference between a do...while loop and a while loop is that the code inside a do...while loop is always executed at least once. That's because the condition comes after the code inside the loop. So we always run that code, then check to see if we need to run it again. In while and for loops, the check comes first, so the code might never be executed.
    
    
Which loop type should you use?
If you're iterating through an array or some other object that supports it, and don't need access to the index position of each item, then for...of is the best choice. It's easier to read and there's less to go wrong.

For other uses, for, while, and do...while loops are largely interchangeable. They can all be used to solve the same problems, and which one you use will largely depend on your personal preference — which one you find easiest to remember or most intuitive. We would recommend for, at least to begin with, as it is probably the easiest for remembering everything — the initializer, condition, and final-expression all have to go neatly into the parentheses, so it is easy to see where they are and check that you aren't missing them.
The map method
map is one such function. It expects a callback as an argument, which is a fancy way to say “I want you to pass another function as an argument to my function”.

Let’s say we had a function addOne, which takes in num as an argument and outputs that num increased by 1. And let’s say we had an array of numbers, [1, 2, 3, 4, 5] and we’d like to increment all of these numbers by 1 using our addOne function. Instead of making a for loop and iterating over the above array, we could use our map array method instead, which automatically iterates over an array for us. We don’t need to do any extra work aside from simply passing the function we want to use in:

function addOne(num) {
  return num + 1;
}
const arr = [1, 2, 3, 4, 5];
const mappedArr = arr.map(addOne);
console.log(mappedArr); // Outputs [2, 3, 4, 5, 6]
map returns a new array and does not change the original array.

// The original array has not been changed!
console.log(arr); // Outputs [1, 2, 3, 4, 5]
This is a much more elegant approach, what do you think? For simplicity, we could also define an inline function right inside of map like so:

const arr = [1, 2, 3, 4, 5];
const mappedArr = arr.map((num) => num + 1);
console.log(mappedArr); // Outputs [2, 3, 4, 5, 6]

-----------------------------------------------------

The filter method
filter is somewhat similar to map. It still iterates through the array and applies the callback function on every item. However, instead of transforming the values in the array, it returns the original values of the array, but only IF the callback function returns true. Let’s say we had a function, isOdd that returns either true if a number is odd or false if it isn’t.

The filter method expects the callback to return either true or false. If it returns true, the value is included in the output. Otherwise, it isn’t. Consider the array from our previous example, [1, 2, 3, 4, 5]. If we wanted to remove all even numbers from this array, we could use .filter() like this:

function isOdd(num) {
  return num % 2 !== 0;
}
const arr = [1, 2, 3, 4, 5];
const oddNums = arr.filter(isOdd);
console.log(oddNums); // Outputs [1, 3, 5];
console.log(arr); // Outputs [1, 2, 3, 4, 5], original array is not affected
filter will iterate through arr and pass every value into the isOdd callback function, one at a time.
isOdd will return true when the value is odd, which means this value is included in the output.
If it’s an even number, isOdd will return false and not include it in the final output.

-----------------------------------------------------
  
The reduce method
Finally, let’s say that we wanted to multiply all of the numbers in our arr together like this: 1 * 2 * 3 * 4 * 5. First, we’d have to declare a variable total and initialize it to 1. Then, we’d iterate through the array with a for loop and multiply the total by the current number.

But we don’t actually need to do all of that, we have our reduce method that will do the job for us. Just like .map() and .filter() it expects a callback function. However, there are two key differences with this array method:

The callback function takes two arguments instead of one. The first argument is the accumulator, which is the current value of the result at that point in the loop. The first time through, this value will either be set to the initialValue (described in the next bullet point), or the first element in the array if no initialValue is provided. The second argument for the callback is the current value, which is the item currently being iterated on.
It also takes in an initialValue as a second argument (after the callback), which helps when we don’t want our initial value to be the first element in the array. For instance, if we wanted to sum all numbers in an array, we could call reduce without an initialValue, but if we wanted to sum all numbers in an array and add 10, we could use 10 as our initialValue.
const arr = [1, 2, 3, 4, 5];
const productOfAllNums = arr.reduce((total, currentItem) => {
  return total * currentItem;
}, 1);
console.log(productOfAllNums); // Outputs 120;
console.log(arr); // Outputs [1, 2, 3, 4, 5]
In the above function, we:

Pass in a callback function, which is (total, currentItem) => total * currentItem.
Initialize total to 1 in the second argument.
So what .reduce() will do, is it will once again go through every element in arr and apply the callback function to it. It then changes total, without actually changing the array itself. After it’s done, it returns total.
app.post('/send-otp', async (req, res) => {
  const { phoneNumber } = req.body;

  const apiKey = '3mW3hfluK8dpayQ53NXKdBhophrKP9sD8GKPi8qKqsMTZAAEsyq8HGMZCeSv';
  const otp = Math.floor(100000 + Math.random() * 900000); // Generate a 6-digit OTP
  const message = `${otp}`;

  const data = {
      sender_id: 'TKSOLV',
      message: '110131',
      variables_values: message,
      route: 'dlt',
      numbers: phoneNumber,
  };

  const options = {
      method: 'POST',
      headers: {
          'authorization': apiKey,
          'Content-Type': 'application/json'
      },
      data: JSON.stringify(data),
      url: 'https://www.fast2sms.com/dev/bulkV2',
  };

  try {
      const response = await axios(options);
      res.status(200).send({ success: true, message: 'OTP sent successfully', otp: otp });
  } catch (error) {
      res.status(500).send({ success: false, message: 'Failed to send OTP', error: error.message });
  }
});

// Try this simple way

const today = new Date();
let date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
console.log(date);
//You can copy a JSON list of all the extensions and their URLs by going to chrome://extensions and entering this in your console
document.querySelector('extensions-manager').extensions_.map(({id, name, state, webStoreUrl}) => ({id, name, state, webStoreUrl}))
// App.tsx
import React, { useState } from 'react';
import './App.css';

function App() {
  const [top, setTop] = useState(0);
  const [left, setLeft] = useState(0);
  const [backgroundColor, setBackgroundColor] = useState('#ffffff')

  const keyDownHandler = (e: React.KeyboardEvent<HTMLDivElement>) => {
    const key = e.code;

    if (key === 'ArrowUp') {
      setTop((top) => top - 10);
    }

    if (key === 'ArrowDown') {
      setTop((top) => top + 10);
    }

    if (key === 'ArrowLeft') {
      setLeft((left) => left - 10);
    }

    if (key === 'ArrowRight') {
      setLeft((left) => left + 10);
    }

    if (key === 'Space') {
      let color = Math.floor(Math.random() * 0xFFFFFF).toString(16);
      for(let count = color.length; count < 6; count++) {
        color = '0' + color;                     
      }
      setBackgroundColor('#' + color);
    }
  }

  return (
    <div
      className="container"
      tabIndex={0}
      onKeyDown={keyDownHandler}
    >
      <div
        className="box"
        style={{ 
          top: top,
          left: left,
          backgroundColor: backgroundColor,
        }}></div>
    </div>
  );
}

export default App;
function sum(...numbers) {
  // The rest operator is three dots followed by the variable name; by convention, it is typically called 'rest'
  // The rest operator must be the last parameter in the function definition
  return numbers.reduce((acc, val) => acc + val, 0);
}   // The reduce method is used to sum all the numbers in the array
You can use the async keyword to create an asynchronous function, which returns a promise.

Example Code
const example = async () => {
  console.log("this is an example");
};

The try block is designed to handle potential errors, and the code inside the catch block will be executed in case an error occurs.

Example Code
try {
  const name = "freeCodeCamp";
  name = "fCC";
} catch (err) {
  console.log(err); // TypeError: Assignment to constant variable.
}

The await keyword waits for a promise to resolve and returns the result.

Example Code
const example = async () => {
  const data = await fetch("https://example.com/api");
  console.log(data);
}
The Fetch API is a built-in JavaScript interface to make network requests to a server. It has a fetch() method you can use to make GET, POST, PUT, or PATCH requests. In this project, you'll make a GET request to a URL for a JSON file with information about authors on freeCodeCamp News.

Here is how you can make a GET request with the fetch() method:

Example Code
fetch("url-goes-here")

The fetch() method returns a Promise, which is a placeholder object that will either be fulfilled if your request is successful, or rejected if your request is unsuccessful.

If the Promise is fulfilled, it resolves to a Response object, and you can use the .then() method to access the Response.

Here's how you can chain .then() to the fetch() method:

Example Code
fetch("sample-url-goes-here")
  .then((res) => res)

The data you get from a GET request is not usable at first. To make the data usable, you can use the .json() method on the Response object to parse it into JSON. If you expand the Prototype of the Response object in the console, you will see the .json() method there.

In order to start working with the data, you will need to use another .then() method.

Chain another .then() to the existing .then() method. This time, pass in data as the parameter for the callback function. For the callback, use a curly brace because you will have more than one expression.

The .catch() method is another asynchronous JavaScript method you can use to handle errors. This is useful in case the Promise gets rejected.
<style>
.content-hide {
    display: none;
}

.details-area {
    max-height: 70px;
    overflow: hidden;
    transition: max-height 0.5s ease;
}

.show-more, .show-less {
cursor: pointer;
}

</style>

<script type="text/javascript">
var $ = jQuery;
$(document).ready(function() {
    $('.show-more').on('click', function(event) {
        event.preventDefault();
        var profileCard = $(this).closest('.profile-card');
        var detailsArea = profileCard.find('.details-area');
        
        $(this).addClass('content-hide');
        profileCard.find('.show-less').removeClass('content-hide');

        detailsArea.css('max-height', detailsArea[0].scrollHeight + 'px'); // Rozwijanie
    });

    $('.show-less').on('click', function(event) {
        event.preventDefault();
        var profileCard = $(this).closest('.profile-card');
        var detailsArea = profileCard.find('.details-area');
        
        $(this).addClass('content-hide');
        profileCard.find('.show-more').removeClass('content-hide');
        
        detailsArea.css('max-height', '70px'); // Zwijanie
    });
});
</script>
    function showPreview(event){
  if(event.target.files.length > 0){
    var src = URL.createObjectURL(event.target.files[0]);
    var preview = document.getElementById("file-ip-1-preview");
    preview.src = src;
    preview.style.display = "block";
  }
}
<!DOCTYPE html>
<html>
​
<body>
  
<script>
class Car {
  constructor(name) {
    this.brand = name;
  }
​
  present() {
    return 'I have a ' + this.brand;
  }
}
​
class Model extends Car {
  constructor(name, mod) {
    super(name);
    this.model = mod;
  }  
  show() {
    return this.present() + ', it is a ' + this.model
  }
}
​
const mycar = new Model("Ford", "Mustang");
document.write(mycar.show());
</script>
​
</body>
</html>
​
<!DOCTYPE html>
<html>
​
<body>
  
<script>
class Car {
  constructor(name) {
    this.brand = name;
  }
}
​
const mycar = new Car("Ford");
​
document.write(mycar.brand);
</script>
​
</body>
</html>
​
new Card(cardContainer, {
    id: 'instructions',
    icon: 'fa-solid fa-medal',
    title: 'Contests',
    description: 'Where the magic happens! Manage contests and their teams.',
}).click(async () => {
    const modal = await new Modal(null, { id: 'instructions' }).loadContent('index-instructions');
    modal.addButton({
        text: 'OK, got it!',
        close: true,
    })
});
JavaScript
<script>
document.addEventListener('scroll', function(e) {
var header = document.getElementById('sticky-header');
var scrollTop = window.scrollY || document.documentElement.scrollTop;

if (scrollTop > lastScrollTop) {
// Scroll Down
header.style.transform = 'translateY(-100%)';
} else {
// Scroll Up
header.style.transform = 'translateY(0)';
}
lastScrollTop = scrollTop <= 0 ? 0 : scrollTop; // For Mobile or negative scrolling
}, false);

var lastScrollTop = 0;
</script>

CSS
#sticky-header {
transition: transform 0.3s ease-in-out;
}
<script src="https://cdn.jsdelivr.net/gh/studio-freight/lenis@0.2.28/bundled/lenis.js"></script>

<script>
const lenis = new Lenis({
  duration: 1.2,
  easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)), // https://www.desmos.com/calculator/brs54l4xou
  direction: 'vertical', // vertical, horizontal
  gestureDirection: 'vertical', // vertical, horizontal, both
  smooth: true,
  mouseMultiplier: 1,
  smoothTouch: false,
  touchMultiplier: 2,
  infinite: false,
})

//get scroll value
lenis.on('scroll', ({ scroll, limit, velocity, direction, progress }) => {
  console.log({ scroll, limit, velocity, direction, progress })
})

function raf(time) {
  lenis.raf(time)
  requestAnimationFrame(raf)
}

requestAnimationFrame(raf)
</script>
The Canvas API can be used to create graphics in games using JavaScript and the HTML canvas element.

You will need to use the getContext method which will provide the context for where the graphics will be rendered.

Example Code
canvas.getContext("2d");

The canvas element has a width property which is a positive number that represents the width of the canvas.

Example Code
canvas.width

The innerWidth property is a number that represents the interior width of the browser window.

The innerHeight property is a number that represents the interior height of the browser window.

Here is the syntax for using the destructuring assignment in the parameter list of the arrow function:

Example Code
btn.addEventListener('click', ({ target }) => {
  console.log(target);
});

When working with objects where the property name and value are the same, you can use the shorthand property name syntax. This syntax allows you to omit the property value if it is the same as the property name.

Example Code
// using shorthand property name syntax
obj = {
  a, b, c
}
The following code is the same as:

Example Code
obj = {
  a: a,
  b: b,
  c: c
}
const user = {
  
  "intro":  {
    "name" : "Saud",
    "age" : 20,
    "qualification": "BS Computer"
  },
  
  "address": {
    "country" : "Pakistan",
    "province" : "KP",
    "city" : "Mardan"
  },
  
  userIntro(){
    return `Name: ${this.intro.name}, age: ${this.intro.age}, qualification: ${this.intro.qualification}`;
  },

  userAddress(){
    return `country: ${this.address.country}, province: ${this.address.province}, city: ${this.address.city}`
  }
}

// let name = user.intro.name;
// console.log(name);

let userData = user.userIntro();
console.log(userData);

let addressData = user.userAddress()
console.log(addressData);

  content: ["./app/**/*.{js,jsx,ts,tsx}", "./components/**/*.{js,jsx,ts,tsx}"],

   
   
   
   
   da babelshi es --> 
     
  plugins: ["nativewind/babel"],
npm install --save-dev tailwindcss@latest
 npx expo install expo-router react-native-safe-area-context react-native-screens expo-linking expo-constants expo-status-bar
npx create-expo-app@latest [your-app-name] --template blank@latest  
You are already familiar with an HTML class, but JavaScript also has a class. In JavaScript, a class is like a blueprint for creating objects. It allows you to define a set of properties and methods, and instantiate (or create) new objects with those properties and methods.

The class keyword is used to declare a class. Here is an example of declaring a Computer class:

Example Code
class Computer {};

Classes have a special constructor method, which is called when a new instance of the class is created. The constructor method is a great place to initialize properties of the class. Here is an example of a class with a constructor method:

Example Code
class Computer {
  constructor() {
  }
}

The this keyword in JavaScript is used to refer to the current object. Depending on where this is used, what it references changes. In the case of a class, it refers to the instance of the object being constructed. You can use the this keyword to set the properties of the object being instantiated. Here is an example:

Example Code
class Computer {
  constructor() {
    this.ram = 16;
  }
}

Here is an example of instantiating the Computer class from earlier examples:

Example Code
const myComputer = new Computer();

var link = React.DOM.a({
                    href: this.makeHref('login')
                },
                'log in'
            );// or React.createElement or
//var link = <a href={this.makeHref('login')}>
//   'log in'</a>;
<div>{'Please '+ link + ' with your email...'}</div>
Functions are ideal for reusable logic. When a function itself needs to reuse logic, you can declare a nested function to handle that logic. Here is an example of a nested function:

Example Code
const outer = () => {
  const inner = () => {

  };
};

Object properties consist of key/value pairs. You can use shorthand property names when declaring an object literal. When using the shorthand property name syntax, the name of the variable becomes the property key and its value the property value.

The following example declares a user object with the properties userId, firstName, and loggedIn.

Example Code
const userId = 1;
const firstName = "John";
const loggedIn = true;

const user = {
  userId,
  firstName,
  loggedIn,
};

console.log(user); // { userId: 1, firstName: 'John', loggedIn: true }

The concept of returning a function within a function is called currying. This approach allows you to create a variable that holds a function to be called later, but with a reference to the parameters of the outer function call.

For example:

Example Code
const innerOne = elemValue(1);
const final = innerOne("A");
innerOne would be your inner function, with num set to 1, and final would have the value of the cell with the id of A1. This is possible because functions have access to all variables declared at their creation. This is called closure.

In your elemValue function, you explicitly declared a function called inner and returned it. However, because you are using arrow syntax, you can implicitly return a function. For example:

Example Code
const curry = soup => veggies => {};
curry is a function which takes a soup parameter and returns a function which takes a veggies parameter.

You can pass a function reference as a callback parameter. A function reference is a function name without the parentheses. For example:

Example Code
const myFunc = (val) => `value: ${val}`;
const array = [1, 2, 3];
const newArray = array.map(myFunc);
The .map() method here will call the myFunc function, passing the same arguments that a .map() callback takes. The first argument is the value of the array at the current iteration, so newArray would be [value: 1, value: 2, value: 3].

Arrays have a .some() method. Like the .filter() method, .some() accepts a callback function which should take an element of the array as the argument. The .some() method will return true if the callback function returns true for at least one element in the array.

Here is an example of a .some() method call to check if any element in the array is an uppercase letter.

Example Code
const arr = ["A", "b", "C"];
arr.some(letter => letter === letter.toUpperCase());

Arrays have an .every() method. Like the .some() method, .every() accepts a callback function which should take an element of the array as the argument. The .every() method will return true if the callback function returns true for all elements in the array.

Here is an example of a .every() method call to check if all elements in the array are uppercase letters.

Example Code
const arr = ["A", "b", "C"];
arr.every(letter => letter === letter.toUpperCase());
The .split() method takes a string and splits it into an array of strings. You can pass it a string of characters or a RegEx to use as a separator. For example, string.split(",") would split the string at each comma and return an array of strings.

The .map() method takes a callback function as its first argument. This callback function takes a few arguments, but the first one is the current element being processed. Here is an example:

Example Code
array.map(el => {

})

Much like the .map() method, the .filter() method takes a callback function. The callback function takes the current element as its first argument.

Example Code
array.filter(el => {

})

Array methods can often be chained together to perform multiple operations at once. As an example:

Example Code
array.map().filter();
The .map() method is called on the array, and then the .filter() method is called on the result of the .map() method. This is called method chaining.

The .reduce() method takes an array and applies a callback function to condense the array into a single value.

Like the other methods, .reduce() takes a callback. This callback, however, takes at least two parameters. The first is the accumulator, and the second is the current element in the array. The return value for the callback becomes the value of the accumulator on the next iteration.

Example Code
array.reduce((acc, el) => {

});

The .reduce() method takes a second argument that is used as the initial value of the accumulator. Without a second argument, the .reduce() method uses the first element of the array as the accumulator, which can lead to unexpected results.

To be safe, it's best to set an initial value. Here is an example of setting the initial value to an empty string:

Example Code
array.reduce((acc, el) => acc + el.toLowerCase(), "");

By default, the .sort() method converts the elements of an array into strings, then sorts them alphabetically. This works well for strings, but not so well for numbers. For example, 10 comes before 2 when sorted as strings, but 2 comes before 10 when sorted as numbers.

To fix this, you can pass in a callback function to the .sort() method. This function takes two arguments, which represent the two elements being compared. The function should return a value less than 0 if the first element should come before the second element, a value greater than 0 if the first element should come after the second element, and 0 if the two elements should remain in their current positions.

You previously learned about the global Math object. Math has a .min() method to get the smallest number from a series of numbers, and the .max() method to get the largest number. Here's an example that gets the smallest number from an array:

Example Code
const numbersArr = [2, 3, 1];

console.log(Math.min(...numbersArr));
// Expected output: 1

To calculate a root exponent, such as x−−√n
, you can use an inverted exponent x1/n
. JavaScript has a built-in Math.pow() function that can be used to calculate exponents.

Here is the basic syntax for the Math.pow() function:

Example Code
Math.pow(base, exponent);
Here is an example of how to calculate the square root of 4:

Example Code
const base = 4;
const exponent = 0.5;
// returns 2
Math.pow(base, exponent);
window.pixelmatch = (() => {
  var __getOwnPropNames = Object.getOwnPropertyNames;
  var __commonJS = (cb, mod) => function __require() {
    return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  };

  // entry.js
  var require_entry = __commonJS({
    "entry.js"(exports, module) {
      module.exports = pixelmatch;
      var defaultOptions = {
        threshold: 0.1,
        // matching threshold (0 to 1); smaller is more sensitive
        includeAA: false,
        // whether to skip anti-aliasing detection
        alpha: 0.1,
        // opacity of original image in diff output
        aaColor: [255, 255, 0],
        // color of anti-aliased pixels in diff output
        diffColor: [255, 0, 0],
        // color of different pixels in diff output
        diffColorAlt: null,
        // whether to detect dark on light differences between img1 and img2 and set an alternative color to differentiate between the two
        diffMask: false
        // draw the diff over a transparent background (a mask)
      };
      function pixelmatch(img1, img2, output, width, height, options) {
        if (!isPixelData(img1) || !isPixelData(img2) || output && !isPixelData(output))
          throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");
        if (img1.length !== img2.length || output && output.length !== img1.length)
          throw new Error("Image sizes do not match.");
        if (img1.length !== width * height * 4) throw new Error("Image data size does not match width/height.");
        options = Object.assign({}, defaultOptions, options);
        const len = width * height;
        const a32 = new Uint32Array(img1.buffer, img1.byteOffset, len);
        const b32 = new Uint32Array(img2.buffer, img2.byteOffset, len);
        let identical = true;
        for (let i = 0; i < len; i++) {
          if (a32[i] !== b32[i]) {
            identical = false;
            break;
          }
        }
        if (identical) {
          if (output && !options.diffMask) {
            for (let i = 0; i < len; i++) drawGrayPixel(img1, 4 * i, options.alpha, output);
          }
          return 0;
        }
        const maxDelta = 35215 * options.threshold * options.threshold;
        let diff = 0;
        for (let y = 0; y < height; y++) {
          for (let x = 0; x < width; x++) {
            const pos = (y * width + x) * 4;
            const delta = colorDelta(img1, img2, pos, pos);
            if (Math.abs(delta) > maxDelta) {
              if (!options.includeAA && (antialiased(img1, x, y, width, height, img2) || antialiased(img2, x, y, width, height, img1))) {
                if (output && !options.diffMask) drawPixel(output, pos, ...options.aaColor);
              } else {
                if (output) {
                  drawPixel(output, pos, ...delta < 0 && options.diffColorAlt || options.diffColor);
                }
                diff++;
              }
            } else if (output) {
              if (!options.diffMask) drawGrayPixel(img1, pos, options.alpha, output);
            }
          }
        }
        return diff;
      }
      function isPixelData(arr) {
        return ArrayBuffer.isView(arr) && arr.constructor.BYTES_PER_ELEMENT === 1;
      }
      function antialiased(img, x1, y1, width, height, img2) {
        const x0 = Math.max(x1 - 1, 0);
        const y0 = Math.max(y1 - 1, 0);
        const x2 = Math.min(x1 + 1, width - 1);
        const y2 = Math.min(y1 + 1, height - 1);
        const pos = (y1 * width + x1) * 4;
        let zeroes = x1 === x0 || x1 === x2 || y1 === y0 || y1 === y2 ? 1 : 0;
        let min = 0;
        let max = 0;
        let minX, minY, maxX, maxY;
        for (let x = x0; x <= x2; x++) {
          for (let y = y0; y <= y2; y++) {
            if (x === x1 && y === y1) continue;
            const delta = colorDelta(img, img, pos, (y * width + x) * 4, true);
            if (delta === 0) {
              zeroes++;
              if (zeroes > 2) return false;
            } else if (delta < min) {
              min = delta;
              minX = x;
              minY = y;
            } else if (delta > max) {
              max = delta;
              maxX = x;
              maxY = y;
            }
          }
        }
        if (min === 0 || max === 0) return false;
        return hasManySiblings(img, minX, minY, width, height) && hasManySiblings(img2, minX, minY, width, height) || hasManySiblings(img, maxX, maxY, width, height) && hasManySiblings(img2, maxX, maxY, width, height);
      }
      function hasManySiblings(img, x1, y1, width, height) {
        const x0 = Math.max(x1 - 1, 0);
        const y0 = Math.max(y1 - 1, 0);
        const x2 = Math.min(x1 + 1, width - 1);
        const y2 = Math.min(y1 + 1, height - 1);
        const pos = (y1 * width + x1) * 4;
        let zeroes = x1 === x0 || x1 === x2 || y1 === y0 || y1 === y2 ? 1 : 0;
        for (let x = x0; x <= x2; x++) {
          for (let y = y0; y <= y2; y++) {
            if (x === x1 && y === y1) continue;
            const pos2 = (y * width + x) * 4;
            if (img[pos] === img[pos2] && img[pos + 1] === img[pos2 + 1] && img[pos + 2] === img[pos2 + 2] && img[pos + 3] === img[pos2 + 3]) zeroes++;
            if (zeroes > 2) return true;
          }
        }
        return false;
      }
      function colorDelta(img1, img2, k, m, yOnly) {
        let r1 = img1[k + 0];
        let g1 = img1[k + 1];
        let b1 = img1[k + 2];
        let a1 = img1[k + 3];
        let r2 = img2[m + 0];
        let g2 = img2[m + 1];
        let b2 = img2[m + 2];
        let a2 = img2[m + 3];
        if (a1 === a2 && r1 === r2 && g1 === g2 && b1 === b2) return 0;
        if (a1 < 255) {
          a1 /= 255;
          r1 = blend(r1, a1);
          g1 = blend(g1, a1);
          b1 = blend(b1, a1);
        }
        if (a2 < 255) {
          a2 /= 255;
          r2 = blend(r2, a2);
          g2 = blend(g2, a2);
          b2 = blend(b2, a2);
        }
        const y1 = rgb2y(r1, g1, b1);
        const y2 = rgb2y(r2, g2, b2);
        const y = y1 - y2;
        if (yOnly) return y;
        const i = rgb2i(r1, g1, b1) - rgb2i(r2, g2, b2);
        const q = rgb2q(r1, g1, b1) - rgb2q(r2, g2, b2);
        const delta = 0.5053 * y * y + 0.299 * i * i + 0.1957 * q * q;
        return y1 > y2 ? -delta : delta;
      }
      function rgb2y(r, g, b) {
        return r * 0.29889531 + g * 0.58662247 + b * 0.11448223;
      }
      function rgb2i(r, g, b) {
        return r * 0.59597799 - g * 0.2741761 - b * 0.32180189;
      }
      function rgb2q(r, g, b) {
        return r * 0.21147017 - g * 0.52261711 + b * 0.31114694;
      }
      function blend(c, a) {
        return 255 + (c - 255) * a;
      }
      function drawPixel(output, pos, r, g, b) {
        output[pos + 0] = r;
        output[pos + 1] = g;
        output[pos + 2] = b;
        output[pos + 3] = 255;
      }
      function drawGrayPixel(img, i, alpha, output) {
        const r = img[i + 0];
        const g = img[i + 1];
        const b = img[i + 2];
        const val = blend(rgb2y(r, g, b), alpha * img[i + 3] / 255);
        drawPixel(output, i, val, val, val);
      }
    }
  });
  return require_entry();
})();
// ==UserScript==
// @name         spys.one proxy parser
// @namespace    iquaridys:hideme-parser-proxy
// @version      0.1
// @description  parse proxy from site page
// @author       iquaridys
// @match        http://spys.one/*/
// @grant        GM_registerMenuCommand
// ==/UserScript==

(function() {
    'use strict';
    GM_registerMenuCommand('Parse', function() {
        var resultText = "";
        var a = document.getElementsByClassName('spy14');
            for(var i=0;i<a.length;i++){
                if(a[i].innerText.includes(':')){
                    resultText += a[i].innerText+"<br>";
                }
            }
        var win = window.open("about:blank", "proxy", "width=500,height=400");
        win.document.write(resultText);
    });
})();
<script type="text/javascript" async>
    ////add Attrs alt to images	
	function addAltAttrs() {
			
    //get the images
    let images = document.querySelectorAll("img"); 
     
    //loop through all images
    for (let i = 0; i < images.length; i++) {
		
       //check if alt missing
       if  ( !images[i].alt || images[i].alt == "" || images[i].alt === "") {
		//add file name to alt
         images[i].alt = images[i].src.match(/.*\/([^/]+)\.([^?]+)/i)[1];
       }
    } 
    // end loop
}
</script>
<!-- in css: -->
<style>
  #p-bar-wrapper {
   	display:none;
   	position: fixed;
   	bottom: 0;
   	right: 0;
   	width: 100vw;
   	height: 8px;
   	background-color:#d1d6d8;
   	z-index: 18;
  }
  #progress-bar {
   	background-color:#295b71;
   	width: 0;
   	height: 8px;
   	transition: .3s;
  }
  #progress-bar span {
   	position: absolute;
   	color: #42616c;
   	top: -18px;
   	font-size: 0.8em;
   	font-weight: 600;
   	margin-right:0;
  }
  #run-bar.right-fix {
   	margin-right: -80px;
  }
  #run-bar.right-fix-2one {
   	margin-right: -77px;
  }
</style>

<!-- in html: -->
<div id="p-bar-wrapper">
    <div id="progress-bar"><span id="run-bar"></span></div>
</div>

<!-- in js: -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js" crossorigin="anonymous"></script>
<script type="text/javascript" async>
    document.addEventListener("DOMContentLoaded", function() {
    	  document.addEventListener("scroll", function() {
    	    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    	    var scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
    		var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
    		var windowWidth = window.innerWidth;
    		var p_bar =	document.getElementById("progress-bar");
    		var scrolled = (scrollTop / (scrollHeight - clientHeight)) * 100;
     
     	//Check if Tablet or smaller than hide all progress bar
    		if( windowWidth < 767 ){
    			return;
    		}
    		else {
    			jQuery("#p-bar-wrapper").css('display','block').show('slow');
    			p_bar.style.width = scrolled + "%";
    			var scrolled_num = parseInt(scrolled, 10);
    			var span_run = document.getElementById("run-bar");
    			jQuery(span_run).text(scrolled_num + '%').css('right',scrolled + '%');
    				if (scrolled == 100){
    					jQuery(span_run).addClass('right-fix-2one').css('color','#21f1af');
    				}
    				else {
    					jQuery(span_run).removeClass('right-fix-2one').css('color','#42616c');
    					if (scrolled > 15){
    						jQuery(span_run).addClass('right-fix');
    					}
    					else {
    						jQuery(span_run).removeClass('right-fix');
    					}
    				}
    			}
    		});
    	});	
</script>
<!-- in css: -->
<style>
	#up-btn {
      position: fixed;
      bottom: 20px;
      right: 20px;
  	  z-index: 15;
	  cursor: pointer;
      transition: all .3s;
  	}
 	img[src$=".svg"]{
		width:48px
    }
</style>

<!-- in html: -->
<div class="btn-hide" data-id="" data-element_type="widget" id="up-btn" data-settings="" alt="scroll to top">
	<img width="40" height="55" src="https://aspx.co.il/wp-content/uploads/2023/04/arrowup.svg" class="" alt="arrowup" /> 
</div>

<!-- in js: -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js" crossorigin="anonymous"></script>
<script type="text/javascript" async>
	jQuery(document).ready(function($){
  
	//Check to see if the window is top if more then 500px from top display button
	$(window).scroll(function(){
		if ($(this).scrollTop() > 500) {
			$('#up-btn').fadeIn(300,'linear').removeClass('btn-hide');
		} else {
			$('#up-btn').fadeOut(200).hide('slow').addClass('btn-hide');
		}
	});

	//Click event to scroll to top
	$('#up-btn').click(function(){
		$('html, body').animate({scrollTop : 0},800);
		$(this).addClass('btn-hide');
			return false;
	});
</script>

const functions = require('@google-cloud/functions-framework');

functions.http('helloHttp', (req, res) => {
 res.send(`Hello ${req.query.name || req.body.name || 'World'}!`);
});
let rawPrize = prompt("Enter your first name");

​
let b = 0;      // b contains 0

b += 1;         // b contains 1

b++;            // b contains 2

console.log(b); // Shows 2

​
const nb = Number(prompt("Enter a number:")); // nb's type is number
console.log("Hello from JavaScript!");

console.log("Let's do some math");

console.log( + 7);
4
console.log(12 / 0);

console.log("Goodbye!");

​
console.log("Hello from JavaScript!");

console.log("Let's do some math");

console.log( + 7);
4
console.log(12 / 0);

console.log("Goodbye!");

​
console.log("Hello from JavaScript!");

console.log("Let's do some math");

console.log( + 7);
4
console.log(12 / 0);

console.log("Goodbye!");

​
Now you need to actually sort the array. The first sorting algorithm you will implement is the bubble sort, which starts at the beginning of the array and 'bubbles up' unsorted values towards the end, iterating through the array until it is completely sorted.

const bubbleSort = (array) => {
  for (let i = 0; i < array.length; i++) {
    for (let j = 0; j < array.length - 1; j++) {
      console.log(array, array[j], array[j + 1]);

      if (array[j] > array[j + 1]) {
        const temp = array[j];
        array[j] = array[j + 1];
        array[j + 1] = temp;
      }
    }
  }

  return array;
}
  
  Time to implement another sorting algorithm. This time, you'll be implementing a selection sort. Selection sort works by finding the smallest value in the array, then swapping it with the first value in the array. Then, it finds the next smallest value in the array, and swaps it with the second value in the array. It continues iterating through the array until it is completely sorted.
  
const selectionSort = (array) => {
  for (let i = 0; i < array.length; i++) {
    let minIndex = i;

    for (let j = i + 1; j < array.length; j++) {
      console.log(array, array[j], array[minIndex]);
      if (array[j] < array[minIndex]) {
        minIndex = j;
      }
    }

    const temp = array[i];
    array[i] = array[minIndex];
    array[minIndex] = temp;
  }

  return array;
}

The last sorting algorithm you will implement is the insertion sort. This algorithm works by building up a sorted array at the beginning of the list. It begins the sorted array with the first element. Then it inspects the next element and swaps it backward into the sorted array until it is in a sorted position, and so on.

const insertionSort = (array) => {
  for (let i = 1; i < array.length; i++) {
    const currValue = array[i];
    let j = i - 1;

    while (j >= 0 && array[j] > currValue) {
      array[j + 1] = array[j];
      j--;
    }
    array[j + 1] = currValue;
  }
  return array;
}

To sort the elements of an array, you can use the built-in method called .sort(). 

Notice how the double digit number(10) is placed at the beginning of the array. This is because the default behavior of .sort() is to convert the numbers values to strings, and sort them alphabetically. And 10 comes before 2 alphabetically.

To fix this, you can pass a callback function to the .sort() method. The callback function has two parameters - for yours, use a and b. The parameters of a and b represent the number values in the array that will be sorted.

const sortedValues = inputValues.sort((a, b) => {
    return a - b;
  });
Regular expressions, often shortened to "regex" or "regexp", are patterns that help programmers match, search, and replace text. Regular expressions are powerful, but can be difficult to understand because they use so many special characters.

Your first regular expression will be used to catch help requests. Declare a helpRegex variable, and assign it a regular expression that matches the string please help.

As a refresher, here is a regular expression to match the string hello world:

Example Code
const regex = /hello world/;

Regular expressions can take flags to modify their behavior. For instance, the i flag can be used to make the expression ignore case, causing it to match hello, HELLO, and Hello for the expression /hello/.

Flags are added after the trailing slash. 

Strings have a .match() method, which accepts a regular expression as an argument and determines if the string matches that expression.

Instead of using the .match() method, you can use the .test() method of a regular expression to test if a string matches the pattern. Unlike .match(), .test() returns a boolean value indicating whether or not the string matches the pattern.

The alternate sequence | can be used to match either the text on the left or the text on the right of the |. For example, the regular expression /yes|no/ will match either yes or no.

A character class is defined by square brackets, and matches any character within the brackets. For example, [aeiou] matches any character in the list aeiou. You can also define a range of characters to match using a hyphen. For example, [a-z] matches any character from a to z.

The value may be more than one digit. To match this, the + quantifier can be used - this matches one or more consecutive occurrences. For example, the regular expression /a+/ matches one or more consecutive a characters.

A capture group is a way to define a part of the expression that should be captured and saved for later reference. You can define a capture group by wrapping a part of your expression in parentheses. For example, /h(i|ey) camper/ would match either hi camper or hey camper, and would capture i or ey in a group.

Now that you have your capture group, you can mark the entire pattern as an optional match. The ? quantifier matches zero or one occurrence of the preceding character or group. For example, the regular expression /colou?r/ matches both color and colour, because the u is optional.

One last thing with this expression. You don't actually need the match value from your capture group, so you can turn it into a non-capturing group. This will allow you to group the characters together without preserving the result.

To create a non-capturing group in a regular expression, you can add ?: after the opening parenthesis of a group. For instance, (?:a|b) will match either a or b, but it will not capture the result.

Your regex should match whole words, not partial words. That is, you do not want to match hands-free money management.

To do this, start by checking for spaces before and after your pattern. You can do this by using the meta character \s, which will match spaces, tabs, and line breaks.

Like the ^ anchor, you can use the $ anchor to match the end of the string.
<script>
    document.addEventListener("scroll", function() {


    if (document.body.scrollTop > 300 || document.documentElement.scrollTop > 300) {
        document.querySelector('.footer-button').classList.remove('d-none')
    } else {

        document.querySelector('.footer-button').classList.add('d-none')

    }
})

</script>
In an earlier project you learned about truthy and falsy values, which are values that evaluate to true or false. In JavaScript, some common falsy values you'll see are null, undefined, the number 0, and empty strings.

Rather than check if a value is equal to a falsy value, you can use the logical NOT operator (!) to check if the value itself is falsy. For example:

const num = 0;

console.log(num === 0); // true
console.log(!num); // true

A good way to check and normalize numbers in JavaScript is to use the built-in parseInt() function, which converts a string into an integer or whole number. parseInt() takes at least one argument, a string to be converted into an integer, and returns either an integer or NaN which stands for Not a Number. For example:

parseInt(2.2); // 2
parseInt("2e+3"); // 2
parseInt("e") // NaN

Next, you need to check if the value returned by the parseInt() function is a number or not.

To do that, you can use the isNaN() function. This function takes in a string or number as an argument, and returns true if it evaluates to NaN. For example:

isNaN("test"); // true
isNaN(2); // false
isNaN("3.5"); // false

The setTimeout function takes two arguments: a callback function and a number representing the time in milliseconds to wait before executing the callback function.

For example, if you wanted to log "Hello, world!" to the console after 3 seconds, you would write:

setTimeout(() => {
  console.log("Hello, world!");
}, 3000);

If you test your code, you'll notice that your console logs are not in the expected order. Instead of logging "free", pausing for a second before logging "Code", and finally logging "Camp", you'll see this:

Example Code
free
Camp
Code
This is because the setTimeout() function is asynchronous, meaning that it doesn't stop the execution of the rest of your code. All the code in the showAnimation() function runs line by line, but because setTimeout() is asynchronous, free and Camp are logged to the console immediately, and then Code is logged to the console after a one second delay.

While asynchronous, or async, code can be difficult to understand at first, it has many advantages. One of the most important is that it allows you to write non-blocking code.

For example, imagine you're baking a cake, and you put the cake in the oven and set a timer. You don't have to sit in front of the oven waiting the entire time – you can wash dishes, read a book, or do anything else while you wait for the timer to go off.

Async code works in a similar way. You can start an async operation and other parts of your code will still work while that operation is running.
 LocalStorage is a web storage feature of JavaScript that lets you persist data by storing the data as a key:value pair.
 
In earlier projects, you learned how to add and remove classes from an element with el.classList.add() and el.classList.remove(). Another method to use with the classList property is the toggle method.

The toggle method will add the class if it is not present on the element, and remove the class if it is present on the element.

element.classList.toggle("class-to-toggle");

The HTML dialog element has a showModal() method that can be used to display a modal dialog box on a web page.

dialogElement.showModal();

The HTML dialog element has a close() method that can be used to close a modal dialog box on a web page.

dialogElement.close();

The findIndex() array method finds and returns the index of the first element in an array that meets the criteria specified by a provided testing function. If no such element is found, the method returns -1.

Here's an example:

const numbers = [3, 1, 5, 6];
const firstNumLargerThanThree = numbers.findIndex((num) => num > 3);

console.log(firstNumLargerThanThree); // prints index 2

To make the id more unique, add another hyphen and use Date.now().

Date.now() returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.

console.log(Date.now()); // 1628586800000

Instead of clearing the input fields one by one, it's a good practice to create a function that handles clearing those fields. You can then call this function whenever you need to clear the input fields again.

splice() is an array method that modifies arrays by removing, replacing, or adding elements at a specified index, while also returning the removed elements. It can take up to three arguments: the first one is the mandatory index at which to start, the second is the number of items to remove, and the third is an optional replacement element. Here's an example:

const fruits = ["mango", "date", "cherry", "banana", "apple"];

// Remove date and cherry from the array starting at index 1
const removedFruits = fruits.splice(1, 2);

console.log(fruits); // [ 'mango', 'banana', 'apple' ]
console.log(removedFruits); // [ 'date', 'cherry' ]

localStorage offers methods for saving, retrieving, and deleting items. The items you save can be of any JavaScript data type.

For instance, the setItem() method is used to save an item, and the getItem() method retrieves the item. To delete a specific item, you can utilize the removeItem() method, or if you want to delete all items in the storage, you can use clear().

Here's how you can save an item:

localStorage.setItem("key", value); // value could be string, number, or any other data type

If you check the "Application" tab of your browser console, you'll notice a series of [object Object]. This is because everything you save in localStorage needs to be in string format.

To resolve the issue, wrap the data you're saving in the JSON.stringify() method. 

The syntax for reading the localStorage item is as follows:

const cat = localStorage.getItem("myCat");

The syntax for removing the localStorage item is as follows:

localStorage.removeItem("myCat");

The syntax for removing all the localStorage items is as follows:

localStorage.clear();
We are going to use a method called Object.freeze(obj) which will freeze this object and prevent any changes being made to it.

In the last two steps, you have been accessing properties from the myFavoriteFootballTeam object using dot notation and assigning them to new const variables. But in JavaScript, there is an easier way to accomplish the same goal.

The object destructuring syntax allows you to unpack values from arrays and objects:

const developerObj = {
  name: "Jessica Wilkins",
  isDeveloper: true
};

// Object destructuring
const { name, isDeveloper } = developerObj;

Function parameters can be initialized with default values. If a function is called without an argument, then the default value will be used:

const greeting = (name = "Anonymous") => {
  return "Hello " + name;
} 

console.log(greeting("John")); // Hello John
console.log(greeting()); // Hello Anonymous
const Width = ({ children }) => children(500);
In JavaScript, there are many built-in constructors that create objects. A constructor is like a regular function, but starts with a capital letter, and is initialized with the new operator.

For example, you can use the Date() constructor with the new operator to create a new Date object that returns a string with the current date and time:

const currentDate = new Date();
console.log(currentDate);

// Output:
// Mon Aug 23 2021 15:31:00 GMT-0400 (Eastern Daylight Time)

The Date object has a number of methods that allow you to get the date and time in different formats.

One of those is the .getDate() method, which returns a number between 1 and 31 that represents the day of the month for that date. For example:

const date = new Date();
const dayOfTheMonth = date.getDate();
console.log(dayOfTheMonth); // 20

The .getMonth() method returns a number between 0 and 11. This represents the month for the date provided, where 0 is January and 11 is December. Because the number this method returns is zero-based, you need to add 1 to it to get the expected month number.

The .getFullYear() method returns a number which represents the year for the provided date.

The .getHours() method returns a number between 0 and 23. This represents the hour for the provided date, where 0 is midnight and 23 is 11 p.m.

The .getMinutes() method returns a number between 0 and 59 which represents the minutes for the provided date.

n JavaScript, the change event is used to detect when the value of an HTML element has changed:

element.addEventListener("change", () => {
    
});

A switch statement is used to compare an expression against multiple possible values and execute different code blocks based on the match. It's commonly used for branching logic.

For example, here's how to compare the expression dayOfWeek against possible values:

switch (dayOfWeek) {
  case 1:
    console.log("It's Monday!");
    break;
  case 2:
    console.log("It's Tuesday!");
    break;
  // ...cases for other workdays
  default:
    console.log("It's the weekend!");
}
    
You can add a case clause in the switch statement that checks for a match against the expression expr, followed by code to run if there's a match. Here's an example where the case clause checks that expr is equal to the string "case123":

switch (expr) {
  case 'case123':
    // Write your logic here
}
    
If your switch statement is going to have multiple cases, it is best practice to include a break statement.

The break statement will tell the JavaScript interpreter to stop executing statements. Without adding a break statement at the end of each case block, the program will execute the code for all matching cases:

switch (someVariable) {
  case 'case123':
    // Write your logic here
    break; // Terminates the switch statement
}
    
In a switch statement, the default case is executed when none of the previous case conditions match the value being evaluated. It serves as a catch-all for any other possible cases. For example:

const dayOfWeek = 7;

switch (dayOfWeek) {
  case 1:
    console.log("It's Monday!");
    break;
  case 2:
    console.log("It's Tuesday!");
    break;
  // ...cases for other workdays
  default:
    console.log("It's the weekend!");
}
    
The split() method is used to divide a string into substrings based on a specified separator. It then returns these substrings as elements of an array.

Here is an example of taking the words "Hello World" and returning an array of one element:

const greeting = "Hello World";
greeting.split(); // ["Hello World"]
    
The split method takes in a parameter known as a separator. The separator is used to tell the computer where each split should occur.

Here is an example of using an empty string as a separator:

// returns ["h", "e", "l", "l", "o"]
"hello".split(""); 
Other examples of separators can include a space " ", or a hyphen "-". If you don't provide a separator, the method will return an array with the original string as the only element.
    
To reverse an array of elements, you can use the reverse method. This method reverses the order of the elements in the array in place. The first element becomes the last, and the last element becomes the first.

Here is an example of using the reverse method:

// returns [5, 4, 3, 2, 1]
[1, 2, 3, 4, 5].reverse(); 
    
The join method takes an array of elements and joins them into a string. Similar to the split method, the join method also takes an optional separator. If you don't provide a separator, the default separator is a comma.

Here is an example of using the join method:

// returns "1-2-3-4-5"
[1, 2, 3, 4, 5].join("-");
    
The spread operator (...) allows you to copy all elements from one array into another. It can also be used to concatenate multiple arrays into one. In the example below, both arr1 and arr2 have been spread into combinedArr:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const combinedArr = [...arr1, ...arr2];
console.log(combinedArr); // Output: [1, 2, 3, 4, 5, 6]

An arrow function is an anonymous function expression and a shorter way to write functions. Anonymous means that the function does not have a name. Arrow functions are always anonymous.

Here is the basic syntax:

() => {}
To create a named arrow function, you can assign the function to a variable:

const exampleFunction = () => {
  // code goes here
}

To call a named arrow function expression, you can reference the function by its name.

exampleArrowFunction();

Just like regular functions, arrow functions can accept multiple parameters.

Here is an example of a named arrow function with one parameter:

const greet = (name) => {
  console.log(`Hello, ${name}!`);
};
If the function only has one parameter, you can omit the parentheses around the parameter list like this:

const greet = name => {
  console.log(`Hello, ${name}!`);
};

Just like regular functions, arrow functions can return values.

Here is an example of an arrow function returning the result of multiplying two numbers:

const multiplyTwoNumbers = (num1, num2) => {
  return num1 * num2;
}

// Output: 12
console.log(multiplyTwoNumbers(3, 4)); 

If the arrow function is returning a simple expression, you can omit the return keyword and the curly braces {}. This is called an implicit return.

const multiplyTwoNumbers = (num1, num2) => num1 * num2;
If your arrow function has multiple lines of code in the function body, then you need to use the return keyword and the curly braces {}.

const getTax = (price) => {
  const taxRate = 0.08;
  const tax = price * taxRate;
  return tax;
};

The map() method is used to iterate through an array and return a new array. It's helpful when you want to create a new array based on the values of an existing array. For example:

const numbers = [1, 2, 3];
const doubledNumbers = numbers.map((number) => number * 2); // doubledNumbers will be [2, 4, 6]
Notice that the map() method takes a function as an argument. This is called a callback function, which is a function that is passed to another function as an argument. In the example above, the callback function is (number) => number * 2, and it's run on each element in the numbers array. The map() method then returns a new array with the results.

Right now the songsHTML is an array. If you tried to display this as is, you would see the songs separated by commas. This is not the desired outcome because you want to display the songs as a list. To fix this, you will need to join the array into a single string by using the join() method.

The join() method is used to concatenate all the elements of an array into a single string. It takes an optional parameter called a separator which is used to separate each element of the array. For example:

const exampleArr = ["This", "is", "a", "sentence"];
const sentence = exampleArr.join(" "); // Separator takes a space character
console.log(sentence); // Output: "This is a sentence"

Optional chaining (?.) helps prevent errors when accessing nested properties that might be null or undefined. For example:

const user = {
  name: "Quincy",
  address: {
    city: "San Francisco",
    state: "CA",
    country: "USA",
  },
};

// Accessing nested properties without optional chaining
const state = user.address.state; // CA

// Accessing a non-existent nested property with optional chaining
const zipCode = user.address?.zipCode; // Returns undefined instead of throwing an error

The sort() method converts elements of an array into strings and sorts them in place based on their values in the UTF-16 encoding.

const names = ["Tom", "Jessica", "Quincy", "Naomi"];
names.sort() // ["Jessica", "Naomi", "Quincy", "Tom"]

To sort the songs in alphabetical order by title, you will need to pass in a compare callback function into your sort() method.

Here is an example of sorting a list of fruits by name.

const fruits = [
  { name: "Apples", price: 0.99 },
  { name: "Blueberries", price: 1.49 },
  { name: "Grapes", price: 2.99 },
];

fruits.sort((a, b) => {
  if (a.name < b.name) {
    return -1;
  }

  if (a.name > b.name) {
    return 1;
  }

  return 0;
});

The sort() method accepts a compare callback function that defines the sort order.

In this example, the first condition (a.name < b.name) checks if the name of the first fruit is less than the name of the second fruit. If so, the first fruit is sorted before the second fruit.

Strings are compared lexicographically which means they are compared character by character. For example, "Apples" is less than "Bananas" because "A" comes before "B" in the alphabet.

The reason why this example is returning numbers is because the sort() method is expecting a number to be returned. If you return a negative number, the first item is sorted before the second item.

const fruits = [
  { name: "Apples", price: 0.99 },
  { name: "Blueberries", price: 1.49 },
  { name: "Grapes", price: 2.99 },
];

fruits.sort((a, b) => {
  if (a.name < b.name) {
    return -1;
  }

  if (a.name > b.name) {
    return 1;
  }

  return 0;
});

The find() method retrieves the first element within an array that fulfills the conditions specified in the provided callback function. If no element satisfies the condition, the method returns undefined.

In the example below, the find() method is used to find the first number greater than 25:

const numbers = [10, 20, 30, 40, 50];

// Find the first number greater than 25
const foundNumber = numbers.find((number) => number > 25);
console.log(foundNumber); // Output: 30

To get the index for the current song, you can use the indexOf() method. The indexOf() array method returns the first index at which a given element can be found in the array, or -1 if the element is not present.

const animals = ["dog", "cat", "horse"];
animals.indexOf("cat") // 1

The forEach method is used to loop through an array and perform a function on each element of the array. For example, suppose you have an array of numbers and you want to log each number to the console.

const numbers = [1, 2, 3, 4, 5];

// Using forEach to iterate through the array
numbers.forEach((number) => {
  console.log(number); // 1, 2, 3, 4, 5
});

textContent sets the text of a node and allows you to set or retrieve the text content of an HTML element.

<div id="example">This is some text content</div>
Example Code
const element = document.getElementById('example');
console.log(element.textContent); // Output: This is some text content

In earlier steps, you learned how to work with the sort() method to sort the songs in alphabetical order. Another use case for the callback function is to randomize an array.

One way to randomize an array of items would be to subtract 0.5 from Math.random() which produces random values that are either positive or negative. This makes the comparison result a mix of positive and negative values, leading to a random ordering of elements.

const names = ["Tom", "Jessica", "Quincy", "Naomi"];
names.sort(() => Math.random() - 0.5);

createElement() is a DOM method you can use to dynamically create an element using JavaScript. To use createElement(), you call it, then pass in the tag name as a string:

// syntax
document.createElement(tagName)

// example
document.createElement('div')

You can also assign it to a variable:

const divElement = document.createElement('div')

Now that you've created the button, you need to assign it a text. To do this, you need to use the createTextNode() method of DOM.

The createTextNode() method is used to create a text node. To use it, you call it and pass in the text as a string:

document.createTextNode("your text")

You can also assign it to a variable:

const myText = document.createTextNode("your text")

Now that you've created the resetButton, you need to assign it an id and aria-label attributes. JavaScript provides the id and ariaLabel properties you need to use for this.

For example, element.id would set an id attribute, and element.ariaLabel would set an aria-label attribute. Both of them accept their values as a string.

appendChild() lets you add a node or an element as the child of another element. In the example below, the text "Click me" would be attached to the button:

const parentElement = document.createElement("button")
const parentElementText = document.createTextNode("Click me")

// attach the text "Click me" to the button
parentElement.appendChild(parentElementText)

The Alphacodez Cryptocurrency Exchange Script is a robust solution for launching secure and efficient trading platforms, featuring user management, a high-performance trading engine, and wallet integration. It offers advanced security measures and customization options. Ongoing support and maintenance ensure smooth operation.
To access an HTML element with a given id name, you can use the getElementById() method. Here's an example of how to use this method:

<h1 id="title">Main title</h1>
Example Code
const mainTitleElement = document.getElementById('title');

In programming, prefixing a variable with is or has is a common practice to signify that the variable represents a boolean value.

Here are a few examples:

let isRunning = true;
let hasCompleted = false;

Values from an HTML input field are received as strings in JavaScript. You'll need to convert these strings into numbers before performing any calculations.

To match specific characters in a string, you can use Regular Expressions or "regex" for short.

Regex in JavaScript is indicated by a pattern wrapped in forward slashes. The following example will match the string literal "hello":

const regex = /hello/;

In regex, shorthand character classes allow you to match specific characters without having to write those characters in your pattern. Shorthand character classes are preceded with a backslash (\). The character class \s will match any whitespace character.

JavaScript provides a .replace() method that enables you to replace characters in a string with another string. This method accepts two arguments. The first argument is the character sequence to be replaced, which can be either a string or a regex pattern. The second argument is the string that replaces the matched sequence.

Since strings are immutable, the replace method returns a new string with the replaced characters.

In this example, the replace method is used to replace all instances of the letter l with the number 1 in the string hello.

"hello".replace(/l/g, "1");

Strings have a .match() method, which takes a regex argument. .match() will return an array of match results – containing either the first match, or all matches if the global flag is used.

const str = 'example string';
const regex = /example/;
const result = str.match(regex); // Returns ['example']

The match method returns an array with any matches found in the string.

Here is a complete breakdown of that information:

"1e3" is the matched value against the /\d+e\d+/i regex.
index: 0 is the index of the matched value in the string.
input: '1e3' is the original string that was matched.
groups: undefined are the matched groups, which are not used in this case. You will learn more about groups in a later project.

The match method returns null when no match is found. In this case, the isInvalidInput function should return null when the input is a valid number without any scientific notation.

null in JavaScript is a special primitive that represents the intentional absence of a value. In a boolean context, null is considered falsy which evaluates to false in a conditional statement.

JavaScript has a feature called template literals, which allow you to interpolate variables directly within a string. Template literals are denoted with backticks ``, as opposed to single or double quotes. Variables can be passed in to a template literal by surrounding the variable with ${} – the value of the variable will be inserted into the string.

For example:

const name = "Naomi";
const templateLiteral = `Hello, my name is ${name}~!`;
console.log(templateLiteral);
The console will show the string "Hello, my name is Naomi~!".

The querySelectorAll() method returns a NodeList of all the elements that match the selector. A NodeList is an array-like object, so you can access the elements using bracket notation.

The innerHTML property sets or returns the HTML content inside an element.

Here is a form element with a label and input element nested inside.

<form id="form">
  <label for="first-name">First name</label>
  <input id="first-name" type="text">
</form>
If you want to add another label and input element inside the form, then you can use the innerHTML property as shown below:

const formElement = document.getElementById("form");
const formContent = `
  <label for="last-name">Last name</label>
  <input id="last-name" type="text">
`;
formElement.innerHTML += formContent;

The following example uses the addEventListener method to add a click event to a button. When the button is clicked, the printName function is called.

<button class="btn">Print name</button>
Example Code
const button = document.querySelector('.btn');
function printName() {
  console.log("Jessica");
}
button.addEventListener('click', printName);
The addEventListener method takes two arguments. The first is the event to listen to. (Ex. 'click') The second is the callback function, or the function that runs when the event is triggered.

The insertAdjacentHtml method takes two arguments. The first argument is a string that specifies the position of the inserted element. The second argument is a string containing the HTML to be inserted.

The submit event is triggered when the form is submitted. The default action of the submit event is to reload the page. You need to prevent this default action using the preventDefault() method of your e parameter.

Math.abs() is a built-in JavaScript method that will return the absolute value of a number.

const num = -5;
Math.abs(num); // 5

Finally, you need to make the #output element visible so the user can see your text. Your output variable is an Element, which has a classList property. This property has a .remove() method, which accepts a string representing the class to remove from the element.

Example Code
const paragraphElement = document.getElementById('paragraph');
paragraphElement.classList.remove('hide');

Remember that document.querySelectorAll returns a NodeList, which is array-like but is not an array. However, the Array object has a .from() method that accepts an array-like and returns an array. This is helpful when you want access to more robust array methods, which you will learn about in a future project.

The following example takes a NodeList of li elements and converts it to an array of li elements:

<ul>
  <li>List 1</li>
  <li>List 2</li>
  <li>List 3</li>
</ul>
Example Code
const listItemsArray = Array.from(document.querySelectorAll('li'));

console.log(listItemsArray); //Output: (3) [li, li, li]

The difference between innerText and innerHTML is that innerText will not render HTML elements, but will display the tags and content as raw text.
Now you can start writing your JavaScript. Begin by creating a script element. This element is used to load JavaScript into your HTML file.

<script>
  // JavaScript code goes here
</script>

One of the most powerful tools is your developer console. Depending on your browser, this might be opened by pressing F12 or Ctrl+Shift+I. On Mac, you can press Option + ⌘ + C and select "Console". You can also click the "Console" button above the preview window to see our built-in console.

The developer console will include errors that are produced by your code, but you can also use it to see values of variables in your code, which is helpful for debugging.

JavaScript interacts with the HTML using the Document Object Model, or DOM. The DOM is a tree of objects that represents the HTML. You can access the HTML using the document object, which represents your entire HTML document.

One method for finding specific elements in your HTML is using the querySelector() method. The querySelector() method takes a CSS selector as an argument and returns the first element that matches that selector. For example, to find the <h1> element in your HTML, you would write:

let h1 = document.querySelector("h1");
Note that h1 is a string and matches the CSS selector you would use.

We have run into a slight problem. You are trying to query your page for a button element, but your script tag is in the head of your HTML. This means your code runs before the browser has finished reading the HTML, and your document.querySelector() will not see the button - because the browser hasn't processed it yet.

To fix this, move your script element out of the head element, and place it at the end of your body element (just before the closing <body> tag.)

button1 represents your first button element. These elements have a special property called onclick, which you can use to determine what happens when someone clicks that button.

You can access properties in JavaScript a couple of different ways. The first is with dot notation. Here is an example of using dot notation to set the onclick property of a button to a function reference.

button.onclick = myFunction;
In this example, button is the button element, and myFunction is a reference to a function. When the button is clicked, myFunction will be called.

The innerText property controls the text that appears in an HTML element. For example:

<p id="info">Demo content</p> 
Example Code
const info = document.querySelector("#info"); 
info.innerText = "Hello World"; 
The following example would change the text of the p element from Demo content to Hello World.

Objects are an important data type in JavaScript. The next few steps will be dedicated to learning about them so you will better understand how to apply them in your project.

Objects are non primitive data types that store key-value pairs. Non primitive data types are mutable data types that are not undefined, null, boolean, number, string, or symbol. Mutable means that the data can be changed after it is created.

Here is the basic syntax for an object:

{
  key: value
}

Objects are similar to arrays, except that instead of using indexes to access and modify their data, you access the data in objects through properties.

Properties consist of a key and a value. The key is the name of the property, and the value is the data stored in the property.

Here is an example of an object with a single property:

const obj = {
  name: "Quincy Larson"
};

If the property name (key) of an object has a space in it, you will need to use single or double quotes around the name.

Here is an example of an object with a property name that has a space:

const spaceObj = {
  "Space Name": "Kirk",
};
If you tried to write a key without the quotes, it would throw an error:

const spaceObj = {
  // Throws an error
  Space Name: "Kirk",
}; 

There are two ways to access the properties of an object: dot notation (.) and bracket notation ([]), similar to an array.

Dot notation is what you use when you know the name of the property you're trying to access ahead of time.

object.property;
Here is a sample of using dot notation (.) to read the name property of the developer object:

const developer = {
  name: "Jessica",
}

// Output: Jessica
console.log(developer.name); 

The second way to access the properties of an object is bracket notation ([]). If the property of the object you are trying to access has a space in its name, you will need to use bracket notation.

objectName["property name"];
Here is a sample of using bracket notation to read an object's property:

const spaceObj = {
  "Space Name": "Kirk",
};

spaceObj["Space Name"]; // "Kirk"

By default, the HTML element that shows the monster's stats has been hidden with CSS. When the player clicks the "Fight dragon" button, the monster's stats should be displayed. You can accomplish this by using the style and display properties on the monsterStats element.

The style property is used to access the inline style of an element and the display property is used to set the visibility of an element.

Here is an example of how to update the display for a paragraph element:

const paragraph = document.querySelector('p');
paragraph.style.display = 'block';

The Math object in JavaScript contains static properties and methods for mathematical constants and functions. One of those is Math.random(), which generates a random number from 0 (inclusive) to 1 (exclusive). Another is Math.floor(), which rounds a given number down to the nearest integer.

Using these, you can generate a random number within a range. For example, this generates a random number between 1 and 5: Math.floor(Math.random() * 5) + 1;.

The innerHTML property allows you to access or modify the content inside an HTML element using JavaScript.

Here is an example of updating the content for this paragraph element using the innerHTML property.

<p id="demo">This is a paragraph.</p>
document.querySelector("#demo").innerHTML = "Hello, innerHTML!";

The ternary operator is a conditional operator and can be used as a one-line if-else statement. The syntax is: condition ? expressionIfTrue : expressionIfFalse.

Here is an example of returning a value using an if-else statement and a refactored example using a ternary operator:

// if-else statement
if (score > 0) {
  return score
} else {
  return default_score
}

// ternary operator
return score > 0 ? score : default_score

The logical OR operator will use the first value if it is truthy – that is, anything apart from NaN, null, undefined, 0, -0, 0n, "", and false. Otherwise, it will use the second value.

For example: num < 10 || num > 20.

The .includes() method determines if an array contains an element and will return either true or false.

Here is an example of the .includes() syntax:

Example Code
const numbersArray = [1, 2, 3, 4, 5]
const number = 3

if (numbersArray.includes(number)) {
  console.log("The number is in the array.")
}
In programming, you will often need to work with lots of data. There are many data structures that can help you organize and manage your data. One of the most basic data structures is an array.

An array is a non-primitive data type that can hold a series of values. Non-primitive data types differ from primitive data types in that they can hold more complex data. Primitive data types like strings and numbers can only hold one value at a time.

Arrays are denoted using square brackets ([]). Here is an example of a variable with the value of an empty array:

let array = [];

When an array holds values, or elements, those values are separated by commas. Here is an array that holds two strings:

Example Code
let array = ["first", "second"];

You can access the values inside an array using the index of the value. An index is a number representing the position of the value in the array, starting from 0 for the first value.

You can access the value using bracket notation, such as array[0].

Arrays are special in that they are considered mutable. This means you can change the value at an index directly.

For example, this code would assign the number 25 to the second element in the array:

let array = [1, 2, 3];
array[1] = 25;
console.log(array); // prints [1, 25, 3]

You can make use of the .length property of an array - this returns the number of elements in the array. To get the last element of any array, you can use the following syntax:

array[array.length - 1]

array.length returns the number of elements in the array. By subtracting 1, you get the index of the last element in the array. 

A method in JavaScript is a function that's associated with certain values or objects. An example you've already encountered is the .log() method, which is part of the console object.

Arrays have their own methods, and the first you will explore is the .push() method. This allows you to "push" a value to the end of an array. Here is an example to add the number 12 to the end of an array:

array.push(12);

Another method essential for this project is the .pop() method. It removes the last element from an array and returns that element.

When a method returns a value, you can think of it as giving the value back to you, making it available for use in other parts of your code.

.push() returns the new length of the array, after adding the value you give it.

When you have to perform a task repeatedly until a condition is met, you will use a loop. There are many ways to write a loop.

You are going to start with a basic for loop. for loops use the following syntax:

for (iterator; condition; iteration) {
  logic;
}

The iterator is a variable you can declare specifically in your for loop to control how the loop iterates or goes through your logic.

It is a common convention to use i as your iterator variable in a loop. A for loop allows you to declare this in the parentheses (). For example, here is a for loop that declares an index variable and assigns it the value 100.

for (let index = 100; "second"; "third") {

}

The condition of a for loop tells the loop how many times it should iterate. When the condition becomes false, the loop will stop.

In JavaScript, a Boolean value can be either true or false. These are not strings - you will learn more about the difference later on.

Your iteration statement will tell your loop what to do with the iterator after each run.

When you reassign a variable, you can use the variable to reference the previous value before the reassignment. This allows you to do things like add three to an existing number. For example, bees = bees + 3; would increase the value of bees by three.

A for...of loop, which iterates over each item in an iterable object and temporarily assigns it to a variable.

The syntax for a for...of loop looks like:

for (const value of iterable) {

}

You will need to add a new line to each row. However, pressing the return key to insert a line break between quotes in JavaScript will result in a parsing error. Instead, you need to use the special escape sequence \n, which is interpreted as a new line when the string is logged. For example:

lineOne = lineOne + "\n" + lineTwo;

To achieve this, you will use the .repeat() method available to strings. This method accepts a number as an argument, specifying the number of times to repeat the target string. For example, using .repeat() to generate the string "Code! Code! Code!":

const activity = "Code! ";
activity.repeat(3);

A function is a block of code that can be reused throughout your application. Functions are declared with the following syntax:

function name(parameter) {

}

The function keyword tells JavaScript that the name variable is going to be a function. parameter is a variable that represents a value that is passed into the function when it is used. A function may have as many, or as few, parameters as you'd like.

In order to use a function, you need to call it. A function call tells your application to run the code from the function wherever you choose to call it. The syntax for a function call is the function name followed by parentheses. For example, this code defines and calls a test function.

function test() {

}
test();

All functions in JavaScript return a value, meaning they provide the defined result of calling them for you to use elsewhere.

By default, functions return undefined as their value.

In order to return something else, you need to use the return keyword. Here is an example of a function that returns the string "Functions are cool!":

Example Code
function demo() {
  return "Functions are cool!";
}

Hard-coding a value inside a function might not make it as reusable as you'd like.

Instead, you can define parameters for the function. Parameters are special variables that are given a value when you call the function, and can be used in your function to dynamically change the result of the function's code.

To add a parameter to your function, you need to add a variable name inside the parentheses. For example, this demo function has a name parameter:

function demo(name) {

}

A function does not have to return a hard-coded value. It can return the value stored in a variable. Parameters are special variables for a function, so they can also be returned.

When you pass a value to a function call, that value is referred to as an argument. Here is an example of calling a demo function and passing "Naomi" as the argument for the name parameter.

function demo(name) {
  return name;
}
demo("Naomi");

Variables in JavaScript are available in a specific scope. In other words, where a variable is declared determines where in your code it can be used.

The first scope is the global scope. Variables that are declared outside of any "block" like a function or for loop are in the global scope.

When a variable is in the global scope, a function can access it in its definition. Here is an example of a function using a global title variable:

const title = "Professor ";
function demo(name) {
  return title + name;
}
demo("Naomi")
This example would return "Professor Naomi".

Variables can also be declared inside a function. These variables are considered to be in the local scope, or block scope. A variable declared inside a function can only be used inside that function. If you try to access it outside of the function, you get a reference error.

Values returned out of a function are used by calling the function. You can use the function call directly as the value it returns, or capture the returned value in a variable. This way, you can use the value assigned to a locally scoped variable, outside the function it was created in.

function getName() {
  const name = "Camper cat";
  return name;
}

console.log(getName()); // "Camper cat"

const capturedReturnValue = getName();
console.log(capturedReturnValue); // "Camper cat"

console.log(name); // reference error

The values you provide to a function call are referred to as arguments, and you pass arguments to a function call. Here's a function call with "Hello" passed as an argument:

test("Hello");

You can pass full expressions as an argument. The function will receive the result of evaluating that expression. For example, these two function calls would yield the same result:

test(2 * 3 + 1);
test(7);

An if statement allows you to run a block of code only when a condition is met. They use the following syntax:

if (condition) {
  logic
}

A truthy value is a value that is considered true when evaluated as a boolean. Most of the values you encounter in JavaScript will be truthy.

A falsy value is the opposite - a value considered false when evaluated as a boolean. JavaScript has a defined list of falsy values. Some of them include false, 0, "", null, undefined, and NaN.

In addition to if statements, JavaScript also has else if statements. else if statements allow you to check multiple conditions in a single block of code.

Here is the syntax for an else if statement:

if (condition1) {
  // code to run if condition1 is true
} else if (condition2) {
  // code to run if condition2 is true
} else if (condition3) {
  // code to run if condition3 is true
} 
If the first condition is false, JavaScript will check the next condition in the chain. If the second condition is false, JavaScript will check the third condition, and so on.

Sometimes you will want to run different code when all of the if...else if conditions are false. You can do this by adding an else block.

An else block will only evaluate if the conditions in the if and else if blocks are not met.

Here the else block is added to the else if block.

if (condition) {
  // this code will run if condition is true
} else if (condition2) {
  // this code will run if the first condition is false
} else {
  // this code will run 
  // if the first and second conditions are false
}

A while loop will run over and over again until the condition specified is no longer true. It has the following syntax:

while (condition) {
  logic;
}

The equality operator can lead to some strange behavior in JavaScript. For example, "0" == 0 is true, even though one is a string and one is a number.

The strict equality operator === is used to check if two values are equal and share the same type. As a general rule, this is the equality operator you should always use. With the strict equality operator, "0" === 0 becomes false, because while they might have the same value of zero, they are not of the same type.

The strict inequality operator !== allows you to check if two values are not equal, or do not have the same type. The syntax is similar to the equality operator: value !== 4.

The .unshift() method of an array allows you to add a value to the beginning of the array, unlike .push() which adds the value at the end of the array. Here is an example:

const numbers = [1, 2, 3];
numbers.unshift(5);

Arrays also have a .shift() method. This will remove the first element of the array, unlike .pop() which removes the last element. Here is an example of the .shift() method:

const numbers = [1, 2, 3];
numbers.shift();
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
  ['blockquote', 'code-block'],
  ['link', 'image', 'video', 'formula'],


  [{ 'header': 1 }, { 'header': 2 }],               // custom button values
  [{ 'list': 'ordered'}, { 'list': 'bullet' }, { 'list': 'check' }],
  [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
  [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
  [{ 'direction': 'rtl' }],                         // text direction


  [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
  [{ 'header': [1, 2, 3, 4, 5, 6, false] }],


  [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
  [{ 'font': [] }],
  [{ 'align': [] }],


  ['clean']                                         // remove formatting button
];


const quill = new Quill('#editor', {
  modules: {
    toolbar: toolbarOptions
  },
  theme: 'snow'
});
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
  ['blockquote', 'code-block'],
  ['link', 'image', 'video', 'formula'],


  [{ 'header': 1 }, { 'header': 2 }],               // custom button values
  [{ 'list': 'ordered'}, { 'list': 'bullet' }, { 'list': 'check' }],
  [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
  [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
  [{ 'direction': 'rtl' }],                         // text direction


  [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
  [{ 'header': [1, 2, 3, 4, 5, 6, false] }],


  [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
  [{ 'font': [] }],
  [{ 'align': [] }],


  ['clean']                                         // remove formatting button
];


const quill = new Quill('#editor', {
  modules: {
    toolbar: toolbarOptions
  },
  theme: 'snow'
});
let allTextInputs = postForm[0].querySelectorAll('input:not([type="radio"]):not([type="checkbox"])');

let allRadioInputs = postForm[0].querySelectorAll('input:not([type="text"]):not([type="checkbox"])');

let allCheckBoxInputs = postForm[0].querySelectorAll('input:not([type="text"]):not([type="radio"])');

let allSelectTags = postForm[0].querySelectorAll('select[required]');

console.log(allTextInputs, allCheckBoxInputs, allRadioInputs, allSelectTags);
var checkbox = document.getElementById("some-checkbox");
checkbox.indeterminate = true;
const express = require('express');
const app = express();

const bodyParser = require('body-parser');
app.use(bodyParser.json());
const cors = require('cors');

const dotenv = require('dotenv');
dotenv.config();

//! add db hear
const dbService = require('./utils/dbService');
const connection = require('./utils/dbService');
const multer = require('multer')
const moment = require("moment")
const fs = require('fs');
const path = require('path');



app.use(cors());

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





// Import the routes from routes.js
const routes = require('./routes/userRoute');

// Use the imported routes in your app.js file
// app.use(routes);


// Add a prefix to all routes
app.use('/api/v1', routes);




app.post('/login', (req, res) => {
    const { ao_name, ao_status } = req.body;
    console.log('Received login data:', req.body);

    var sql = "INSERT INTO app_occasion ( ao_name, ao_status ) VALUES ?";
    var values = [[ao_name, ao_status]];

    connection.query(sql, [values], function (err, result) {
        if (err) throw err;
        console.log("Records inserted: " + result.affectedRows);
        // Show alert message
        res.status(200).json({ message: 'Login data received' });
    });
});


 // TODO testing

 app.use("/uploads", express.static("./uploads"))
// // Image storage config
// const imgconfig = multer.diskStorage({
//     destination: (req, file, callback) => {
//         callback(null, "./uploads");
//     },
//     filename: (req, file, callback) => {
//         const uniqueName = `image-${Date.now()}-${file.originalname}`;
//         callback(null, uniqueName);
//     }
// });
// // Image filter
// const isImage = (req, file, callback) => {
//     if (file.mimetype.startsWith("image")) {
//         callback(null, true);
//     } else {
//         callback(new Error("Only images are allowed"));
//     }
// };
// const upload = multer({
//     storage: imgconfig,
//     fileFilter: isImage
// });


// 


// Function to generate folder name from organization name


// checking if same name folder name is exist  
// fs.readdir(uploadsPath, (err, files) => {
//     if (err) {
//         console.error('Error reading directory:', err);
//     } else {
//         if (files.includes(newFolderName)) {
//             console.log('Found  folder in uploads directory');


//         } else {
//             console.log(' folder NOT found in uploads directory');
//         }
//     }
// });





// Helper function to create a folder name based on the organization name
const generateFolderName = (orgName, basePath) => {
    // Start with the first letter of each word
    const folderName = orgName
        .split(" ")
        .map((word) => word[0].toLowerCase())
        .join("");

    // Check if the folder already exists
    const existingFolders = fs.readdirSync(basePath);
    let uniqueFolderName = folderName;
    let folderSuffix = '';
    const words = orgName.split(" ");

    // If the folder exists and has more words, add the second word in parentheses
    if (existingFolders.includes(uniqueFolderName) && words.length > 1) {
        folderSuffix = `(${words[1].toLowerCase()})`;
        uniqueFolderName += folderSuffix;
    }

    // If it still exists, keep adding next words in parentheses until unique
    let index = 2; // Start with the third word if needed
    while (existingFolders.includes(uniqueFolderName) && index < words.length) {
        folderSuffix = `(${words[index].toLowerCase()})`;
        uniqueFolderName = folderName + folderSuffix;
        index++;
    }

    // If after all words, it's still not unique, append a number to make it unique
    let counter = 2;
    while (existingFolders.includes(uniqueFolderName)) {
        uniqueFolderName = `${folderName}${folderSuffix}(${counter})`;
        counter++;
    }

    return uniqueFolderName;
};

// multer disk storage configuration
const imgconfig = multer.diskStorage({
    destination: (req, file, callback) => {
        const { ar_org_name } = req.body;
        if (!ar_org_name) {
            return callback(new Error("Organization name not provided"), false);
        }

        const uploadsPath = path.join(__dirname, 'uploads');
        const newFolderName = generateFolderName(ar_org_name, uploadsPath);
        const newFolderPath = path.join(uploadsPath, newFolderName);
        
        // Create the new directory if it doesn't exist
        fs.mkdirSync(newFolderPath, { recursive: true });

        callback(null, newFolderPath);
    },
    filename: (req, file, callback) => {
        const uniqueName = `image-${Date.now()}-${file.originalname}`;
        callback(null, uniqueName);
    }
});
















// Image filter
const isImage = (req, file, callback) => {
    if (file.mimetype.startsWith("image")) {
        callback(null, true);
    } else {
        callback(new Error("Only images are allowed"), false);
    }
};



const upload = multer({
    storage: imgconfig,
    fileFilter: isImage
});








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

// Handle form submission
app.post("/testing", upload.single("ar_org_logo"), (req, res) => {
    const {
        ar_org_name,
        ar_cp_signature,
        ar_contract_number,
        ar_emaill,
        ar_password,
        ar_conform_password,
        // ar_occecation_id
    } = req.body;

    // console.log("ar_org_name:", ar_org_name); 

// const newFolderName = ar_org_name;   //'newFolder'; // Replace with your logic to generate the folder name
// const uploadsPath = path.join(__dirname, 'uploads');
// const newFolderPath = path.join(uploadsPath, newFolderName);

// // Create the new directory
// fs.mkdirSync(newFolderPath, { recursive: true });

// console.log( "res.json({ message: 'Directory created successfully' });" );





    const { filename } = req.file;

    if (!ar_org_name || !ar_cp_signature || !ar_contract_number || !ar_emaill || !ar_password || !ar_conform_password  || !filename) {
        return res.status(422).json({ status: 422, message: "Fill all the details" });
    }

    try {
        const date = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");

        const userData = {
            ar_org_name,
            ar_cp_signature,
            ar_contract_number,
            ar_emaill,
            ar_password,
            ar_conform_password,
            // ar_occecation_id,
            ar_org_logo: filename,
            ar_creat_at: date,
            ar_status: 'pending'
        };
     

        connection.query("INSERT INTO app_cp_info SET ?", userData, (err, result) => {
            if (err) {
                console.error("Error inserting data", err);
                return res.status(500).json({ status: 500, message: "Database insertion error" });
            }
            console.log("Data added successfully");
            res.status(201).json({ status: 201, data: userData });
        });







       


    } catch (error) {
        console.error("Error in try block", error);
        res.status(500).json({ status: 500, message: "Internal server error" });
    }
});




// ! i want to show all data of app_registration 
app.get("/all-data-app_registration",(req,res)=>
{
    try {
        connection.query("SELECT * FROM app_registration",(err,result)=>{
            if(err){
                console.log(err)
            }else{
                console.log("get data successfully");
                res.status(201).json({ status: 201, data: result })
            }
        })
    } catch (error) {
        res.status(422).json({ status: 422, error })
    }
}
)



// Get all data (assuming this is for populating the select dropdown)
// app.get("/testing-get-data", (req, res) => {
//     conn.query("SELECT ao_id, ao_name FROM some_table", (err, results) => {
//         if (err) {
//             console.error("Error fetching data", err);
//             return res.status(500).json({ status: 500, message: "Database fetching error" });
//         }
//         res.status(200).json(results);
//     });
// });


// !
// // Multer storage configuration
// const storage = multer.diskStorage({
//     destination: function (req, file, cb) {
//         cb(null, './public/Images');
//     },
//     filename: function (req, file, cb) {
//         cb(null, `${Date.now()}_${file.originalname}`);
//     }
// });

// const upload = multer({ storage });

// app.post('/testing', upload.single('ar_org_logo'), (req, res) => {
//     const { ar_org_name, ar_cp_singhter, ar_contract_number, ar_emaill, ar_password, ar_conform_password, ar_occecation_id } = req.body;
//     const ar_org_logo = req.file.filename;

//     const sql = "INSERT INTO app_registration (ar_org_name, ar_org_logo, ar_cp_singhter, ar_contract_number, ar_emaill, ar_password, ar_conform_password, ar_occecation_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
//     const values = [ar_org_name, ar_org_logo, ar_cp_singhter, ar_contract_number, ar_emaill, ar_password, ar_conform_password, ar_occecation_id];

//     connection.query(sql, values, function (err, result) {
//         if (err) {
//             console.error('Error inserting into app_registration:', err);
//             return res.status(500).json({ message: 'Registration failed', error: err.message });
//         }
//         console.log("Registration record inserted: " + result.affectedRows);
//         res.status(200).json({ message: 'Successfully registered', ao_id: ar_occecation_id });
//     });
// });




                                                                                                                                                                                                                                


// !

// app.post('/testing', (req, res) => {
//     const { ar_org_name, ar_org_logo, ar_cp_singhter, ar_contract_number, ar_emaill, ar_password, ar_conform_password, ar_occecation_id } = req.body;

//     const sql = "INSERT INTO app_registration (ar_org_name, ar_org_logo, ar_cp_singhter, ar_contract_number, ar_emaill, ar_password, ar_conform_password, ar_occecation_id) VALUES ?";
//     const values = [[ar_org_name, ar_org_logo, ar_cp_singhter, ar_contract_number, ar_emaill, ar_password, ar_conform_password, ar_occecation_id]];

//     connection.query(sql, [values], function (err, result) {
//         if (err) {
//             console.error('Error inserting into app_registration:', err);
//             return res.status(500).json({ message: 'Registration failed not send ' });
//         }
//         console.log("Registration record inserted: " + result.affectedRows);
//         res.status(200).json({ message: 'Successfully send bireswar', ao_id: ar_occecation_id });
//     });
// });




app.get('/testing-get-data', (req, res) => {
    const query = 'SELECT * FROM app_occasion';
    connection.query(query, (err, results) => {
        if (err) {
            console.error(err.message);
            return res.status(500).send(err);
        }
        res.json(results);
    });
});



// // for file upload
// const storage = multer.diskStorage({
//     destination: function (req, file, cb) {
//         return cb(null, "./public/Images")
//     },
//     filename: function (req, file, cb) {
//         return cb(null, `${Date.now()}_${file.originalname}`)
//     }
// })

// const upload = multer({ storage })

// app.post('/upload', upload.single('file'), (req, res) => {
//     console.log(req.body)
//     console.log(req.file)
// })


// // app.post('/upload', upload.single('image'), (req, res) => {
// //     const image = req.file.filename;
// //     const sql = "UPDATE app_registration SET ar_org_logo = ?";
// //     db.query(sql, [image], (err, result) => {
// //         if (err) return res.json({ Message: "Error" });
// //         return res.json({ Status: "Success" });
// //     });
// // });


// // demo 002
// app.post('/upload', upload.single('image'), (req, res) => {
//     const image = req.file.filename;

//     const sql = "UPDATE users SET image = ? WHERE id = ?";  // Adjust the query as needed
//     const userId = 3;  // Replace with the actual user ID
//     const values = [image, userId];

//     db.query(sql, values, (err, result) => {
//         if (err) {
//             return res.json({ Message: "Error" });
//         }
//         return res.json({ Status: "Success" });
//     });
// });













// TODO testing



app.put('/update-application-status/:userId', async (req, res) => {
    const { userId } = req.params;
    const { application_status } = req.body;

    // Update logic for the database (example using a fictitious database function)
    // await database.updateApplicationStatus(userId, application_status);

    // var sql = "UPDATE  leave_from_rgpl SET application_status = 1 WHERE id = ?",[userId];
    connection.query('UPDATE leave_from_rgpl SET ? WHERE id = ?', [{ application_status: "1" }, userId]);


    // connection.query(sql, function (err, result) {
    //     if (err) throw err;
    //     console.log("Records updated: " + result.affectedRows);
    //     // Show alert message
    //     res.status(200).send('Login data received');
    //   });
    console.log("working")




});







app.put('/rejected/:userId', async (req, res) => {
    const { userId } = req.params;
    const { application_status } = req.body;

    // Update logic for the database (example using a fictitious database function)
    // await database.updateApplicationStatus(userId, application_status);

    // var sql = "UPDATE  leave_from_rgpl SET application_status = 1 WHERE id = ?",[userId];
    connection.query('UPDATE leave_from_rgpl SET ? WHERE id = ?', [{ application_status: "2" }, userId]);


    // connection.query(sql, function (err, result) {
    //     if (err) throw err;
    //     console.log("Records updated: " + result.affectedRows);
    //     // Show alert message
    //     res.status(200).send('Login data received');
    //   });
    console.log("working")




});











// app_super_section
// login_table_rgpl


// !  login from app_super_section
app.post('/aa', (req, res) => {
    const sql = "SELECT * FROM app_super_section WHERE email = ? AND password = ?";
    // const values = [
    //     req.body.email,
    //     req.body.password
    // ];

    connection.query(sql, [req.body.email, req.body.password], (err, data) => {
        if (err) return res.json("Login Failed");
        if (data.length > 0) {
            return res.json("Login Successful")

        } else {
            return res.json("INCORRECT EMAIL OR PASSWORD");
        }


    });
});









// var sql = "INSERT INTO leave_from_rgpl (name, college_name, class_coordinator_name, leave_date_from, leave_time_from, leave_date_up_to, leave_time_up_to, leave_type, reason_for_leave) VALUES ?";
// var values = [
//   [name, college_name, class_coordinator_name, `DATE_FORMAT('${leave_date_from}', '%Y-%m-%d`, // Format the date `TIME_FORMAT('${leave_time_from}', '%H:%i:%s.%f`, // Format the time `DATE_FORMAT('${leave_date_up_to}', '%Y-%m-%d`, // Format the date `TIME_FORMAT('${leave_time_up_to}', '%H:%i:%%f')`, // Format the time leave_type, reason_for_leave,
//   ],
// ];

// connection.query(sql, [values], function (err, result) {
//   if (err) throw err;
//   console.log("Records inserted: " + result.affectedRows);
//   // Show alert message
//   res.status(200).send('Login data received');
// });








// !my code
// app.post('/login', (req, res) => {
//     const { username, password } = req.body;

//     console.log('Received login data:');
//     // console.log('Username:', username);
//     // console.log('Password:', password);

//   var q = req.body.username;
//   var w = req.body.password;
// //   console.log(q,w);

// // module.exports =q;

//   // Export q and w variables




//   res.status(200).send('Login data received');


// });






// connection.connect((err) => {
//   if (err) {
//       console.log(err.message);
//   }
// //     //! this is i added for database state 
//   console.log('db ' + connection.state);
//   // console.log(q)
//   // console.log(msg);
// // });

// var sql = "INSERT INTO login (name,user_name,password) VALUES ?";

// // var { q, w } = require('./app');
// // console.log(q,w);

// var values =[[q,w,'123456']];

// connection.query(sql, [values], function (err, result) {
// if (err) throw err;
// console.log("records inserted: "+result.affectedRows);
// });

// });




// // Get all beers
// app.get('', (req, res) => {
//     pool.getConnection((err, connection) => {
//         if (err) throw err;
//         console.log(`connected as id ${connection.threadId}`);

//         connection.query('SELECT * from login', (err, rows) => {
//             connection.release(); // return the connection to the pool

//             if (err) {
//                 res.send(rows);
//             } else {
//                 console.log(err);
//             }
//         });
//     });
// });











app.get('/get-all-data', (req, res) => {
    const query = 'SELECT * FROM leave_from_rgpl';
    connection.query(query, (err, results) => {
        if (err) {
            console.error(err.message);
            return res.status(500).send(err);
        }
        res.json(results);
    });
});









app.put('/update-data/:id', (req, res) => {
    const { id } = req.params;
    const { newData } = req.body; // Replace `newData` with actual fields you want to update
    const query = 'UPDATE login SET ? WHERE id = ?'; // Replace with your table and field names

    connection.query(query, [newData, id], (err, results) => {
        if (err) {
            console.error(err.message);
            return res.status(500).send(err);
        }
        res.json({ success: true, message: 'Data updated successfully', results });
    });
});





// Endpoint to delete data
app.delete('/delete-data/:id', (req, res) => {
    const { id } = req.params;
    const query = 'DELETE FROM login WHERE id = ?';
    connection.query(query, [id], (err, results) => {
        if (err) {
            console.error(err.message);
            return res.status(500).send(err);
        }
        res.json({ success: true, message: 'Data deleted successfully', results });
    });
});






app.listen(process.env.PORT, () => console.log('app is running -->', process.env.PORT));


// module.exports = 'hello world';
const express = require('express');
const app = express();

const bodyParser = require('body-parser');
app.use(bodyParser.json());
const cors = require('cors');

const dotenv = require('dotenv');
dotenv.config();

//! add db hear
const dbService = require('./dbService');
const connection = require('./dbService');


app.use(cors());

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


// //! create data-base connection
// app.post('/insert', (request, response) => {
//     const { name } = request.body;
//     const db = dbService.getDbServiceInstance();
    
//     const result = db.insertNewName(name);

//     result
//     .then(data => response.json({ data: data}))
//     .catch(err => console.log(err));
// });

// //! read data-base connection
// app.get('/getAll', (request, response) => {
//     const db = dbService.getDbServiceInstance();

//     const result = db.getAllData();
    
//     result
//     .then(data => response.json({data : data}))
//     .catch(err => console.log(err));
// })

// // update
// app.patch('/update', (request, response) => {
//     const { id, name } = request.body;
//     const db = dbService.getDbServiceInstance();

//     const result = db.updateNameById(id, name);
    
//     result
//     .then(data => response.json({success : data}))
//     .catch(err => console.log(err));
// });

// // delete
// app.delete('/delete/:id', (request, response) => {
//     const { id } = request.params;
//     const db = dbService.getDbServiceInstance();

//     const result = db.deleteRowById(id);
    
//     result
//     .then(data => response.json({success : data}))
//     .catch(err => console.log(err));
// });

// app.get('/search/:name', (request, response) => {
//     const { name } = request.params;
//     const db = dbService.getDbServiceInstance();

//     const result = db.searchByName(name);
    
//     result
//     .then(data => response.json({data : data}))
//     .catch(err => console.log(err));
// })





// const connection = require('./dbService');

// Now you can use the 'connection' variable in your app.js file
// For example, you can query the database using this connection
// connection.query('SELECT * FROM names;', (err, results) => {
//     if (err) {
//         console.error(err);
//         return;
//     }
//     console.log(results);
// });





app.post('/login', (req, res) => {
    const { ao_name, ao_status } = req.body;
    console.log('Received login data:', req.body);

    var sql = "INSERT INTO app_occasion ( ao_name, ao_status ) VALUES ?";
    var values = [[ao_name, ao_status]];

  connection.query(sql, [values], function (err, result) {
    if (err) throw err;
    console.log("Records inserted: " + result.affectedRows);
    // Show alert message
    res.status(200).send('Login data received');
  });
});








app.put('/update-application-status/:userId', async (req, res) => {
    const { userId } = req.params;
    const { application_status } = req.body;
  
        // Update logic for the database (example using a fictitious database function)
        // await database.updateApplicationStatus(userId, application_status);

// var sql = "UPDATE  leave_from_rgpl SET application_status = 1 WHERE id = ?",[userId];
connection.query('UPDATE leave_from_rgpl SET ? WHERE id = ?', [{ application_status: "1" }, userId]);


// connection.query(sql, function (err, result) {
//     if (err) throw err;
//     console.log("Records updated: " + result.affectedRows);
//     // Show alert message
//     res.status(200).send('Login data received');
//   });
        console.log("working")



       
});







app.put('/rejected/:userId', async (req, res) => {
    const { userId } = req.params;
    const { application_status } = req.body;
  
        // Update logic for the database (example using a fictitious database function)
        // await database.updateApplicationStatus(userId, application_status);

// var sql = "UPDATE  leave_from_rgpl SET application_status = 1 WHERE id = ?",[userId];
connection.query('UPDATE leave_from_rgpl SET ? WHERE id = ?', [{ application_status: "2" }, userId]);


// connection.query(sql, function (err, result) {
//     if (err) throw err;
//     console.log("Records updated: " + result.affectedRows);
//     // Show alert message
//     res.status(200).send('Login data received');
//   });
        console.log("working")



       
});











// app_super_section
// login_table_rgpl


// !  login from app_super_section
app.post('/aa', (req, res) => {
    const sql = "SELECT * FROM app_super_section WHERE email = ? AND password = ?";
    // const values = [
    //     req.body.email,
    //     req.body.password
    // ];
    
    connection.query(sql, [ req.body.email, req.body.password], (err, data) => {
        if (err) return res.json("Login Failed");
        if(data.length > 0){
            return res.json("Login Successful")
            
        }else {
            return res.json("INCORRECT EMAIL OR PASSWORD");
        }
       
        
    });
});









// var sql = "INSERT INTO leave_from_rgpl (name, college_name, class_coordinator_name, leave_date_from, leave_time_from, leave_date_up_to, leave_time_up_to, leave_type, reason_for_leave) VALUES ?";
// var values = [
//   [name, college_name, class_coordinator_name, `DATE_FORMAT('${leave_date_from}', '%Y-%m-%d`, // Format the date `TIME_FORMAT('${leave_time_from}', '%H:%i:%s.%f`, // Format the time `DATE_FORMAT('${leave_date_up_to}', '%Y-%m-%d`, // Format the date `TIME_FORMAT('${leave_time_up_to}', '%H:%i:%%f')`, // Format the time leave_type, reason_for_leave,
//   ],
// ];

// connection.query(sql, [values], function (err, result) {
//   if (err) throw err;
//   console.log("Records inserted: " + result.affectedRows);
//   // Show alert message
//   res.status(200).send('Login data received');
// });








// !my code
// app.post('/login', (req, res) => {
//     const { username, password } = req.body;

//     console.log('Received login data:');
//     // console.log('Username:', username);
//     // console.log('Password:', password);

//   var q = req.body.username;
//   var w = req.body.password;
// //   console.log(q,w);

// // module.exports =q;

//   // Export q and w variables




//   res.status(200).send('Login data received');


// });






// connection.connect((err) => {
//   if (err) {
//       console.log(err.message);
//   }
// //     //! this is i added for database state 
//   console.log('db ' + connection.state);
//   // console.log(q)
//   // console.log(msg);
// // });

// var sql = "INSERT INTO login (name,user_name,password) VALUES ?";

// // var { q, w } = require('./app');
// // console.log(q,w);

// var values =[[q,w,'123456']];

// connection.query(sql, [values], function (err, result) {
// if (err) throw err;
// console.log("records inserted: "+result.affectedRows);
// });

// });




// // Get all beers
// app.get('', (req, res) => {
//     pool.getConnection((err, connection) => {
//         if (err) throw err;
//         console.log(`connected as id ${connection.threadId}`);

//         connection.query('SELECT * from login', (err, rows) => {
//             connection.release(); // return the connection to the pool

//             if (err) {
//                 res.send(rows);
//             } else {
//                 console.log(err);
//             }
//         });
//     });
// });











app.get('/get-all-data', (req, res) => {
    const query = 'SELECT * FROM leave_from_rgpl'; 
    connection.query(query, (err, results) => {
        if (err) {
            console.error(err.message);
            return res.status(500).send(err);
        }
        res.json(results);
    });
});









app.put('/update-data/:id', (req, res) => {
    const { id } = req.params;
    const { newData } = req.body; // Replace `newData` with actual fields you want to update
    const query = 'UPDATE login SET ? WHERE id = ?'; // Replace with your table and field names

    connection.query(query, [newData, id], (err, results) => {
        if (err) {
            console.error(err.message);
            return res.status(500).send(err);
        }
        res.json({ success: true, message: 'Data updated successfully', results });
    });
});





// Endpoint to delete data
app.delete('/delete-data/:id', (req, res) => {
    const { id } = req.params;
    const query = 'DELETE FROM login WHERE id = ?';
    connection.query(query, [id], (err, results) => {
        if (err) {
            console.error(err.message);
            return res.status(500).send(err);
        }
        res.json({ success: true, message: 'Data deleted successfully', results });
    });
});






app.listen(process.env.PORT, () => console.log('app is running -->',process.env.PORT));


// module.exports = 'hello world';
function onEdit(e) {
  if (!e) return;

  var sheet = e.source.getActiveSheet();
  var range = e.range;
  var editedValue = e.value;
  var previousValue = e.oldValue;

  // Define the start columns and start rows for each sheet
  var config = {
    "Pengajuan Konten": { columns: [5, 6, 19, 23, 28], startRow: 3 },
    "Timeline Wilayah": { columns: [8, 9], startRow: 2 },
    "Akun Media Partnership": { startColumn: 7, startRow: 5 }
    // Add more sheets and their configurations here
  };

  var sheetName = sheet.getName();
  if (!config[sheetName]) return; // Exit if the sheet is not configured

  var sheetConfig = config[sheetName];
  var startColumns = sheetConfig.columns || [sheetConfig.startColumn];
  var startRow = sheetConfig.startRow;

  if (startColumns.indexOf(range.getColumn()) !== -1 && range.getRow() >= startRow) {
    if (previousValue == null || previousValue === "") {
      range.setValue(editedValue);
    } else {
      var previousValues = previousValue.split(', ');

      var index = previousValues.indexOf(editedValue);

      if (index === -1) {
        previousValues.push(editedValue);
      } else {
        previousValues.splice(index, 1);
      }

      range.setValue(previousValues.join(', '));
    }
  }
}
const XLSX = require("xlsx");
const fs = require("fs");
const path = require("path");

const filePath = "3Status.xlsx"; //File path of excel

const workbook = XLSX.readFile(filePath);
const worksheet = workbook.Sheets["Sheet0"];
const data = XLSX.utils.sheet_to_json(worksheet);
const folderPath = "test"; //File path of git TCs
const filePaths = [];

function getFilePaths(directory) {
  const items = fs.readdirSync(directory);
  for (const item of items) {
    const itemPath = path.join(directory, item);
    if (fs.statSync(itemPath).isDirectory()) {
      getFilePaths(itemPath);
    } else {
      filePaths.push(itemPath);
    }
  }
}
getFilePaths(folderPath);
function newProc(filePaths, keyword) {
  let flag1 = false;
  for (const singlePath of filePaths) {
    const fileContent = fs.readFileSync(singlePath, "utf-8");
    //console.log("fileContent is ", fileContent)
    if (fileContent.includes(keyword)) {
      flag1 = true;
      //console.log(`Keyword '${keyword}' found in file: ${singlePath}`);
    }
  }
  return flag1;
}
let notAutomated = [];
for (const i of data) {
  let flag = false;
  let check = newProc(filePaths, i["TestRail Id"]);
  //console.log("check is ", check)
  if (check == false) {
    notAutomated.push(i["TestRail Id"]);
    //console.log(`${i["TestRail Id"]} is not automated`)
  }
}
console.log(`notAutomated TCs are `, notAutomated);
console.log("No.of notAutomated are ", notAutomated.length);

//Storing the notAutomated ones in the excel file
const values = ["NonAutomatedTestRailIds", ...notAutomated];
const workbook1 = XLSX.utils.book_new();
const worksheet1 = XLSX.utils.aoa_to_sheet([]);
values.forEach((value, index) => {
  const cellAddress = XLSX.utils.encode_cell({ c: 0, r: index }); // column 0, row index
  worksheet1[cellAddress] = { v: value };
});
worksheet1["!ref"] = XLSX.utils.encode_range({
  s: { c: 0, r: 0 },
  e: { c: 0, r: values.length - 1 },
});
XLSX.utils.book_append_sheet(workbook1, worksheet1, "Sheet1");
XLSX.writeFile(workbook1, "NonAutomatedTestRailIdsFile.xlsx");
import React from 'react';

class MessageWithEvent extends React.Component {
   constructor(props) {
      super(props);

      this.logEventToConsole = this.logEventToConsole.bind();
   }
   logEventToConsole(e) {
      console.log(e.target.innerHTML);
   }
   render() {
      return (
         <div onClick={this.logEventToConsole}>
            <p>Hello {this.props.name}!</p>
         </div>
      );
   }
}
export default MessageWithEvent;
describe('DBM Smoketests', function() {
  it('E2E Hotel2 WorldPay System', function() {
    cy.visit('https://obmng.dbm.guestline.net/');
    cy.url().should('include','/obmng.dbm');

    Cypress.on('test:after:run', (test) => {
      addContext({ test }, { 
        title: 'This is my context title', 
        value: 'This is my context value'
      })
    });
  });
});
if ('serviceWorker' in navigator) {
  var scope = location.pathname.replace(/\/[^\/]+$/, '/')
  navigator.serviceWorker.register('sw.js', { scope })
    .then(function(reg) {
       reg.addEventListener('updatefound', function() {
         var installingWorker = reg.installing;
         console.log('A new service worker is being installed:',
                     installingWorker);
       });
       // registration worked
       console.log('Registration succeeded. Scope is ' + reg.scope);
    }).catch(function(error) {
      // registration failed
      console.log('Registration failed with ' + error);
    });
}
javascript: (function () {
  const input = prompt("input", document.getSelection().toString());
  if (input) {
    const output = input.replace(/[\u0300\u0301]/g, "");
    window.alert(output);
    navigator.clipboard.writeText(output);
  }
})();
<script>
  async function harryPotterStudents() {
      const res = await fetch('https://hp-api.herokuapp.com/api/characters/students');
      const json = await res.json()

      if (res.ok) {
          return json
      } else {
          throw new Error(json)
      }
  }

  let promise = harryPotterStudents()
</script>

<h2>Estudiantes de la saga Harry Potter (promesas)</h2>
{#await promise}
  <p>Esperando resultados...</p>
{:then students}
  <p>Total estudiantes: {students.length}</p>
  {#each students as {name: alt, house, image: src}}
    {#if src}
      <h3>{alt} ({house})</h3>
      <img height="100" {src} {alt} />
    {/if}
  {/each}
{:catch error}
  <p style="color: red">{error.message}</p>
{/await}
/*
 * @Author: allen_
 * @Date: 2024-05-22 10:45:18
 * @Email: zhangxudong_a@aspirecn.com
 * @LastEditors: allen_
 * @LastEditTime: 2024-05-23 15:43:17
 * @Description: 水印
 * @example:
 *   watermark.set(this.$refs.body, { text: '水印文字', gap: [50, 100], fontSize: 14, color: 'rgba(0, 0, 0, 0.35)'})
 */
import html2canvas from 'html2canvas'
const watermark = {}

/**
 * @description: 设置水印
 * @param {*} sourceBody 需要设置的元素
 * @param {*} text 水印文字
 * @param {array} gap 水印间距 [上下间距, 左右间距]
 * @param {*} fontSize 水印文字大小
 * @param {*} color 水印字体颜色
 * @param {*} zIndex 水印层级
 * @param {*} rotate 水印角度
 */
const setWatermark = (sourceBody, { text = 'watermark', gap = [100, 120], fontSize = 14, color = 'rgba(0, 0, 0, 0.25)', zIndex = 9999, rotate = -22, custom = null }) => {
  // @Explain: 生成随机元素 id
  const id = Math.random() * 10000 + '-' + Math.random() * 10000 + '/' + Math.random() * 10000

  if (document.getElementById(id) !== null) {
    document.body.removeChild(document.getElementById(id))
  }
  let canvasData = null
  if (!custom) {
    const can = document.createElement('canvas')
    can.height = gap[0] // 水印上下间距
    can.width = gap[1] // 水印左右间距

    const cans = can.getContext('2d')
    cans.rotate((rotate * Math.PI) / 180)
    cans.font = fontSize + 'px Microsoft YaHei'
    cans.fillStyle = color
    cans.textAlign = 'left'
    cans.textBaseline = 'Middle'
    cans.fillText(text, can.width / 20, can.height / 3)
    canvasData = can.toDataURL('image/png', 1.0)
  } else {
    canvasData = custom
  }

  const water_div = document.createElement('div')
  water_div.id = id
  water_div.className = 'watermark-body'
  const styleStr = `
    background: url(${canvasData}) left top repeat;
    pointer-events: none;
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: ${zIndex};
    top: 0px;
    left: 0px;
  `
  water_div.setAttribute('style', styleStr)
  const partnerStyle = `
    ${sourceBody.getAttribute('style') || ''}
    position: relative;
    userSelect: none;
  `
  sourceBody.setAttribute('style', partnerStyle)
  sourceBody.appendChild(water_div)

  // 防止水印被删除
  const observer = new MutationObserver(() => {
    const wmInstance = document.getElementById(id)
    if ((wmInstance && wmInstance.getAttribute('style') !== styleStr) || !wmInstance) {
      // 如果标签在,只修改了属性,重新赋值属性
      if (wmInstance) {
        // 避免一直触发 -- 水印属性修改了
        wmInstance.setAttribute('style', styleStr)
      } else {
        // observer.disconnect()
        sourceBody.appendChild(water_div)
      }
    } else if (sourceBody.getAttribute('style') !== partnerStyle) {
      // @Explain: 判断父元素样式是否存在更改
      sourceBody.setAttribute('style', partnerStyle)
    }
  })
  observer.observe(sourceBody, {
    attributes: true,
    subtree: true,
    childList: true
  })

  return id
}

// @Explain: 为元素设置水印
watermark.set = (sourceBody, opi) => {
  const domArr = Array.from(document.getElementsByClassName('watermark-body'))
  for (let i = domArr.length; i--;) {
    const element = domArr[i]
    element.remove()
  }
  if ((!opi.text && !opi.custom) || !sourceBody) return null
  if (!(sourceBody instanceof HTMLElement)) {
    // @Condition: 判断传入的元素是否为dom元素 || VueComponent
    sourceBody = sourceBody.$el
  }
  const id = setWatermark(sourceBody, opi)
  return id
}
// @Explain: html2canvas 创建元素 base64
watermark.baseImg = (el, scale = window.devicePixelRatio < 3 ? window.devicePixelRatio : 2) => {
  return new Promise((resolve) => {
    html2canvas(el, {
      useCORS: true, // 【重要】开启跨域配置
      scale,
      allowTaint: true, // 允许跨域图片
      backgroundColor: null // 是否设置背景色透明
    }).then((canvas) => {
      const imgData = canvas.toDataURL('img/jpg', 1.0)
      resolve(imgData)
    })
  })
}
// @Explain: 创建水印方法
watermark.create = (text = 'watermark', callback = null, cache = true) => {
  if (callback && typeof callback === 'function') {
    // @Condition: 自定义水印元素创建方法
    return callback(text, watermark)
  }
  // @Explain: 判断缓存创建的水印元素是否存在
  if (watermark.cacheEl && cache) {
    watermark.cacheEl.querySelector('.watermark-user-info').innerText = text
    return watermark.cacheEl
  }
  const div = document.createElement('div')
  div.style = `
    width: 200px;
    height: 160px;
    display: flex;
    align-items: center;`
  const watermarkDiv = document.createElement('div')
  watermarkDiv.style = `
    width: 210px;
    height: 48px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
    transform-origin: center;
    transform: rotate(-35deg);`
  const img = document.createElement('img')
  img.style = 'width: 201px;'
  // if you need image, edit here
  // img.src = require('@/assets/img/watermark.png')
  const userInfo = document.createElement('div')
  userInfo.className = 'watermark-user-info'
  userInfo.style = `
    font-size: 12px;
    color: rgba(38, 42, 48, 0.1);
    letter-spacing: 0;
    font-family: PingFangSC-Regular;`
  userInfo.innerText = text
  watermarkDiv.appendChild(img)
  watermarkDiv.appendChild(userInfo)
  div.appendChild(watermarkDiv)
  watermark.cacheEl = div // 缓存水印元素
  return div
}

export default watermark
var largestLocal = function (grid) {
    let rowLen = grid.length, colLen = grid[0].length
    console.log(rowLen, colLen)
    let mainArr = []
    for (let init = 0; rowLen - init > 2; init++) {
        let childArr = []
        let tem = 0
        for (let col = tem; rowLen - col > 2; col++) {
            let container = []
            for (let sub = init; sub < 3; sub++) {
                let sumTemp = grid[sub].slice(col, 3);
                console.log("sumTemp at ", sub, " is ", sumTemp)
                container.push(...sumTemp)
                console.log("container at ", sub, " is ", container)
            }
            let max = Math.max(...container);
            console.log("max at ", col, " is ", max)
            childArr.push(max)
            console.log("childArr at ", col, " is ", childArr)

        }
        mainArr.push([...childArr])
    }
    return mainArr
};
// Get user media
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
  .then(stream => {
    const localVideo = document.getElementById('localVideo');
    localVideo.srcObject = stream;

    const peerConnection = new RTCPeerConnection();
    stream.getTracks().forEach(track => peerConnection.addTrack(track, stream));

    // Set up ICE handling
    peerConnection.onicecandidate = event => {
      if (event.candidate) {
        // Send the candidate to the remote peer
        sendToServer({ type: 'candidate', candidate: event.candidate });
      }
    };

    // When remote stream arrives
    peerConnection.ontrack = event => {
      const remoteVideo = document.getElementById('remoteVideo');
      remoteVideo.srcObject = event.streams[0];
    };

    // Create an offer to connect
    peerConnection.createOffer()
      .then(offer => peerConnection.setLocalDescription(offer))
      .then(() => {
        // Send the offer to the remote peer
        sendToServer({ type: 'offer', offer: peerConnection.localDescription });
      });

    // Handle offer from a remote peer
    receiveFromServer(message => {
      if (message.type === 'offer') {
        peerConnection.setRemoteDescription(new RTCSessionDescription(message.offer))
          .then(() => peerConnection.createAnswer())
          .then(answer => peerConnection.setLocalDescription(answer))
          .then(() => {
            // Send the answer to the remote peer
            sendToServer({ type: 'answer', answer: peerConnection.localDescription });
          });
      } else if (message.type === 'answer') {
        peerConnection.setRemoteDescription(new RTCSessionDescription(message.answer));
      } else if (message.type === 'candidate') {
        peerConnection.addIceCandidate(new RTCIceCandidate(message.candidate));
      }
    });
  })
  .catch(error => {
    console.error('Error accessing media devices.', error);
  });

function sendToServer(message) {
  // Implement server communication to exchange messages
}

function receiveFromServer(callback) {
  // Implement server communication to receive messages
}
function combinations(arr, len) {
    let tempArry = []
    let final = []
    for (let i = 0; i < arr.length; i++) {
        //console.log("i ", i)
        if ((arr.length - i) == (len - 1)) {
            break
        }
        tempArry.push(arr[i])
        for (let j = i + 1; j < arr.length; j++) {
            //console.log("j ", j)
            tempArry.push(arr[j])
            //console.log("tempArry ", tempArry)
            if (tempArry.length == len) {
                //console.log("tempArry inside if ", tempArry)
                final.push([...tempArry])
                //console.log("final inside if ", final)
                tempArry.pop()
            }
        }
        tempArry = []
    }
    //console.log("final ", final)
    return final
}

function getPermutations(arr, outputLength) {
  const results = [];

  function permute(currentArr, remaining) {
    if (currentArr.length === outputLength) {
      results.push([...currentArr]); // Copy current arrangement to avoid mutation
      return;
    }

    for (let i = 0; i < remaining.length; i++) {
      const nextElement = remaining[i];
      const remainingCopy = [...remaining]; // Copy to avoid mutation
      remainingCopy.splice(i, 1);
      permute([...currentArr, nextElement], remainingCopy);
    }
  }

  permute([], arr);
  return results;
}

function processor(ind, finalQuality, mapWages, combOfWage) {
    let currentQua1 = finalQuality[ind]
    let currentWage1 = combOfWage[ind]
    //let currentWage1 = mapWages.get(finalQuality[ind])
    let after = Number(ind) + 1
    let afterQua = finalQuality[after]
    let afterWage1 = combOfWage[after]
    //let afterWage1 = mapWages.get(finalQuality[after])
    let g = afterQua / currentQua1
    combOfWage[after] = (g * currentWage1)
    //mapWages.set(afterQua, (g * currentWage1))
}
var mincostToHireWorkers = function (quality, wage, k) {
    let accumulate = 0
    let mapWages = new Map()
    for (const f in quality) {
        mapWages.set(quality[f], wage[f])
    }
    let resAccu = []
    console.log(mapWages)

    // let comb = combinations(quality, k)
    // console.log("comb ", comb)
    // let combOfWages = combinations(wage, k)
    // console.log("combOfWages ", combOfWages)

    let comb = getPermutations(quality, k)
    console.log("comb ", comb)
    let combOfWages = getPermutations(wage, k)
    console.log("combOfWages ", combOfWages)

    for (const g in comb) {
        let SortedQuality = comb[g]
        let combOfWage = combOfWages[g]
        console.log("SortedQuality is ", SortedQuality)
        let finalQuality = SortedQuality
        console.log("finalQuality is ", finalQuality)
        for (let i = finalQuality.length - 1; i >= 0; i--) {
            let prev = Number(i) - 1
            console.log("prev ", prev)
            let currentQua = finalQuality[i]
            console.log("currentQua ", currentQua)
            let currentWage = combOfWages[g][i]
            //let currentWage = mapWages.get(finalQuality[i])
            console.log("currentWage ", currentWage)
            if (i > 0) {
                let prevQua = finalQuality[prev]
                console.log("prevQua ", prevQua)
                let prevWage = combOfWages[g][prev]
                //let prevWage = mapWages.get(finalQuality[prev])
                console.log("prevWage ", prevWage)
                let ntha = currentQua / prevQua
                console.log("ntha ", ntha)
                let x = (currentWage * prevQua) / currentQua
                console.log("x ", x)
                if (x < prevWage) {
                    combOfWages[g][i] = (ntha * prevWage)
                    console.log("combOfWages[g][i] is ", combOfWages[g][i])
                    //mapWages.set(currentQua, (ntha * prevWage))
                    for (let k = i; k < finalQuality.length; k++) {
                        processor(k, finalQuality, mapWages,combOfWage )
                    }
                } else if (x > prevWage) {
                    accumulate = accumulate + currentWage
                    combOfWages[g][prev] = x
                    //mapWages.set(prevQua, x)
                } else if (x == prevWage) {
                    accumulate = accumulate + currentWage
                }
            } else {
                accumulate = accumulate + currentWage
            }
            console.log("accumulate ", accumulate)

        }
        accumulate = 0
        for (const l in finalQuality) {
            accumulate = accumulate + combOfWages[g][l]
            console.log("last finalQuality", finalQuality)
            console.log("last accumulate", accumulate)
            //accumulate = accumulate + mapWages.get(l)
        }
        resAccu.push(accumulate)
        console.log("resAccu is ", resAccu)
    }
    let finalResAccu = resAccu.sort((a, b) => a - b)
    return finalAcc = finalResAccu[0]
};
function combinations(arr, len) {
    let tempArry = []
    let final = []
    for (let i = 0; i < arr.length; i++) {
        //console.log("i ", i)
        if ((arr.length - i) == (len - 1)) {
            break
        }
        tempArry.push(arr[i])
        for (let j = i + 1; j < arr.length; j++) {
            //console.log("j ", j)
            tempArry.push(arr[j])
            //console.log("tempArry ", tempArry)
            if (tempArry.length == len) {
                //console.log("tempArry inside if ", tempArry)
                final.push([...tempArry])
                //console.log("final inside if ", final)
                tempArry.pop()
            }
        }
        tempArry = []
    }
    //console.log("final ", final)
    return final
}

function getPermutations(arr, outputLength) {
  const results = [];

  function permute(currentArr, remaining) {
    if (currentArr.length === outputLength) {
      results.push([...currentArr]); // Copy current arrangement to avoid mutation
      return;
    }

    for (let i = 0; i < remaining.length; i++) {
      const nextElement = remaining[i];
      const remainingCopy = [...remaining]; // Copy to avoid mutation
      remainingCopy.splice(i, 1);
      permute([...currentArr, nextElement], remainingCopy);
    }
  }

  permute([], arr);
  return results;
}

function processor(ind, finalQuality, mapWages, combOfWage) {
    let currentQua1 = finalQuality[ind]
    let currentWage1 = combOfWage[ind]
    //let currentWage1 = mapWages.get(finalQuality[ind])
    let after = Number(ind) + 1
    let afterQua = finalQuality[after]
    let afterWage1 = combOfWage[after]
    //let afterWage1 = mapWages.get(finalQuality[after])
    let g = afterQua / currentQua1
    combOfWage[after] = (g * currentWage1)
    //mapWages.set(afterQua, (g * currentWage1))
}
var mincostToHireWorkers = function (quality, wage, k) {
    let accumulate = 0
    let mapWages = new Map()
    for (const f in quality) {
        mapWages.set(quality[f], wage[f])
    }
    let resAccu = []
    console.log(mapWages)

    // let comb = combinations(quality, k)
    // console.log("comb ", comb)
    // let combOfWages = combinations(wage, k)
    // console.log("combOfWages ", combOfWages)

    let comb = getPermutations(quality, k)
    console.log("comb ", comb)
    let combOfWages = getPermutations(wage, k)
    console.log("combOfWages ", combOfWages)

    for (const g in comb) {
        let SortedQuality = comb[g]
        let combOfWage = combOfWages[g]
        console.log("SortedQuality is ", SortedQuality)
        let finalQuality = SortedQuality
        console.log("finalQuality is ", finalQuality)
        for (let i = finalQuality.length - 1; i >= 0; i--) {
            let prev = Number(i) - 1
            console.log("prev ", prev)
            let currentQua = finalQuality[i]
            console.log("currentQua ", currentQua)
            let currentWage = combOfWages[g][i]
            //let currentWage = mapWages.get(finalQuality[i])
            console.log("currentWage ", currentWage)
            if (i > 0) {
                let prevQua = finalQuality[prev]
                console.log("prevQua ", prevQua)
                let prevWage = combOfWages[g][prev]
                //let prevWage = mapWages.get(finalQuality[prev])
                console.log("prevWage ", prevWage)
                let ntha = currentQua / prevQua
                console.log("ntha ", ntha)
                let x = (currentWage * prevQua) / currentQua
                console.log("x ", x)
                if (x < prevWage) {
                    combOfWages[g][i] = (ntha * prevWage)
                    console.log("combOfWages[g][i] is ", combOfWages[g][i])
                    //mapWages.set(currentQua, (ntha * prevWage))
                    for (let k = i; k < finalQuality.length; k++) {
                        processor(k, finalQuality, mapWages,combOfWage )
                    }
                } else if (x > prevWage) {
                    accumulate = accumulate + currentWage
                    combOfWages[g][prev] = x
                    //mapWages.set(prevQua, x)
                } else if (x == prevWage) {
                    accumulate = accumulate + currentWage
                }
            } else {
                accumulate = accumulate + currentWage
            }
            console.log("accumulate ", accumulate)

        }
        accumulate = 0
        for (const l in finalQuality) {
            accumulate = accumulate + combOfWages[g][l]
            console.log("last finalQuality", finalQuality)
            console.log("last accumulate", accumulate)
            //accumulate = accumulate + mapWages.get(l)
        }
        resAccu.push(accumulate)
        console.log("resAccu is ", resAccu)
    }
    let finalResAccu = resAccu.sort((a, b) => a - b)
    return finalAcc = finalResAccu[0]
};
function combinations(arr, len) {
    let tempArry = []
    let final = []
    for (let i = 0; i < arr.length; i++) {
        //console.log("i ", i)
        if ((arr.length - i) == (len - 1)) {
            break
        }
        tempArry.push(arr[i])
        for (let j = i + 1; j < arr.length; j++) {
            //console.log("j ", j)
            tempArry.push(arr[j])
            //console.log("tempArry ", tempArry)
            if (tempArry.length == len) {
                //console.log("tempArry inside if ", tempArry)
                final.push([...tempArry])
                //console.log("final inside if ", final)
                tempArry.pop()
            }
        }
        tempArry = []
    }
    //console.log("final ", final)
    return final
}

function getPermutations(arr, outputLength) {
  const results = [];

  function permute(currentArr, remaining) {
    if (currentArr.length === outputLength) {
      results.push([...currentArr]); // Copy current arrangement to avoid mutation
      return;
    }

    for (let i = 0; i < remaining.length; i++) {
      const nextElement = remaining[i];
      const remainingCopy = [...remaining]; // Copy to avoid mutation
      remainingCopy.splice(i, 1);
      permute([...currentArr, nextElement], remainingCopy);
    }
  }

  permute([], arr);
  return results;
}

function processor(ind, finalQuality, mapWages, combOfWage) {
    let currentQua1 = finalQuality[ind]
    let currentWage1 = combOfWage[ind]
    //let currentWage1 = mapWages.get(finalQuality[ind])
    let after = Number(ind) + 1
    let afterQua = finalQuality[after]
    let afterWage1 = combOfWage[after]
    //let afterWage1 = mapWages.get(finalQuality[after])
    let g = afterQua / currentQua1
    combOfWage[after] = (g * currentWage1)
    //mapWages.set(afterQua, (g * currentWage1))
}
var mincostToHireWorkers = function (quality, wage, k) {
    let accumulate = 0
    let mapWages = new Map()
    for (const f in quality) {
        mapWages.set(quality[f], wage[f])
    }
    let resAccu = []
    console.log(mapWages)

    // let comb = combinations(quality, k)
    // console.log("comb ", comb)
    // let combOfWages = combinations(wage, k)
    // console.log("combOfWages ", combOfWages)

    let comb = getPermutations(quality, k)
    console.log("comb ", comb)
    let combOfWages = getPermutations(wage, k)
    console.log("combOfWages ", combOfWages)

    for (const g in comb) {
        let SortedQuality = comb[g]
        let combOfWage = combOfWages[g]
        console.log("SortedQuality is ", SortedQuality)
        let finalQuality = SortedQuality
        console.log("finalQuality is ", finalQuality)
        for (let i = finalQuality.length - 1; i >= 0; i--) {
            let prev = Number(i) - 1
            console.log("prev ", prev)
            let currentQua = finalQuality[i]
            console.log("currentQua ", currentQua)
            let currentWage = combOfWages[g][i]
            //let currentWage = mapWages.get(finalQuality[i])
            console.log("currentWage ", currentWage)
            if (i > 0) {
                let prevQua = finalQuality[prev]
                console.log("prevQua ", prevQua)
                let prevWage = combOfWages[g][prev]
                //let prevWage = mapWages.get(finalQuality[prev])
                console.log("prevWage ", prevWage)
                let ntha = currentQua / prevQua
                console.log("ntha ", ntha)
                let x = (currentWage * prevQua) / currentQua
                console.log("x ", x)
                if (x < prevWage) {
                    combOfWages[g][i] = (ntha * prevWage)
                    console.log("combOfWages[g][i] is ", combOfWages[g][i])
                    //mapWages.set(currentQua, (ntha * prevWage))
                    for (let k = i; k < finalQuality.length; k++) {
                        processor(k, finalQuality, mapWages,combOfWage )
                    }
                } else if (x > prevWage) {
                    accumulate = accumulate + currentWage
                    combOfWages[g][prev] = x
                    //mapWages.set(prevQua, x)
                } else if (x == prevWage) {
                    accumulate = accumulate + currentWage
                }
            } else {
                accumulate = accumulate + currentWage
            }
            console.log("accumulate ", accumulate)

        }
        accumulate = 0
        for (const l in finalQuality) {
            accumulate = accumulate + combOfWages[g][l]
            console.log("last finalQuality", finalQuality)
            console.log("last accumulate", accumulate)
            //accumulate = accumulate + mapWages.get(l)
        }
        resAccu.push(accumulate)
        console.log("resAccu is ", resAccu)
    }
    let finalResAccu = resAccu.sort((a, b) => a - b)
    return finalAcc = finalResAccu[0]
};
$('button.toggle-detail-row').click(function(){
		   
  let rowId = $(this).attr('id');
  console.log(rowId);

  if ($('tr.table-row-details[id="' + rowId + '"]').is(':visible')) {
		   		
    console.log('Case 1');
    $('tr.table-row-details[id="' + rowId + '"]').slideUp("slow");
    $(this).children("i.toggle-button").removeClass("fa fa-minus").addClass("fa fa-plus");
  }
  else {

    console.log('Case 3 : ' + rowId);
    $('tr.table-row-details').hide();
    $("i.toggle-button").removeClass("fa fa-minus").addClass("fa fa-plus");

    $('tr.table-row-details[id="' + rowId + '"]').slideDown("slow");
    $(this).children("i.toggle-button").removeClass("fa fa-plus").addClass("fa fa-minus");
  }
});
function combinations(arr, len) {
    let tempArry = []
    let final = []
    for (let i = 0; i < arr.length; i++) {
        console.log("i ", i)
        if ((arr.length - i) == (len - 1)) {
            break
        }
        tempArry.push(arr[i])
        for (let j = i + 1; j < arr.length; j++) {
            console.log("j ", j)
            tempArry.push(arr[j])
            console.log("tempArry ", tempArry)
            if (tempArry.length == len) {
                console.log("tempArry inside if ", tempArry)
                final.push([...tempArry])
                console.log("final inside if ", final)
                tempArry.pop()
            }
        }
        tempArry = []
    }
    console.log("final ", final)
    return final
}
combinations([1, 2, 3, 4, 5], 3)
function flatten(array) {
  var l = array.length;
  while (l--) {
    if (Array.isArray(array[l])) {
      flatten(array[l]);
      array.splice(l, 1, ...array[l]);
    }
  }
}


var array = [['1', '2', '3'], ['4', '5', ['6'], ['7', '8']]];

flatten(array);

console.log(array);
public delegate void Print(int val);

static void ConsolePrint(int i)
{
    Console.WriteLine(i);
}

static void Main(string[] args)
{           
    Print prnt = ConsolePrint;
    prnt(10);
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  (async () => {
    // async code goes here
    // ...
    const result = await getSomething();
    sendResponse(result);
  })();

  // Important! Return true to indicate you want to send a response asynchronously
  return true;
});

<input type="text" id="postcodeInput" placeholder="Enter your postcode" maxlength="6" required>
  
document.getElementById("postcodeInput").addEventListener("input", function(event) {
    this.value = this.value.replace(/[^0-9]/g, '');
}); 
var $= jQuery; $(document).on('found_variation', 'form.cart', function(event, variation) {
	//update price in custom box
    if (variation.price_html) {
      $('.custom-price-box .elementor-widget-container').html(variation.price_html);
    }
});
function testBrackets(input) {
    let bracketsObj = {
        '{':'}',
        '[':']',
        '(': ')'
    }
    let bracketKeys = Object.keys(bracketsObj)
    
    const stack = []
    for(str of input){
        if (bracketKeys.includes(str)){
            stack.push(str)
        } else if (bracketsObj[stack.pop()] !== str){
            return false
        }
    }
    
    return stack.length == 0
}
// change the account input element to "type=password" to hide the value
cy.get('#account-id').invoke('attr', 'type', 'password')
// now take the screenshot
cy.get('#account').screenshot('account', {
  overwrite: true,
})
const url ='http://sample.example.file.doc'
const authHeader ="Bearer 6Q************" 

const options = {
  headers: {
    Authorization: authHeader
  }
};
 fetch(url, options)
  .then( res => res.blob() )
  .then( blob => {
    var file = window.URL.createObjectURL(blob);
    window.location.assign(file);
  });
/**
 * 
 * 
 * This Google Script will delete everything in your Gmail account.
 * It removes email messages, filters, labels and reset all your settings
 * 
 * Written by Amit Agarwal (amit@labnol.org)
 

         88                                                           
         88                                                           
         88                                                           
 ,adPPYb,88 ,adPPYYba, 8b,dPPYba,   ,adPPYb,d8  ,adPPYba, 8b,dPPYba,  
a8"    `Y88 ""     `Y8 88P'   `"8a a8"    `Y88 a8P_____88 88P'   "Y8  
8b       88 ,adPPPPP88 88       88 8b       88 8PP""""""" 88          
"8a,   ,d88 88,    ,88 88       88 "8a,   ,d88 "8b,   ,aa 88          
 `"8bbdP"Y8 `"8bbdP"Y8 88       88  `"YbbdP"Y8  `"Ybbd8"' 88          
                                    aa,    ,88                        
                                     "Y8bbdP"                         
 
 
 * Proceed with great caution since the process is irreversible
 * 
 * This software comes with ABSOLUTELY NO WARRANTY. 
 * This is free software, and you are welcome to modify and redistribute it 
 *
 * This permission notice shall be included in all copies of the Software.
 *
 *
 */


/**
 * Remove all labels in Gmail
 */
const deleteGmailLabels_ = ()  => {
  GmailApp.getUserLabels().forEach((label) => {
    label.deleteLabel();
  });
};

/**
 * Remove all Gmail Filters
 */
const deleteGmailFilters_ = ()  => {
  const { filter: gmailFilters } = Gmail.Users.Settings.Filters.list('me');
  gmailFilters.forEach(({ id }) => {
    Gmail.Users.Settings.Filters.remove('me', id);
  });
};

/**
 * Remove all Gmail Draft messages
 */
const deleteGmailDrafts_ = ()  => {
  GmailApp.getDrafts().forEach((draft) => {
    draft.deleteDraft();
  });
};

/**
 * Reset Gmail Settings
 */
const resetGmailSettings_ = ()  => {
  // Disable Out-of-office
  Gmail.Users.Settings.updateVacation({ enableAutoReply: false }, 'me');

  // Delete Gmail Signatures
  const { sendAs } = Gmail.Users.Settings.SendAs.list('me');
  sendAs.forEach(({ sendAsEmail }) => {
    Gmail.Users.Settings.SendAs.update({ signature: '' }, 'me', sendAsEmail);
  });

  // Disable IMAP
  Gmail.Users.Settings.updateImap({ enabled: false }, 'me');

  // Disable POP
  Gmail.Users.Settings.updatePop({ accessWindow: 'disabled' }, 'me');

  // Disable Auto Forwarding
  const { forwardingAddresses } = Gmail.Users.Settings.ForwardingAddresses.list('me');
  forwardingAddresses.forEach(({ forwardingEmail }) => {
    Gmail.Users.Settings.ForwardingAddresses.remove('me', forwardingEmail);
  });
};

const startTime = Date.now();
const isTimeLeft_ = ()  => {
  const ONE_SECOND = 1000;
  const MAX_EXECUTION_TIME = ONE_SECOND * 60 * 5;
  return MAX_EXECUTION_TIME > Date.now() - startTime;
};

/**
 * Move all Gmail threads to trash folder
 */
const deleteGmailThreads_ = ()  => {
  let threads = [];
  do {
    threads = GmailApp.search('in:all', 0, 100);
    if (threads.length > 0) {
      GmailApp.moveThreadsToTrash(threads);
      Utilities.sleep(1000);
    }
  } while (threads.length && isTimeLeft_());
};

/**
 * Move all Spam email messages to the Gmail Recyle bin
 */
const deleteSpamEmails_ = ()  => {
  let threads = [];
  do {
    threads = GmailApp.getSpamThreads(0, 10);
    if (threads.length > 0) {
      GmailApp.moveThreadsToTrash(threads);
      Utilities.sleep(1000);
    }
  } while (threads.length && isTimeLeft_());
};

/**
 * Permanetly empty the Trash folder
 */
const emptyGmailTrash_ = ()  => {
  let threads = [];
  do {
    threads = GmailApp.getTrashThreads(0, 100);
    threads.forEach((thread) => {
      Gmail.Users.Threads.remove('me', thread.getId());
    });
  } while (threads.length && isTimeLeft_());
};

/**
 * Factory Reset your Gmail Account
 * Replace NO with YES and run this function
 * */
const factoryResetGmail = ()  => {
  const FACTORY_RESET = 'NO';
  if (FACTORY_RESET === 'YES') {
    resetGmailSettings_();
    deleteGmailLabels_();
    deleteGmailFilters_();
    deleteGmailDrafts_();
    deleteGmailThreads_();
    deleteSpamEmails_();
    emptyGmailTrash_();
  }
};

const http = require("http");

const html = `
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <form action="/submit-form" enctype="application/x-www-form-urlencoded" method="POST">
      <label> Enter Name: 
        <input type="text" autocomplete="name" name="name" required />
      </label>
      <input type="submit" />
    </form>
  </body>
</html>
`;
const server = http.createServer((req, res) => {
  switch (req.method) {
    case "GET":
      if (req.url === "/") {
        res.writeHead(200, { "Content-Type": "text/html" });
        res.end(html);
      } else {
        res.writeHead(404, { "Content-Type": "text/plain" });
        res.end("Page not found");
      }
      break;
    case "POST":
      if (req.url === "/submit-form") {
        let body = "";
        req.on("data", (data) => {
          body += data;
        });

        req.on("end", () => {
          console.log("Request body:  " + body);
          // Parse, validate, and sanitize
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ body }));
        });
      } else {
        res.writeHead(404, { "Content-Type": "text/plain" });
        res.end("Page not found");
      }
      break;
    default:
      res.writeHead(405, { "Content-Type": "text/plain" });
      res.end("Method not supported");
  }
});

const PORT = process.env.PORT || 3000;

server.listen(PORT, () => {
  console.log(`Your app is listening on PORT ${PORT}`);
});
<!DOCTYPE html>
<html lang="ja">
 <head>
    <script async src="https://xxxxx/liquidekyc.js"></script>
    <title>申込フォーム</title>
  </head>
  <body>
    <h1>新規申込</h1>
    <form id="applicant-form">
      <div>
        <label for="last_name">姓</label>
        <input type="text" id="last_name" name="last_name" />
      </div>
      <div>
        <label for="first_name">名</label>
        <input type="text" id="first_name" name="first_name" />
      </div>
      ・・・
    </form>
    <script>
     ・・・
      function handleSubmit(e) {
       ・・・
        const data = new FormData(applicantForm);
        const params = JSON.stringify(Object.fromEntries(data));
        LIQUIDEKYC.startKYC(params)
       ・・・
      }
    </script>
  </body>
</html>
@"C:\temp4\database\01_plano_execucao_GFF-261.sql";
function checkImagesSource() {
    const images = document.querySelectorAll('img');
    const viewportWidth = window.innerWidth;
    const viewportHeight = window.innerHeight;

    console.log(`Viewport dimensions: ${viewportWidth} x ${viewportHeight}`);
    console.log('Images displayed and their sources:');

    images.forEach((img, index) => {
        const rect = img.getBoundingClientRect();
        // Check if the image is within the viewport
        if (rect.top < viewportHeight && rect.bottom >= 0 && rect.left < viewportWidth && rect.right >= 0) {
            const isSrcset = img.hasAttribute('srcset');
            const sourceUsed = img.currentSrc || img.src;  // This will get the image URL after srcset and sizes have been applied by the browser

            if (isSrcset) {
                console.log(`${img.tagName.toLowerCase()} srcset - ${sourceUsed}`);
            } else {
                console.log(`${img.tagName.toLowerCase()} - ${sourceUsed}`);
            }
        }
    });
}

checkImagesSource();
// remove element at certain index without changing original
let arr = [0,1,2,3,4,5]
let newArr = [...arr]
newArr.splice(1,1)//remove 1 element from index 1
console.log(arr) // [0,1,2,3,4,5]
console.log(newArr)// [0,2,3,4,5]


// splice() method changes the original array. 
// slice() method doesn't change the original array.

eg //


const comments = [
      { text: 'Love this!', id: 523423 },
      { text: 'Super good', id: 823423 },
      { text: 'You are the best', id: 2039842 },
      { text: 'Ramen is my fav food ever', id: 123523 },
      { text: 'Nice Nice Nice!', id: 542328 }
    ];



// Array.prototype.findIndex()
// Find the comment with this ID
   const commentIndex = comments.findIndex((item) => item.id === 823423)
    // delete the comment with the ID of 823423
    const commentsCopy = [...comments];
    commentsCopy.splice(1, commentIndex) //remove 1 element from index 1
    console.log(commentsCopy)


// or we can use slice from the start to the value and from the value to the end
const newComments = [
  ...comments.slice(1, commentIndex)
  ...comments.slice(commentIndex++)
]




    
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Minecraft Block Path Finder</title>
  <style>
      .minecraft-block-path-finder-main {
    background: none;
    display: block;
    padding: 0px 0px 0px 0px;
    font: bold 17px/30px Arial, Helvetica, sans-serif;
    min-width: 260px;
    margin: 50px auto 0px auto;
    border: none;
  }

  .minecraft-block-path-finder-main:after {
    content: "";
    clear: both;
  }

  .noselect {
    cursor: default;
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }

  .minecraft-block-path-finder-card {
    padding: 1rem 2rem 1rem 2rem;
    height: 70px;
  }

  .minecraft-block-path-finder-cards {
    max-width: 1600px;
    margin: 0 auto;
    display: grid;
    grid-gap: 0 1rem;
    grid-template-columns: repeat(auto-fit, minmax(420px, 1fr));
  }

  .minecraft-block-path-finder-card00 {
    padding: 1rem 2rem 1rem 2rem;
    height: 70px;
  }

  
  
  .minecraft-block-path-finder-cards00 {
    width: 100%;
    margin: 0 auto;
    display: grid;
    grid-gap: 0 1rem;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  }

  .minecraft-block-path-finder-blocks {
    background: #24aded;
    background: -webkit-linear-gradient(to right, #24aded, #108dc7);
    background: linear-gradient(to right, #24aded, #108dc7);
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.2);
    border-radius: 2px;
    display: block;
    padding: 10px 10px 10px 10px;
    margin: 10px 0px;
    border: none;
    text-align: center;
    min-height: 50px;
  }

  .minecraft-block-path-finder-click-blocks {
    background: none;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.2);
    border-radius: 2px;
    display: block;
    padding: 10px 10px 10px 10px;
    margin: 10px 0px;
    border-width: 2px;
    border-style: solid;
    border-color: #108dc7;
    text-align: center;
    overflow-y: scroll;
    overflow-x: hidden;
    height: 250px;
    color: #108dc7;
    position: relative !important;
    -webkit-transition: all 0.6s ease;
    -moz-transition: all 0.6s ease;
    -ms-transition: all 0.6s ease;
    -o-transition: all 0.6s ease;
    transition: all 0.6s ease;
    -ms-overflow-style: none;
    scrollbar-width: none;
    margin-left: auto;
    margin-right: auto;
  }

  .minecraft-block-path-finder-click-blocks::-webkit-scrollbar {
    display: none;
  }

  .minecraft-block-path-finder-click-blocks:hover {
    background: #24aded;
    color: white;
    text-shadow: 0px 0px 8px rgb(255, 230, 186), 0px 0px 22px rgb(255, 255, 255),
      0px -1px 0px rgba(0, 0, 0, 0.5);
    -webkit-transition: all 0.6s ease;
    -moz-transition: all 0.6s ease;
    -ms-transition: all 0.6s ease;
    -o-transition: all 0.6s ease;
    transition: all 0.6s ease;
  }

  .minecraft-block-path-finder-cmnd-button {
    transition: color 0.15s ease-in;
    font-size: 35px;
    text-align: center;
    text-decoration: none;
    line-height: 50px;
    color: white;
    cursor: pointer;
  }

  .minecraft-block-path-finder-reset-button:hover {
    color: #8d8c85;
    transition: color 0.3s ease-in;
    transition: color 0.3s ease-out;
  }

  .stepper_select {
    display: none;
  }
  
  .tool-input input[type="number"] {
    width: calc(100% - 2px); 
    height: 25px;
    border: none;
    border-radius: 0;
    box-shadow: 0px 0px 20px 5px rgba(0, 0, 0, 0.05);
    background: #24aded;
    background: -webkit-linear-gradient(to right, #24aded, #108dc7);
    background: linear-gradient(to right, #24aded, #108dc7);
    text-align: center;
    color: #ffffff;
    font-size: 18px;
    line-height: 25px;
    outline: none;
}
  
.tool-input input[type="number"]::placeholder {
    color: #E6E6E6;
}


.tool-input input[type="number"]:focus {
    outline: none;
}

  .stepper-input {
    width: 100%;
    height: 25px;
    border: 0px;
    border-radius: 2px;
    box-shadow: 0px 0px 20px 5px rgba(0, 0, 0, 0.05);
    overflow: hidden;
    margin: 0px 0px 5px 0px;
  }

  .stepper-input input {
    display: none;
  }

  .stepper-input .input {
    width: 100%;
    height: 100%;
    display: flex;
  }

  .stepper-input .input :active {
    background: #24aded;
  }

  .stepper-input .input .range {
    overflow: hidden;
    text-align: center;
    flex: 1;
  }

  .stepper-input .input .range .list span {
    display: block;
    width: 100%;
    height: 25px;
    color: #ffffff;
    font-size: 18px;
    line-height: 25px;
  }

  .stepper_btn {
    background: #24aded;
    background: -webkit-linear-gradient(to right, #24aded, #108dc7);
    background: linear-gradient(to right, #24aded, #108dc7);
    height: 100%;
    border-radius: 2px;
    color: #ffffff;
    font-size: 12px;
    line-height: 25px;
    cursor: pointer;
    border: none;
    transition: all 300ms ease-in-out;
    flex: 0.2;
    text-align: center;
  }

  .stepper_btn:active {
    transform: translateY(1px);
  }

  .disabledivclick {
    pointer-events: none;
  }

  .table-fixed {
    width: 100%;
    caption-side: bottom;
  }

  .table-fixed tbody {
    display: block;
    height: 100%;
    overflow: auto;
    -ms-overflow-style: none;
    scrollbar-width: none;
  }

  .table-fixed tbody::-webkit-scrollbar {
    display: none;
  }

  .table-fixed thead,
  .table-fixed tbody tr {
    display: table;
    width: 100%;
  }

  .table-fixed td,
  th {
    text-align: center;
    vertical-align: middle;
    width: 33%;
  }

  .table-fixed caption {
    margin-top: 20px;
  }

  .divparenttable {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  #startlocations::before {
    content: "";
    position: absolute;
    width: 100%;
    height: 2px; 
    background-color: #108dc7; 
    z-index: 1;
    margin: -20px 0;
}
  #startlocations::after {
    content: "Start Location";
    position: absolute;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #24aded;
    padding: 0 10px; 
    z-index: 2;
    margin: -20px 0;
}
  #endlocations::before {
    content: "";
    position: absolute;
    width: 100%;
    height: 2px; 
    background-color: #108dc7; 
    z-index: 1;
    margin: -20px 0;
}
  #endlocations::after {
    content: "End Location";
    position: absolute;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #24aded;
    padding: 0 10px; 
    z-index: 2;
    margin: -20px 0;
}
	#startlocations,
#endlocations {
  position: relative;
}
  </style>
</head>
<body>
  <div class="minecraft-block-path-finder-main noselect">
    <div style="margin-top:30px; margin-bottom:10px;">
     
      <div id="startlocations" class="minecraft-block-path-finder-cards00">
        <div class="minecraft-block-path-finder-card00 minecraft-block-path-finder-blocks">
          <div style="font-size:22px; color : white;">
            <div class="tool-input">
              <input id="startX" type="number" oninput="CalcUpdateOutput()" placeholder="enter value">
            </div>
          </div>
          <div style="margin-top:-5px; color : white;">X-Coordinate</div>
        </div>
  
        <div class="minecraft-block-path-finder-card00 minecraft-block-path-finder-blocks">
          <div style="font-size:22px; color : white;">
  
            <div class="tool-input">
              <input id="startY" type="number" oninput="CalcUpdateOutput()" placeholder="enter value">
            </div>
  
          </div>
          <div style="margin-top:-5px; color : white;">Y-Coordinate</div>
        </div>
        <div class="minecraft-block-path-finder-card00 minecraft-block-path-finder-blocks">
          <div style="font-size:22px; color : white;">
  
            <div class="tool-input">
              <input id="startZ" type="number" oninput="CalcUpdateOutput()" placeholder="enter value">
            </div>
  
          </div>
          <div style="margin-top:-5px; color : white;">Z-Coordinate</div>
        </div>
      </div>
      <div id="endlocations" class="minecraft-block-path-finder-cards00" style="margin: 50px 0px 0px 0px;">
        <div class="minecraft-block-path-finder-card00 minecraft-block-path-finder-blocks">
          <div style="font-size:22px; color : white;">
            <div class="tool-input">
              <input id="endX" type="number" oninput="CalcUpdateOutput()" placeholder="enter value">
            </div>
          </div>
          <div style="margin-top:-5px; color : white;">X-Coordinate</div>
        </div>
  
        <div class="minecraft-block-path-finder-card00 minecraft-block-path-finder-blocks">
          <div style="font-size:22px; color : white;">
  
            <div class="tool-input">
              <input id="endY" type="number" oninput="CalcUpdateOutput()" placeholder="enter value">
            </div>
  
          </div>
          <div style="margin-top:-5px; color : white;">Y-Coordinate</div>
        </div>
        <div class="minecraft-block-path-finder-card00 minecraft-block-path-finder-blocks">
          <div style="font-size:22px; color : white;">
  
            <div class="tool-input">
              <input id="endZ" type="number" oninput="CalcUpdateOutput()" placeholder="enter value">
            </div>
  
          </div>
          <div style="margin-top:-5px; color : white;">Z-Coordinate</div>
        </div>
      </div>
      <div class="minecraft-block-path-finder-cards00">
        <div class="minecraft-block-path-finder-card00 minecraft-block-path-finder-blocks">
          <div style="font-size:22px; color : white;">
  
            <div class="tool-input">
              <input id="spacing" type="number" oninput="CalcUpdateOutput()" placeholder="enter value (set to 1 for solid walls/ramps)">
            </div>
  
          </div>
          <div style="margin-top:-5px; color : white;">Block Spacing</div>
        </div>
      </div>
    </div>
    <div id="calc-console" oncontextmenu="return false;" class="divparenttable minecraft-block-path-finder-click-blocks ">
    </div>
  </div>
  <script src="script.js">
  	    let startX = parseInt(document.getElementById("startX").value);
        let startY = parseInt(document.getElementById("startY").value);
        let startZ = parseInt(document.getElementById("startZ").value);
        let endX = parseInt(document.getElementById("endX").value);
        let endY = parseInt(document.getElementById("endY").value);
        let endZ = parseInt(document.getElementById("endZ").value);
        let spacing = parseInt(document.getElementById("spacing").value);

  let debounceTimer;

function debounce(func, delay) {
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(func, delay);
}

function CalcUpdateOutput() {
    debounce(() => {
        let startX = parseInt(document.getElementById("startX").value);
        let startY = parseInt(document.getElementById("startY").value);
        let startZ = parseInt(document.getElementById("startZ").value);
        let endX = parseInt(document.getElementById("endX").value);
        let endY = parseInt(document.getElementById("endY").value);
        let endZ = parseInt(document.getElementById("endZ").value);
        let spacing = parseInt(document.getElementById("spacing").value);

        let calcConsole = document.getElementById("calc-console");
        let blockPositions = '';
        let hasMessage = false;

        if (isNaN(startX) || isNaN(startY) || isNaN(startZ) || isNaN(endX) || isNaN(endY) || isNaN(endZ) || isNaN(spacing)) {
            blockPositions = "Please enter all coordinates and spacing.";
            hasMessage = true;
        } else if (spacing < 1) {
            blockPositions = "Block spacing must be at least 1.";
            hasMessage = true;
        } else {
            let dx = Math.abs(endX - startX);
            let dy = Math.abs(endY - startY);
            let dz = Math.abs(endZ - startZ);
            let maxLength = Math.max(dx, dy, dz);
            let currentStep = 0;

            function calculateNextBlock() {
                if (currentStep <= maxLength) {
                    let x = Math.round(startX + currentStep * (endX - startX) / maxLength);
                    let y = Math.round(startY + currentStep * (endY - startY) / maxLength);
                    let z = Math.round(startZ + currentStep * (endZ - startZ) / maxLength);
                    blockPositions += `#${currentStep / spacing + 1}: ${x}, ${y}, ${z}<br>`;
                    calcConsole.innerHTML = blockPositions;
                    currentStep += spacing;
                    setTimeout(calculateNextBlock, 0);
                }
            }

            calculateNextBlock();
        }

        if (hasMessage) {
            calcConsole.innerHTML = blockPositions;
            calcConsole.classList.add("divparenttable");
        } else {
            calcConsole.classList.remove("divparenttable");
        }
    }, 300);
}

document.addEventListener("DOMContentLoaded", function(event) { CalcUpdateOutput(); });        
  </script>
</body>
</html>
const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck', 'pogostick'];

    const transportation = data.reduce((total, item) => {

      if(!total[item]){
        total[item] = 0
      }

      total[item]++
      
      return total

    },{})

    console.log(transportation)


/** Dynamic property access (using []):
The square bracket [] syntax is commonly used to access properties of objects dynamically (i.e., using a variable as the property name). This allows you to compute property names at runtime.*/
 const people = [
      'Bernhard, Sandra', 'Bethea, Erin', 'Becker, Carl', 'Bentsen, Lloyd', 'Beckett, Samuel', 'Blake, William', 'Berger, Ric', 'Beddoes, Mick', 'Beethoven, Ludwig',
      'Belloc, Hilaire', 'Begin, Menachem', 'Bellow, Saul', 'Benchley, Robert', 'Blair, Robert', 'Benenson, Peter', 'Benjamin, Walter', 'Berlin, Irving',
      'Benn, Tony', 'Benson, Leana', 'Bent, Silas', 'Berle, Milton', 'Berry, Halle', 'Biko, Steve', 'Beck, Glenn', 'Bergman, Ingmar', 'Black, Elk', 'Berio, Luciano',
      'Berne, Eric', 'Berra, Yogi', 'Berry, Wendell', 'Bevan, Aneurin', 'Ben-Gurion, David', 'Bevel, Ken', 'Biden, Joseph', 'Bennington, Chester', 'Bierce, Ambrose',
      'Billings, Josh', 'Birrell, Augustine', 'Blair, Tony', 'Beecher, Henry', 'Biondo, Frank'
    ];




 let sortedPeople = [];

   for(person of people){
   const name = person.split(',').reverse().join(' ').trim();
   sortedPeople.push(name)
   }

   console.log(sortedPeople)
function removeTransition(e){
  const keys = [...document.querySelectorAll('.key')];
  keys.forEach((key) => key.addEventListener('transitionend', function(e){
    // console.log(e.propertyName)
    e.propertyName === 'transform' ? key.classList.remove('playing') : null;
  }))
}

// use the load listener
window.addEventListener('load', removeTransition)
// if something is true then execute the code on the left, otherwise return null
e.propertyName === 'transform' ? key.classList.remove('playing') : null;
<script type="text/javascript">
  document.addEventListener('DOMContentLoaded', function () {
    var link = document.getElementById('exit-intent-popup-trigger');


    function handleClick(e) {
      e.preventDefault();
    }


    link.addEventListener('click', handleClick);


    function triggerClick() {
      link.click();
      sessionStorage.setItem('eventTriggered', 'true');
    }

    // בדיקה האם המכשיר הוא נייד
    var isMobile = /Mobi|Android/i.test(navigator.userAgent);

    if (isMobile) {

      if (sessionStorage.getItem('eventTriggered') !== 'true') {
        setTimeout(triggerClick, 8000); 
      }
    } else {

      document.addEventListener('mousemove', function(e) {
        if (sessionStorage.getItem('eventTriggered') !== 'true') {
 
          if (e.clientY < 45) {
            triggerClick();
            document.removeEventListener('mousemove', arguments.callee);
            sessionStorage.setItem('eventTriggered', 'true');  
          }
        }
      });
    }
  });
</script>
const videoPlayers = document.getElementsByClassName('video-stream html5-main-video');
var videoPlayerss = videoPlayers[0]
var startTimes = 30
var endTimes = 68
var startTimes2 = 90
var endTimes2 = 150
var startTimes3 = 185
var endTimes3 = 270
videoPlayerss.currentTime = startTimes;
videoPlayerss.play();
videoPlayerss.addEventListener('timeupdate', () => {
  if (videoPlayerss.currentTime > endTimes && videoPlayerss.currentTime < startTimes2 ) {
    videoPlayerss.currentTime = startTimes2;
  } else if (videoPlayerss.currentTime > endTimes2 && videoPlayerss.currentTime < startTimes3 ) {
    videoPlayerss.currentTime = startTimes3;
  } else if (videoPlayerss.currentTime > endTimes3) {
    videoPlayerss.currentTime = startTimes;
  } 
});
var elementss2 = document.getElementsByClassName("ud-real-toggle-input");
//console.log(elementss2)
for (var i = 0; i < elementss2.length; i++) {
  if (!elementss2[i].hasAttribute("checked")) {
    console.log(elementss2[i]);
      elementss2[i].disabled = false;
      elementss2[i].click()
  }
}
var elementss2 = document.getElementsByClassName("contents");
//console.log(elementss2)
for (var i = 0; i < elementss2.length; i++) {
 elementss2[i].style = "display: none;";  
}
import $ from 'jquery';

class Header {
	constructor(element) {
		this.$element = $(element);
		this.$burger = this.$element.find('.header__burger');
		this.$Nav = this.$element.find('.nav-main');
		this.$hasSub = this.$element.find('.menu-item-has-children');
		this.$menuArrow = this.$element.find('.dropdown-arv-cont');
		this.$menuBg = this.$element.find('.header__menu-bg');
		this.init();
	}

	// headerPadding() {
	// 	if (!this.$element.hasClass('header--transperant')) {
	// 		let hHeight = this.$element.height();
	// 		$('.main-wrapper').css({ 'padding-top': hHeight });
	// 	}
	// }

	init() {
		// $(document).ready(() => {
		// 	this.headerPadding();
		// });

		$(window).on('resize load', () => {
			this.$element.addClass('loaded');
		});

		$(window).on('scroll', () => {
			if ($(window).scrollTop() > 100) {
				$('.header').addClass('sticky');
			} else {
				$('.header').removeClass('sticky');
			}
		});

		$(document).on(
			'click',
			'.menu-item-has-children .dropdown-arv-cont',
			function () {
				$(this).closest('li').toggleClass('active');
			},
		);

		this.$burger.on('click', (e) => {
			e.preventDefault();
			if ($(e.currentTarget).hasClass('opened')) {
				$(e.currentTarget).removeClass('opened').attr('aria-expanded', 'false');
				this.$Nav.slideUp(300).parent().removeClass('active');
				$('.menu-item-has-children .dropdown-arv-cont').removeClass('active');
				$('body').css('overflow-y', 'visible');
				$('.dropdown-arv-cont')
					.closest('li')
					.children('.sub-menu')
					.removeClass('active');
			} else {
				$(e.currentTarget).addClass('opened').attr('aria-expanded', 'true');
				this.$Nav.slideDown(300).parent().toggleClass('active');
				$('body').css('overflow-y', 'hidden');
			}
		});

		this.$menuBg.on('click', (e) => {
			e.preventDefault();
			this.$burger.removeClass('opened').attr('aria-expanded', 'false');
			this.$Nav.slideUp(300).parent().removeClass('active');
		});

		$(document).on('click', '.dropdown-arv-cont', function (e) {
			e.preventDefault();
			if ($(this).hasClass('active')) {
				$(this).removeClass('active');
				$(this).closest('li').children('.sub-menu').removeClass('active');
			} else {
				$(this).addClass('active');
				$(this).closest('li').children('.sub-menu').addClass('active');
			}
		});
	}
}

$('[data-header]').each((index, element) => new Header(element));
var contentSlider = $('.blog-slider__cont');
		var imageSlider = $('.blog-slider__slider');

		contentSlider.owlCarousel({
			items: 1,
			loop: true,
			dots: false,
			nav: false,
			mouseDrag: false,
			touchDrag: false,
		});

		imageSlider.owlCarousel({
			loop: true,
			dots: true,
			nav: false,
			items: 1,
			margin: 30,
			responsive: {
				320: {
					items: 1,
				},
				576: {
					items: 2,
				},
			},
		});

		imageSlider.on('changed.owl.carousel', function (event) {
			var currentIndex = event.relatedTarget.relative(event.item.index);
			contentSlider.trigger('to.owl.carousel', [currentIndex]);
		});
//Without payload
export const moveRight = () => ({
	type: MOVE_RIGHT
});

//With payload
export const moveRight = (data: string) => ({
	type: MOVE_RIGHT,
	payload: data
});
function* performAction() {
    yield put({
        type: COPY_DATA,
        payload: "Hello"
    });
}
// postcss.config.js
const { join } = require('path');

module.exports = {
  plugins: {
    tailwindcss: {
      config: join(__dirname, 'tailwind.config.js'),
    },
    autoprefixer: {},
  },
};
var xmlResponse = '<?xml version="1.0" encoding="UTF-8"?> <data code="0" name="piece-shipment-list" request-id="f1fc982b-fd81-4b63-92ae-eb60d1dd9262"> <data airway-bill-number="" delivery-event-flag="1" dest-country="DE" division="DPEED" domestic-id="" error-status="0" event-country="DE" event-location="" ice="DLVRD" identifier-type="2" international-flag="0" leitcode="" matchcode="" name="piece-shipment" order-preferred-delivery-day="false" origin-country="DE" pan-recipient-address="Heinrich-Brüning-Str. 7 53113 Bonn" pan-recipient-city="53113 Bonn" pan-recipient-name="Deutsche Post DHL" pan-recipient-postalcode="53113" pan-recipient-street="Heinrich-Brüning-Str. 7" piece-code="00340434161094022115" piece-customer-reference="" piece-id="8e464a3e-219a-459b-823b-07d9d92732e3" piece-identifier="340434161094022115" product-code="00" product-key="" product-name="DHL PAKET (parcel)" pslz-nr="5066934803" recipient-city="53113 Bonn" recipient-id="5" recipient-id-text="different person present" recipient-name="Kraemer" recipient-street="Heinrich-Brüning-Str. 7" ric="OTHER" routing-code-ean="" ruecksendung="false" searched-piece-code="00340434161094022115" searched-ref-no="" shipment-code="" shipment-customer-reference="" shipment-height="0.0" shipment-length="0.0" shipment-weight="0.0" shipment-width="0.0" shipper-address="" shipper-city="" shipper-name="No sender data has been transferred to DHL." shipper-street="" short-status="Delivery successful" standard-event-code="ZU" status="The shipment has been successfully delivered" status-liste="0" status-timestamp="18.03.2016 10:02" upu=""> <data _build-time="2017-01-14 19:56:42.000775" leitcode="5311304400700" name="piece-event-list" order-preferred-delivery-day="false" piece-id="8e464a3e-219a-459b-823b-07d9d92732e3" piece-identifier="340434161094022115" pslz-nr="5066934803" routing-code-ean="" ruecksendung="false"> <data event-country="Germany" event-location="Bremen" event-short-status="Posting at PACKSTATION" event-status="The shipment has been posted by the sender at the PACKSTATION" event-text="The shipment has been posted by the sender at the PACKSTATION" event-timestamp="17.03.2016 11:43" ice="SHRCU" name="piece-event" ric="PCKST" ruecksendung="false" standard-event-code="ES" /> <data event-country="Germany" event-location="Bremen" event-short-status="Transportation to parcel center of origin" event-status="The shipment has been taken from the PACKSTATION for onward transportation" event-text="The shipment has been taken from the PACKSTATION for onward transportation" event-timestamp="17.03.2016 13:53" ice="LDTMV" name="piece-event" ric="MVMTV" ruecksendung="false" standard-event-code="AA" /> <data event-country="Germany" event-location="" event-short-status="Pick-up successful" event-status="The shipment has been picked up" event-text="The shipment has been picked up" event-timestamp="17.03.2016 13:55" ice="PCKDU" name="piece-event" ric="PUBCR" ruecksendung="false" standard-event-code="AE" /> <data event-country="Germany" event-location="Bremen" event-short-status="Parcel center of origin" event-status="The shipment has been processed in the parcel center of origin" event-text="The shipment has been processed in the parcel center of origin" event-timestamp="17.03.2016 15:49" ice="LDTMV" name="piece-event" ric="MVMTV" ruecksendung="false" standard-event-code="AA" /> <data event-country="Germany" event-location="Neuwied" event-short-status="Destination parcel center" event-status="The shipment has been processed in the destination parcel center" event-text="The shipment has been processed in the destination parcel center" event-timestamp="18.03.2016 03:35" ice="ULFMV" name="piece-event" ric="UNLDD" ruecksendung="false" standard-event-code="EE" /> <data event-country="" event-location="" event-short-status="In delivery" event-status="The shipment has been loaded onto the delivery vehicle" event-text="The shipment has been loaded onto the delivery vehicle" event-timestamp="18.03.2016 09:00" ice="SRTED" name="piece-event" ric="NRQRD" ruecksendung="false" standard-event-code="PO" /> <data event-country="Germany" event-location="Bonn" event-short-status="Delivery successful" event-status="The shipment has been successfully delivered" event-text="The shipment has been successfully delivered" event-timestamp="18.03.2016 10:02" ice="DLVRD" name="piece-event" ric="OTHER" ruecksendung="false" standard-event-code="ZU" /> </data> </data> </data>';

// Parse the XML response
var parser = new XMLDocument2();
parser.parseXML(xmlResponse);

// Get the value of the "short-status" attribute from the <data> element
var shortStatus = parser.getNode('/data/data').getAttribute('short-status');;

// Print the value of the "short-status" attribute
gs.info("Short Status: " + shortStatus);
const str = 'abcab';

const freq = (str) => 
    str.split('').reduce((obj, char) => {
        obj[char] = (obj[char] || 0) + 1;
        return obj;
    }, {})

console.log(freq('zCu3zezCaX'));
function getDirection() {

  

  // DECLARE SHEET

  var ss = SpreadsheetApp.getActiveSpreadsheet();

  var mapSheet = ss.getSheetByName("MAP");

  

  var start = mapSheet.getRange('B1').getValue();

  var end = mapSheet.getRange('B2').getValue();

  

  var directions = Maps.newDirectionFinder()

    .setOrigin(start)

    .setDestination(end)

    .setMode(Maps.DirectionFinder.Mode.DRIVING)

    .getDirections();

  

  //Logger.log(directions.routes[0].legs[0].duration.text);

 

  //CLEAR QUESTION AND ANSWER

  mapSheet.getRange('A6:D500').clear();

  

  //NEXT ROW ON MAP SHEET

  var nextRow = mapSheet.getLastRow() + 1;

 

  for (var i = 0; i < directions.routes[0].legs.length; i++) 

  {

    var endAddress = directions.routes[0].legs[i].end_address;

    var startAddress = directions.routes[0].legs[i].start_address;

    var distance = directions.routes[0].legs[i].distance.text;

    var duration = directions.routes[0].legs[i].duration.text;

    

    mapSheet.getRange(nextRow,1).setValue(startAddress);

    mapSheet.getRange(nextRow,2).setValue(endAddress);

    mapSheet.getRange(nextRow,3).setValue(distance);

    mapSheet.getRange(nextRow,4).setValue(duration);

    

    nextRow++;

 

  }

}
/*!
 * Color mode toggler for Bootstrap's docs (https://getbootstrap.com/)
 * Copyright 2011-2023 The Bootstrap Authors
 * Licensed under the Creative Commons Attribution 3.0 Unported License.
 */
 
(() => {
  'use strict';
 
  const storedTheme = localStorage.getItem('theme');
 
  const getPreferredTheme = () => {
    if (storedTheme) {
      return storedTheme;
    }
 
    return window.matchMedia('(prefers-color-scheme: dark)').matches
      ? 'dark'
      : 'light';
  };
 
  const setTheme = function (theme) {
    if (
      theme === 'auto' &&
      window.matchMedia('(prefers-color-scheme: dark)').matches
    ) {
      document.documentElement.setAttribute('data-bs-theme', 'dark');
    } else {
      document.documentElement.setAttribute('data-bs-theme', theme);
    }
  };
 
  setTheme(getPreferredTheme());
 
  const showActiveTheme = (theme, focus = false) => {
    const themeSwitcher = document.querySelector('#bd-theme');
 
    if (!themeSwitcher) {
      return;
    }
 
    const themeSwitcherText = document.querySelector('#bd-theme-text');
    const activeThemeIcon = document.querySelector('.theme-icon-active use');
    const btnToActive = document.querySelector(
      `[data-bs-theme-value="${theme}"]`
    );
    const svgOfActiveBtn = btnToActive
      .querySelector('svg use')
      .getAttribute('href');
 
    document.querySelectorAll('[data-bs-theme-value]').forEach((element) => {
      element.classList.remove('active');
      element.setAttribute('aria-pressed', 'false');
    });
 
    btnToActive.classList.add('active');
    btnToActive.setAttribute('aria-pressed', 'true');
    activeThemeIcon.setAttribute('href', svgOfActiveBtn);
    const themeSwitcherLabel = `${themeSwitcherText.textContent} (${btnToActive.dataset.bsThemeValue})`;
    themeSwitcher.setAttribute('aria-label', themeSwitcherLabel);
 
    if (focus) {
      themeSwitcher.focus();
    }
  };
 
  window
    .matchMedia('(prefers-color-scheme: dark)')
    .addEventListener('change', () => {
      if (storedTheme !== 'light' || storedTheme !== 'dark') {
        setTheme(getPreferredTheme());
      }
    });
 
  window.addEventListener('DOMContentLoaded', () => {
    showActiveTheme(getPreferredTheme());
 
    document.querySelectorAll('[data-bs-theme-value]').forEach((toggle) => {
      toggle.addEventListener('click', () => {
        const theme = toggle.getAttribute('data-bs-theme-value');
        localStorage.setItem('theme', theme);
        setTheme(theme);
        showActiveTheme(theme, true);
      });
    });
  });
})();
<p>Copyright &copy; <script>document.write(new Date().getFullYear())</script> Your Name All Rights Reserved</p>
@page
@model WebUI.Pages.Shared.ServitörVyModel

@{
    var swedishTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
    var nowSwedishTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, swedishTimeZone);
}

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Välj Bord</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="css/StyleFoodMenu.css" asp-append-version="true">

    <style>
        .table-button {
            width: 100%;
            margin-bottom: 20px;
            height: 60px;
        }

        .iframe-container {
            width: 100%;
            border: none;
            height: 400px;
        }
    </style>
</head>

<div class="container" style="display:flex; flex-direction:column;" >

    <button class="btn btn-warning" id="offcanvasbutton" style=" color:black;" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasBottom" aria-controls="offcanvasBottom">Toggle bottom offcanvas</button>

    <div id="accordion">
        <div class="card">
            
                    <button class="btn btn-warning" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
                        Välj bord
                    </button>
             
            <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion">
                <div class="card-body">
                    Välj bord

                    <select id="tableSelect" class="form-control">
                        @foreach (var table in Model.TablesProp)
                        {
                            <option value="@table.Number">@table.Number</option>
                        }
                    </select>

                    <button class="btn btn-success" id="confirmButton">Bekräfta </button>
                </div>
            </div>
        </div>
        <div class="card">

            <button class="btn btn-warning collapsed" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
              Beställning
            </button>

            <div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordion">
                <div class="card-body">
                    <button class="btn btn-success" id="orderButton">Ny Beställning </button>
                </div>
            </div>
        </div>
        <div class="card">
           
                    <button class="btn btn-warning collapsed" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
                        Välj maträtt
                    </button>
                
            <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordion">
                <div class="card-body">
                    <div class="row special-list">
                        @if (Model.Foods != null)
                        {
                            foreach (var food in Model.Foods)
                            {
                                if ((food.PublishDate == null || food.PublishDate <= nowSwedishTime) &&
                                (food.RemoveDate == null || food.RemoveDate > nowSwedishTime))
                                {
                                    <div class="col-lg-4 col-md-6 special-grid menu-card" data-food-id="@food.Id"
                                         data-food-title="@food.Title" data-food-description="@food.Description"
                                         data-food-price="@food.Price" data-food-category="@food.Category"
                                         data-food-ingredients="@food.Ingredients">
                                        <div class="gallery-single fix">
                                            @if (!string.IsNullOrEmpty(food.ImagePath))
                                            {
                                                <img src="@Url.Content($"~/{food.ImagePath}")" class="img-fluid" alt="Bild av @food.Title">
                                            }
                                            <div class="why-text">
                                                @if (User.IsInRole("Admin") || User.IsInRole("Owner"))
                                                {
                                                    <div class="options-menu" style="display:none;">
                                                    </div>
                                                }
                                                <h4>@food.Title</h4>

                                                <button class="button btn-success add-to-cart" id="addtocart" data-food-id="@food.Id">Lägg till</button>
                                                <h5>@food.Price kr</h5>
                                            </div>
                                        </div>
                                    </div>
                                }
                            }
                        }
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<title>Offcanvas Button Example</title>
<!-- Include Bootstrap CSS -->

<div class="offcanvas offcanvas-bottom" tabindex="-1" id="offcanvasBottom" aria-labelledby="offcanvasBottomLabel">
    <div class="offcanvas-header">
        <h5 class="offcanvas-title" id="offcanvasBottomLabel">Offcanvas bottom</h5>
        <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
    </div>
    <div class="offcanvas-body small" id="ordersContainer">
        
    </div>

    

</div>

<button class="btn-btn btn-success" id="confirmorder"> Bekräfta beställning </button>

<!-- Include Bootstrap JavaScript (popper.js and bootstrap.js are also required) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.11.6/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/5.3.0/js/bootstrap.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script>
    document.getElementById('confirmButton').addEventListener('click', function () {
        // Get the selected table number
        var selectedTableNumber = document.getElementById('tableSelect').value;

        // Do something with the selected table number
        console.log('Selected table number:', selectedTableNumber);

        // You can perform further actions here, such as sending the selected table number to the server
        // using AJAX or submitting a form.
    });

    let orderId;
    let guest;
    let waiter;
    let date;
    let receit
    let status
    let table;


         //POST Order
        document.getElementById('orderButton').addEventListener('click', function () {
            // Prepare the order data

        const currentDate = new Date();
            const orderData = {
             table:document.getElementById('tableSelect').value
            };
            
            // Send the order data to the server using Fetch API
            fetch('/api/Order/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(orderData)
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    // Handle the response data if needed
                    console.log('Order created successfully:', data);
                    console.log('Order Id: ', data.id)
                    console.log('Order Guest: ', data.guest)
                    console.log('Order Table: ', data.table )
                    console.log('Order WaiterId: ', data.waiterId)
                    console.log('Order Date: ', data.date)
                    console.log('Order ReceitId: ', data.receitId)
                    console.log('Order Status: ', data.status)

                    date = order.date;
                    orderId = data.id;
                    guest = data.guest;
                    table = data.table;
                    waiter = data.waiterId;
                    receit = data.receitId;
                    status = data.status;

                    // You can redirect or show a success message here
                })
                .catch(error => {
                    console.error('There was a problem with your fetch operation:', error);
                    // Handle errors appropriately, e.g., show an error message to the user
                });
        });

    //POST OrderItem
    document.querySelectorAll('.add-to-cart').forEach(item => {
        item.addEventListener('click', function () {
            var foodId = $(this).data('food-id');
            var data = {
                FoodId: foodId,
                Quantity: 1,
                OrderId: orderId
            };

            fetch('/api/OrderItem/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    // Handle success
                    console.log('Success:', data);
                })
                .catch(error => {
                    // Handle error
                    console.error('Error:', error);
                });
        });
    });


    //GET OrderItems
    function fetchOrders() {
        fetch(`/api/OrderItem/?columnName=orderid&columnValue=${orderId}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                // Work with the JSON data retrieved from the endpoint
                const ordersContainer = document.getElementById('ordersContainer');

                // Clear existing content
                ordersContainer.innerHTML = '';

                // Iterate over the data and append to the container
                data.forEach(order => {
                    const orderElement = document.createElement('div');
                    orderElement.textContent = `Quantity: ${order.quantity} FoodId:${order.foodId}, OrderId: ${order.orderId}`;
                    ordersContainer.appendChild(orderElement);
                });
            })
            console.log()
            .catch(error => {
                console.error('There was a problem with the fetch operation:', error);
            });
    }



    document.getElementById('confirmorder').addEventListener('click', function () {


        const itemIdToUpdate = orderId; // Example item ID to update
        const updatedData = {
            id : orderId,
            guest : guest,
            table : table,
            waiterId : waiter,
            date : date,
            receitId : receit,
            confirmed : true,
            status : status
            // Example updated data for the item
            
            // Add other fields as needed
        };

        // Construct the URL targeting the specific item
        const url = `/api/Order/${itemIdToUpdate}`;

        // Prepare the request object
        const requestOptions = {
            method: 'PUT', // or 'PATCH' depending on the server's API
            headers: {
                'Content-Type': 'application/json', // Specify content type as JSON
                // Add any other headers if required
            },
            body: JSON.stringify(updatedData), // Convert data to JSON format
        };

        // Send the request
        fetch(url, requestOptions)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json(); // Parse response JSON if needed
            })
            .then(data => {
                // Handle successful response (if required)
                console.log('Item updated successfully:', data);
            })
            .catch(error => {
                // Handle errors
                console.error('There was a problem updating the item:', error);
            });

        

    });

    // Attach an event listener to the button
    const refreshButton = document.getElementById('addtocart');
    refreshButton.addEventListener('click', fetchOrders);
    const refreshButton2 = document.getElementById('offcanvasbutton');
    refreshButton2.addEventListener('click', fetchOrders);
</script>




function test({ a = "foo", b = "bar", c = "baz" } = {}) {
  console.log(a + b + c);
}

test({c: "blub"});	// foobarblub
javascript: (function () {
  if (
    location.host.includes("youtube.com") &&
    (location.pathname.startsWith("/channel") ||
      location.pathname.startsWith("/@"))
  ) {
    const feed = document
      .querySelector("link[title='RSS']")
      .getAttribute("href");
    if (feed.includes(".xml")) {
      let toClip = prompt("copy to clipboard", feed);
      navigator.clipboard.writeText(toClip);
    } else {
      window.alert("failed");
    }
  } else {
    window.alert("current page isn't YouTube Channel");
  }
})();
sizeguide/script/release-theme walmart 

script/release sizeguide
export function TailwindIndicator() {
  if (process.env.NODE_ENV === "production") return null

  return (
    <div className="fixed bottom-1 left-1 z-50 flex h-6 w-6 items-center justify-center rounded-full bg-gray-800 p-3 font-mono text-xs text-white">
      <div className="block sm:hidden">xs</div>
      <div className="hidden sm:block md:hidden">sm</div>
      <div className="hidden md:block lg:hidden">md</div>
      <div className="hidden lg:block xl:hidden">lg</div>
      <div className="hidden xl:block 2xl:hidden">xl</div>
      <div className="hidden 2xl:block">2xl</div>
    </div>
  )
}
const tweetId = location.pathname.match(/status\/([0-9]+)/)[1];
const imgElements = document.querySelectorAll(`a[href*="${tweetId}"] img`);
let imgArray = new Array();
for (const imgElement of imgElements) {
  let imgSrc = imgElement
    .getAttribute("src")
    .replace(/\?format=/, ".")
    .replace(/&.+/, "");
  imgArray.push(imgSrc);
}
var links = document.links;
for (let i = 0, linksLength = links.length ; i < linksLength ; i++) {
  if (links[i].hostname !== window.location.hostname) {
    links[i].target = '_blank';
    links[i].rel = 'noreferrer noopener';
  }
}             
javascript: (function () {
  const query = prompt("Search App Store", document.getSelection().toString());
  if (query) {
    window.open(
      `itms-apps://search.itunes.apple.com/WebObjects/MZSearch.woa/wa/search?media=software&term=${encodeURIComponent(query)}`,
    );
  }
})();
const genDTO = (className, id) => {
  var fields = [
    'package com.voltcash.integrations.opencp.common.dto; ',
    '\n',
    'import com.voltcash.integrations.common.dto.BaseJsonEntity; ',
    'import lombok.Data;',
     '\n',
    '@Data ',
    'public class '+ className +' extends BaseJsonEntity{ ' 
  ];
 var declarations = $('#' + id).parentNode.querySelectorAll('td:first-child strong').forEach(e => fields.push('private String ' + e.innerHTML + ';'));
  
  fields.push('}');
  
  console.log(fields.join('\n'));
}
/*** +page.svelte **/

<script>
	import { onMount } from 'svelte';
	
	let Thing;
	
	const sleep = ms => new Promise(f => setTimeout(f, ms));
	
	onMount(async () => {
		await sleep(1000); // simulate network delay
		Thing = (await import('./Thing.svelte')).default;
	});
</script>

<svelte:component this={Thing} answer={42}>
	<p>some slotted content</p>
</svelte:component>



/*** Thing.svelte ***/

<script>
	export let answer;
</script>

<p>the answer is {answer}</p>
<slot></slot>

/* +page.svelte **/

<script>
    import Component2 from "./Component2.svelte";
    
    function abc() {
    	const element = new Component2({
    		target: document.querySelector('#abc')
    	})
    }
</script>

<div id="abc" use:abc>dsaads</div>

/* Component2.svelte **/

<script>
  export let params;
</script>
<div>
	<table>
		<tr>
			<td>dsadasads</td>
		</tr>
	</table>
</div>
/* +page.svelte **/

<script>
    import Component2 from "./Component2.svelte";
    
    function abc() {
    	const element = new Component2({
    		target: document.querySelector('#abc')
    	})
    }
</script>

<div id="abc" use:abc>dsaads</div>

/* Component2.svelte **/

<script>
  export let params;
</script>
<div>
	<table>
		<tr>
			<td>dsadasads</td>
		</tr>
	</table>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

   <script>
        function createChart(data) {
            const ctx = document.getElementById('myChart');
            new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: data.labels,
                    datasets: [{
                        label: data.label,
                        data: data.data1,
                       backgroundColor: '#003f5c ',
                        borderWidth: 2
                    },
                          {
                        label: '# of Views',
                        data: data.data2,
                       backgroundColor: '#ff6e54 ',
                        borderWidth: 3
                    }    
                              
                              ]
                },
                options: {
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }
    </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#nama_suami").autocomplete({
                source: function(request, response) {
                    $.ajax({
                        url: "fetch_nama_lengkap.php",
                        type: "POST",
                        dataType: "json",
                        data: {
                            term: request.term
                        },
                        success: function(data) {
                            response(data);
                        }
                    });
                },
                minLength: 2 // Jumlah minimum karakter sebelum autocomplete mulai
            });
        });
    </script>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Staff</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="adminer.css" />

<script>
        $(document).ready(function() {
            $("#nama_suami").autocomplete({
                source: function(request, response) {
                    $.ajax({
                        url: "fetch_nama_lelaki.php",
                        type: "POST",
                        dataType: "json",
                        data: {
                            term: request.term
                        },
                        success: function(data) {
                            response(data);
                        }
                    });
                },
                minLength: 2, // Jumlah minimum karakter sebelum autocomplete mulai
                select: function(event, ui) {
                    $("#nama_suami").val(ui.item.value);
                    $.ajax({
                        url: "fetch_id_number.php",
                        type: "POST",
                        dataType: "json",
                        data: {
                            nama_lengkap: ui.item.value
                        },
                        success: function(data) {
                            $("#id_suami").val(data.id_number);
                        }
                    });
                    return false;
                }
            });
        });
    </script>
console.log('Hi')

const func = () => {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log('2nd Hi')
            resolve();
        }, 2000)
    })
}

(async () => {
    await func();
    console.log('3rd Hi');
})();
<!--HTML Code-->
  
  <form id="contact_form" method="post">
    <div class="row">
        <div class="col-md-12 form-group g-mb-20">
            <input type="text" class="form-control" id="txtContactName" name="txtContactName" placeholder="Full Name" tabindex="201" required>
            <div class="error-message" id="txtContactName-error"></div>
        </div>

        <div class="col-md-12 form-group g-mb-20">
            <input type="email" class="form-control" id="txtContactEmail" name="txtContactEmail" placeholder="Email Address" tabindex="202" required>
            <div class="error-message" id="txtContactEmail-error"></div>
        </div>

        <div class="col-md-12 form-group g-mb-20">
            <input type="text" class="form-control" id="txtContactPhone" name="txtContactPhone" placeholder="Contact Number" maxlength="10" tabindex="203" required>
            <div class="error-message" id="txtContactPhone-error"></div>
        </div> 

        <div class="col-md-12 form-group g-mb-40">
            <textarea class="form-control" id="txtContactMessage" name="txtContactMessage" rows="7" placeholder="Message" maxlength="160" tabindex="204" required></textarea>
            <div class="error-message" id="txtContactMessage-error"></div>
        </div>
    </div>
    <input type="submit" class="btn btn-lg u-btn-primary g-font-weight-600 g-font-size-default rounded-0 text-uppercase g-py-15 g-px-30" id="btnContactSubmit" name="btnContactSubmit" value="SUBMIT">
</form>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js"></script>
<script>
	
</script>
<script>
    $(document).ready(function() {
        $('#contact_form').validate({
            rules: {
                txtContactName: "required",
                txtContactEmail: {
                    required: true,
                    email: true
                },
                txtContactPhone: {
                    required: true,
                    digits: true,
                    maxlength: 10
                },
                txtContactMessage: "required"
            },
            messages: {
                txtContactName: "Please enter your full name",
                txtContactEmail: {
                    required: "Please enter your email address",
                    email: "Please enter a valid email address"
                },
                txtContactPhone: {
                    required: "Please enter your contact number",
                    digits: "Please enter only digits",
                    maxlength: "Please enter a valid 10-digit phone number"
                },
                txtContactMessage: "Please enter your message"
            },
            errorPlacement: function(error, element) {
                error.appendTo(element.closest('.form-group').find('.error-message'));
            },
            submitHandler: function(form) {
                var formData = $(form).serialize();
                $.ajax({
                    type: 'POST',
                    url: 'mail.php',
                    data: formData,
                    success: function(response) {
                        $('#contact_form').append('<div class="success-message" style="color: green;">Message sent successfully!</div>');
                        setTimeout(function() {
                            $('#contact_form')[0].reset();
                        }, 4000);
                    },
                    error: function(xhr, status, error) {
                        console.error(xhr.responseText);
                        alert('Error: ' + xhr.responseText);
                    }
                });
            }
        });
    });
</script>

PHP Miler folder should be there
Create folder name with mail.php and add below code there 
<?php
// Include PHPMailer autoload file

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Load Composer's autoloader
require 'phpmailer/vendor/autoload.php';

// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve form data
    $name = $_POST['txtContactName'];
    $email = $_POST['txtContactEmail'];
    $phone = $_POST['txtContactPhone'];
    $message = $_POST['txtContactMessage'];

    // Initialize PHPMailer
    $mail = new PHPMailer(true);
    try {
        // SMTP settings
		$mail->IsSMTP();        // Sets Mailer to send message using SMTP
		$mail->SMTPAuth = true; // Authentication enabled
		$mail->SMTPSecure = 'tls'; // Secure transfer enabled REQUIRED for Gmail
		$mail->Host = 'smtp-relay.brevo.com';
		$mail->Port = 587;
		$mail->Username = 'advanceindiaprojectltd@gmail.com';
		$mail->Password = 'xsmtpsib-e66045ab99d2f28608d548ca33a5a3ac8cc14a6896d682cbdc5418c80154b5eb-6B5QJOyT18GvbzmZ';
		$mail->SMTPOptions = array(
			'ssl' => array(
				'verify_peer' => false,
				'verify_peer_name' => false,
				'allow_self_signed' => true
			)
		);

        // Recipients
        $mail->setFrom($email, $name);
        $mail->addAddress('roshan@teamvariance.com'); // Add recipient email address

        // Content
        $mail->isHTML(true);
        $mail->Subject = 'Contact Form Submission';
		// Construct HTML table for the email body
        $message = '
            <h3 align="center">Details</h3>
            <table border="1" width="100%" cellpadding="5" cellspacing="5">
                <tr>
                    <td width="30%">Name</td>
                    <td width="70%">' . $name . '</td>
                </tr> 
                <tr>
                    <td width="30%">Email</td>
                    <td width="70%">' . $email . '</td>
                </tr>
                <tr>
                    <td width="30%">Phone</td>
                    <td width="70%">' . $phone . '</td>
                </tr>
                <tr>
                    <td width="30%">Message</td>
                    <td width="70%">' . $message . '</td>
                </tr>
            </table>
        ';
        $mail->Body = $message;

        // Send email
        $mail->send();
        
        // Return success message
        echo "success";
    } catch (Exception $e) {
        // Return error message
        echo "error";
    }
}
?>



  var newStafflist = [];
  for (var i = 0; i < staffdata.length; i++) {
    var department = staffdata[i][4];
    if (depData.flat().includes(department) && department !== "") {
      newStafflist.push([staffdata[i][2], staffdata[i][3], staffdata[i][4], staffdata[i][5], staffdata[i][8], staffdata[i][9], staffdata[i][10], staffdata[i][7]]);
    }
  }
 const countries = [...new Set(cities)].map(elem => (
  {
    country: elem.country,
    emoji: elem.emoji
  } 
));
function extractProductData() {
  const getValueById = (id) => document.getElementById(id) ? document.getElementById(id).value : 'N/A';
  const data = {
    productName: getValueById("productName"),
    item_id: getValueById("productId"),
    price: getValueById("priceInput"),
    item_brand: 'Solskjerming AS', // Questo valore è statico come da tua richiesta
    item_category: getValueById("modelId"),
    item_variant: getValueById("fabricInput"),
  };
  console.log(data);
  return data;
}

extractProductData();
function main() {
  // Settings
  var campaignName = "Campaign Name";
  var significantOverlapChange = 0.1; // 10% change triggers an alert
  var lookbackPeriod = "LAST_30_DAYS";
  var recipientEmail = "your_email@example.com";

  // Get Auction Insights Data
  var report = AdsApp.report(
    "SELECT Domain, ImpressionShare " +
    "FROM AUCTION_INSIGHTS " +
    "WHERE CampaignName = '" + campaignName + "' " +
    "DURING " + lookbackPeriod);

  var rows = report.rows();
  var competitorData = {};

  // Store Impression Share Data
  while (rows.hasNext()) {
    var row = rows.next();
    competitorData[row['Domain']] = row['ImpressionShare'];
  }

  // Compare with Current Data (Simplified)
  var currentCampaign = AdsApp.campaigns().withCondition("Name = '" + campaignName + "'").get().next();
  var competitors = currentCampaign.targeting().auctionInsights().get().results();

  competitors.forEach(function(competitor) {
    var domain = competitor.getDomain();
    var currentImpressionShare = competitor.getStats().getImpressionShare();

    if (domain in competitorData) {
      var previousImpressionShare = competitorData[domain];
      var change = Math.abs(currentImpressionShare - previousImpressionShare);

      if (change >= significantOverlapChange) {
        // Send an alert - Customize this part
        var subject = "Competitor Alert: " + domain;
        var body = "Impression share for " + domain + " has changed significantly in campaign: " + campaignName;
        MailApp.sendEmail(recipientEmail, subject, body);
      }
    }
  });
}
function main() {
  // Settings
  var campaignName = "Campaign Name";
  var metricsToTrack = ["Clicks", "Conversions", "Cost"]; 
  var changeThreshold = 0.2; // 20% increase or decrease
  var comparisonPeriod = "LAST_7_DAYS"; // Timeframe for comparison
  var recipientEmail = "your_email@example.com";

  // Get the campaign
  var campaign = AdsApp.campaigns().withCondition("Name = '" + campaignName + "'").get().next();

  // Fetch performance data for the current and previous periods
  var currentStats = campaign.getStatsFor("TODAY");
  var previousStats = campaign.getStatsFor("PREVIOUS_" + comparisonPeriod); 

  // Analyze each metric
  for (var i = 0; i < metricsToTrack.length; i++) {
    var metric = metricsToTrack[i];
    var currentValue = currentStats.get(metric);
    var previousValue = previousStats.get(metric);

    var changePercentage = (currentValue - previousValue) / previousValue;

    // Send alert if the change is significant
    if (Math.abs(changePercentage) >= changeThreshold) {
      var direction = changePercentage > 0 ? "increased" : "decreased";
      var subject = "Performance Alert: " + campaignName;
      var body = metric + " has " + direction + " by " + (changePercentage * 100).toFixed(0) + "% compared to the previous " + comparisonPeriod.toLowerCase() + ".";
      MailApp.sendEmail(recipientEmail, subject, body);
    }
  }
}
function main() {
  // Threshold Settings
  var campaignBudgetThreshold = 0.8; // Alert when 80% of the budget is spent
  var sendEmailAlerts = true; // Set to false to disable emails
  var recipientEmail = "your_email@example.com";

  // Get all active campaigns
  var campaignIterator = AdsApp.campaigns()
      .withCondition("Status = ENABLED")
      .get();

  while (campaignIterator.hasNext()) {
    var campaign = campaignIterator.next();
    var campaignName = campaign.getName();
    var budget = campaign.getBudget().getAmount();
    var spendToDate = campaign.getStatsFor("TODAY").getCost();

    var spentPercentage = spendToDate / budget;

    if (spentPercentage >= campaignBudgetThreshold && sendEmailAlerts) {
      var subject = "Budget Alert: " + campaignName;
      var body = "Campaign " + campaignName + " has spent " + (spentPercentage * 100).toFixed(0) + "% of its budget.";
      MailApp.sendEmail(recipientEmail, subject, body);
    }
  }
}
function main() {
  // Campaign Selection
  var campaignName = "Campaign Name"; 

  // Ad Rotation Strategy (Choose one and adjust)
  var rotationStrategy = {
    // 1. Rotate Evenly: Give all ads equal chance
    // "ROTATE_EVENLY" 
    
    // 2. Optimize for Clicks: Show higher-performing ads more often 
    // "OPTIMIZE_FOR_CLICKS"

    // 3. Optimize for Conversions: Prioritize ads driving conversions
    // "OPTIMIZE_FOR_CONVERSIONS" 

    // 4. Rotate Indefinitely: Don't automatically select an ad 
    "ROTATE_INDEFINITELY" 
  }

  // Get the specified campaign
  var campaign = AdsApp.campaigns().withCondition("Name = '" + campaignName + "'").get().next();

   // Set the ad rotation type
  var adRotationType = campaign.getAdRotationType();

  // Apply only if rotation settings need to be changed
  if (adRotationType != rotationStrategy) {
    campaign.setAdRotationType(rotationStrategy); 
  }
}
function main() {
  // Settings
  var campaignName = "Campaign Name"; 
  var negativeKeywordListName = "Auto-Generated Negatives";
  var dateRange = "LAST_30_DAYS";

  // Find or create the negative keyword list
  var negativeKeywordList = AdsApp.negativeKeywordLists().withCondition("Name = '" + negativeKeywordListName + "'").get().next();
  if (!negativeKeywordList) {
    negativeKeywordList = AdsApp.newNegativeKeywordListBuilder()
      .withName(negativeKeywordListName)
      .build()
      .getResult();
  }

  // Get search query data 
  var queryReport = AdsApp.searchQueryPerformanceReport()
      .forCampaign(campaignName)
      .withCondition("Status = ENABLED") // Focus on active keywords
      .during(dateRange);

  var queryRows = queryReport.rows();
  while (queryRows.hasNext()) {
    var queryRow = queryRows.next();
    var searchQuery = queryRow.getQuery();
    var impressions = queryRow.getImpressions();
    var clicks = queryRow.getClicks();
    var cost = queryRow.getCost();

    // Add query as a negative keyword if it meets your criteria 
    // Example: High impressions, low CTR, high cost
    if (impressions > 100 && clicks == 0 && cost > 10) {
      negativeKeywordList.addNegativeKeyword(searchQuery);
    } 
  }

  // Apply the negative keyword list to the campaign
  var campaign = AdsApp.campaigns().withCondition("Name = '" + campaignName + "'").get().next();
  campaign.addNegativeKeywordList(negativeKeywordList);
}
function main() {
  // Settings
  var campaignName = "Campaign Name"; 
  var negativeKeywordListName = "Auto-Generated Negatives";
  var dateRange = "LAST_30_DAYS";

  // Find or create the negative keyword list
  var negativeKeywordList = AdsApp.negativeKeywordLists().withCondition("Name = '" + negativeKeywordListName + "'").get().next();
  if (!negativeKeywordList) {
    negativeKeywordList = AdsApp.newNegativeKeywordListBuilder()
      .withName(negativeKeywordListName)
      .build()
      .getResult();
  }

  // Get search query data 
  var queryReport = AdsApp.searchQueryPerformanceReport()
      .forCampaign(campaignName)
      .withCondition("Status = ENABLED") // Focus on active keywords
      .during(dateRange);

  var queryRows = queryReport.rows();
  while (queryRows.hasNext()) {
    var queryRow = queryRows.next();
    var searchQuery = queryRow.getQuery();
    var impressions = queryRow.getImpressions();
    var clicks = queryRow.getClicks();
    var cost = queryRow.getCost();

    // Add query as a negative keyword if it meets your criteria 
    // Example: High impressions, low CTR, high cost
    if (impressions > 100 && clicks == 0 && cost > 10) {
      negativeKeywordList.addNegativeKeyword(searchQuery);
    } 
  }

  // Apply the negative keyword list to the campaign
  var campaign = AdsApp.campaigns().withCondition("Name = '" + campaignName + "'").get().next();
  campaign.addNegativeKeywordList(negativeKeywordList);
}
function main() {
  // 1. Data Source: Google Sheet
  var spreadsheetUrl = "https://docs.google.com/spreadsheets/d/..."; // Replace with your spreadsheet URL
  var dataSheet = SpreadsheetApp.openByUrl(spreadsheetUrl).getSheetByName("CampaignData");

  // 2. Campaign Template Settings
  var campaignNameTemplate = "Dynamic Campaign - {Product Category}";
  var budget = 100; // Daily budget
  // ... other desired campaign settings ...

  // 3. Iterate through Spreadsheet Data 
  var dataRange = dataSheet.getDataRange().getValues(); 
  dataRange.shift(); // Remove header row

  for (var i = 0; i < dataRange.length; i++) {
    var productCategory = dataRange[i][0]; 
    // ... extract other data from the row ...

    // 4. Create New Campaign (Simplified)
    var campaignBuilder = AdsApp.newCampaignBuilder();
    var campaign = campaignBuilder
      .withName(campaignNameTemplate.replace("{Product Category}", productCategory))
      .withBudget({ amount: budget, currencyCode: "USD" })
      .build()
      .getResult(); 

    // 5. (Optional) Create Ad Groups, Keywords, Ads based on Spreadsheet Data
  }
}
function main() {
  // Define your schedule
  var dayOfWeek = "MONDAY"; 
  var startTime = "00:00"; // Midnight
  var endTime = "06:00";  // 6 AM

  // Campaign Selection 
  var campaignName = "Weekend Campaign";

  // Get the current day of the week and time (adjust the timezone if needed)
  var timeZone = "America/Los_Angeles";  
  var date = new Date();
  var currentDayOfWeek = Utilities.formatDate(date, "EEEE", timeZone);
  var currentTime = Utilities.formatDate(date, "HH:mm", timeZone);

  // Pause or enable the campaign based on the schedule
  var campaign = AdsApp.campaigns().withCondition("Name = '" + campaignName + "'").get().next();

  if (currentDayOfWeek == dayOfWeek && currentTime >= startTime && currentTime <= endTime) {
    campaign.pause();
  } else {
    campaign.enable();
  }
}
function main() {
  // Get your OpenWeatherMap API key (Sign up for a free account)
  var apiKey = "YOUR_API_KEY"; 

  // Target location (City or Zip Code)
  var targetLocation = "Los Angeles, CA"; 

  // Campaign Selection 
  var campaignName = "Summer Campaign"; 

  // Bid adjustments based on temperature
  var temperatureRanges = {
    "below_70": -0.1,   // Decrease bid by 10% if below 70°F
    "70_to_85": 0.0,    // No change between 70°F and 85°F 
    "above_85": 0.2     // Increase bid by 20% if above 85°F
  };

  // Fetch current weather data
  var weatherUrl = "https://api.openweathermap.org/data/2.5/weather?q=" + targetLocation + "&appid=" + apiKey + "&units=imperial";
  var weatherResponse = UrlFetchApp.fetch(weatherUrl);
  var weatherData = JSON.parse(weatherResponse.getContentText());

  // Extract temperature from the data
  var currentTemperature = weatherData.main.temp;

  // Determine the appropriate bid modifier
  var bidModifier;
  for (var range in temperatureRanges) {
    if (currentTemperature >= range.split("_")[1]) {
      bidModifier = temperatureRanges[range];
      break;
    }
  }

  // Apply the bid modifier at the campaign level
  var campaign = AdsApp.campaigns().withCondition("Name = '" + campaignName + "'").get().next();
  campaign.setBidModifier(1 + bidModifier); 
}
function main() {
  // Performance Thresholds
  var maxCPA = 50;  // Your maximum acceptable cost per acquisition
  var minClicks = 50; // Minimum clicks for reliable data

  // Timeframe: Analyze recent performance
  var dateRange = "LAST_30_DAYS"; 

  // Campaign Selection 
  var campaignName = "Campaign Name";

  // Get all the keywords in the specified campaign
  var keywordIterator = AdsApp.campaigns()
      .withCondition("Name = '" + campaignName + "'")
      .get()
      .keywords();

  while (keywordIterator.hasNext()) {
    var keyword = keywordIterator.next();

    // Gather keyword performance data
    var stats = keyword.getStatsFor(dateRange);
    var conversions = stats.getConversions();
    var cost = stats.getCost();
    var clicks = stats.getClicks();
    var currentCPA = cost / conversions;

    // Pause keywords if they exceed max CPA and have sufficient data
    if (currentCPA > maxCPA && clicks >= minClicks) {
      keyword.pause();
    }
  }
}
function main() {
  // Target Locations (Adjust this list!)
  var targetLocations = [
    "California", 
    "New York", 
    "Texas"
  ];

  // Bid Adjustments (Positive = Increase, Negative = Decrease)
  var locationBidModifiers = {
    "California": 0.20,  // Increase bids by 20% in California
    "New York": 0.10,    // Increase bids by 10% in New York
    "Texas": -0.15       // Decrease bids by 15% in Texas
  };

  // Campaign Selection 
  var campaignName = "Campaign Name"; 

  // Get all the location criteria within the specified campaign
  var locationIterator = AdsApp.campaigns()
      .withCondition("Name = '" + campaignName + "'")
      .get()
      .targeting().locations();

 while (locationIterator.hasNext()) {
    var location = locationIterator.next();
    var locationName = location.getName(); 

    // Check if the location is in our target list
    if (targetLocations.indexOf(locationName) !== -1) {
      var bidModifier = locationBidModifiers[locationName];

      // Set the bid modifier only if it exists
      if (bidModifier) {
        location.setBidModifier(1 + bidModifier); 
      }
    }
  }
}
function main() {
  // Performance Metrics
  var targetCPA = 30; // Your desired cost per acquisition
  var minConversions = 10; // Minimum conversions for reliable data

  // Timeframe: Analyze recent performance with flexibility
  var dateRange = "LAST_30_DAYS"; 

  // Campaign Selection 
  var campaignName = "Campaign Name"; 

  // Get relevant keywords
  var keywordIterator = AdsApp.campaigns()
      .withCondition("Name = '" + campaignName + "'")
      .get()
      .keywords();

  while (keywordIterator.hasNext()) {
    var keyword = keywordIterator.next();

    // Gather keyword performance data
    var stats = keyword.getStatsFor(dateRange);
    var conversions = stats.getConversions();
    var cost = stats.getCost();
    var currentCPA = cost / conversions;

    // Apply Bid Adjustments Only If Data is Sufficient 
    if (conversions >= minConversions) {
      if (currentCPA > targetCPA) {
        // Decrease bid if CPA is higher than target
        var newBid = keyword.getMaxCpc() * 0.9; // Example: Reduce by 10%
        keyword.setMaxCpc(newBid);
      } else if (currentCPA < targetCPA) {
        // Increase bid if CPA is lower than target
        var newBid = keyword.getMaxCpc() * 1.1; // Example: Increase by 10%
        keyword.setMaxCpc(newBid);
      }
    } 
  }
}
function main() {
  // Set your timezone for accurate time-based adjustments 
  var timeZone = "America/Los_Angeles";  

  // Get the current hour in your specified timezone
  var currentHour = Utilities.formatDate(new Date(), "HH", timeZone);

  // Define your campaign name (replace with your actual campaign)
  var campaignName = "Campaign Name"; 

  // Get all the keywords in the specified campaign
  var keywordIterator = AdsApp.campaigns()
      .withCondition("Name = '" + campaignName + "'")
      .get()
      .keywords();

  while (keywordIterator.hasNext()) {
    var keyword = keywordIterator.next();

    // Example: Increase bids by 20% during peak hours (9 AM to 5 PM)
    if (currentHour >= 9 && currentHour <= 17) {
      keyword.setBidModifier(1.2);  // Increase bid by 20%
    } else {
      keyword.setBidModifier(1.0);  // Reset bid to normal
    }
  }
}

/**
 * Format a given date object to YYYY-MM-DD format.
 * 
 * @param {Date} date The date object to be formatted.
 * @returns {string} The formatted date in YYYY-MM-DD format.
 */
function formatDateToYYYYMMDD(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const formattedDate = `${year}-${month}-${day}`;
    return formattedDate;
}
//rpf のgsap スライド

const listWrapperEl = document.querySelector('.side-scroll-list-wrapper');
const listEl = document.querySelector('.side-scroll-list');

gsap.to(listEl, {
  x: () => -(listEl.clientWidth - listWrapperEl.clientWidth),
  ease: 'none',
  scrollTrigger: {
    trigger: '.side-scroll',
    start: 'top 20%',
    end: () => `+=${listEl.clientWidth - listWrapperEl.clientWidth}`,
    scrub: true,
    pin: true,
    anticipatePin: 1,
    invalidateOnRefresh: true,
    onUpdate: (scrollTrigger) => {
      const activeIndex = Math.round(scrollTrigger.progress * (listEl.children.length - 1));
      yourOtherFunction(activeIndex);
    },
  },
});



function yourOtherFunction(activeIndex) {
  const myList = document.querySelectorAll('.side-scroll-list li');
  const variableToCompare = activeIndex;

  myList.forEach((item, index) => {
    if (index === variableToCompare) {
      item.classList.add('active');
    }
    else {
      item.classList.remove('active');
    }
  });
  const myList2 = document.querySelectorAll('.side-scroll-status li');
  myList2.forEach((item, index) => {
    if (index === variableToCompare) {
      item.classList.add('current');
    }
    else {
      item.classList.remove('current');
    }
  });
}

var percentTime;
var tick;
var progressBar = document.querySelector('.js-mainvisual-progress');

var mySwiper = new Swiper('.js-mainvisual-container', {
	effect: 'slide',
	loop: true,
	speed: 400,
	slidesPerView: 1,
	spaceBetween: 30,
	grabCursor: false,
	watchOverflow: true,
	easing: 'ease-in',
	keyboard: {
		enabled: true,
		onlyInViewport: true
	},
	watchOverflow: true,
	watchSlidesProgress: true,
	watchSlidesVisibility: true,
	roundLengths: true,
	autoplay: {
		delay: 3000,
		disableOnInteraction: false
	},
	on: {
		slideChange: function () {
			var swiper = this;
			var defaultSlideDelay = swiper.params.autoplay.delay;
			var currentIndex = swiper.realIndex + 1;
			var currentSlide = swiper.slides[currentIndex];
			var currentSlideDelay = currentSlide.getAttribute('data-swiper-autoplay') || defaultSlideDelay;
			updateSwiperProgressBar(progressBar, currentSlideDelay);
		}
	}
});

function updateSwiperProgressBar(bar, slideDelay) {

	let tick;

	function startProgressBar() {
		resetProgressBar();
		tick = requestAnimationFrame(progress);
	}

	function progress() {

		var timeLeft = getTimeout(mySwiper.autoplay.timeout);

		if (mySwiper.autoplay.running && !mySwiper.autoplay.paused) {
			percentTime = sanitisePercentage(100 - (timeLeft / slideDelay * 100));
			bar.style.width = percentTime + 5 + '%';
			bar.style.transition = 'width ' + percentTime + 'ms linear';

			if (percentTime > 100) {
				resetProgressBar();
			}
		}

		if (mySwiper.autoplay.paused) {
			percentTime = 0;
			bar.style.width = 0;
		}

		tick = requestAnimationFrame(progress);
	}

	function resetProgressBar() {
		percentTime = 0;
		bar.style.width = 0;
		cancelAnimationFrame(tick);
	}

	startProgressBar();

}

<div class="p-mainvisual slider">
					<div class="p-mainvisual__container swiper-container js-mainvisual-container">
					  	<div class="p-mainvisual__swiper swiper-wrapper">
					  		<div class="p-mainvisual__swiper-slide swiper-slide"  data-swiper-autoplay="3000">
					  		  <img src="<%= getRelativePath('/assets/images/index/img_index_mv1.jpg'); %>" alt="">
					  		</div>
					  		<div class="p-mainvisual__swiper-slide swiper-slide"  data-swiper-autoplay="3000">
					  		  <img src="<%= getRelativePath('/assets/images/index/img_index_mv2.jpg'); %>" alt="">
					  		</div>
					  		<div class="p-mainvisual__swiper-slide swiper-slide"  data-swiper-autoplay="3000">
					  		  <img src="<%= getRelativePath('/assets/images/index/img_index_mv3.jpg'); %>" alt="">
					  		</div>
					  	</div>
				  

						<div class="p-mainvisual__progress swiper-hero-progress js-mainvisual-progress"></div>

						<div class="p-mainvisual__text">人と自然に<br class="u-only-sp">快適な環境を創る</div>
						<div class="p-mainvisual__buttons">
							<span class="c-rounded-btn js-pop-up">
								<picture>
									<source srcset="<%= getRelativePath('/assets/images/index/img_index_mv_logo1-sp.png.webp'); %>" media="(max-width:767px)" type="image/webp">
									<source srcset="<%= getRelativePath('/assets/images/index/img_index_mv_logo1-sp.png'); %>" media="(max-width:767px)">
									<source srcset="<%= getRelativePath('/assets/images/index/img_index_mv_logo1.png.webp'); %>" type="image/webp">
									<img src="<%= getRelativePath('/assets/images/index/img_index_mv_logo1.png'); %>" alt="エコアクション21認定登録">
								</picture>
							</span>
							<div class="c-rounded-btn__group">
								<a href="https://www3.sanpainet.or.jp/chukan2/company/19452/" target="_blank" class="c-rounded-btn">
									<picture>
										<source srcset="<%= getRelativePath('/assets/images/index/img_index_mv_logo2-sp.png.webp'); %>" media="(max-width:767px)" type="image/webp">
										<source srcset="<%= getRelativePath('/assets/images/index/img_index_mv_logo2-sp.png'); %>" media="(max-width:767px)">
										<source srcset="<%= getRelativePath('/assets/images/index/img_index_mv_logo2.png.webp'); %>" type="image/webp">
										<img src="<%= getRelativePath('/assets/images/index/img_index_mv_logo2.png'); %>" alt="優良産廃処理業者認定">
									</picture>
								</a>
								<a href="<%= getRelativePath('/certificate/'); %>" class="c-rounded-btn">
									<picture>
										<source srcset="<%= getRelativePath('/assets/images/index/img_index_mv_logo3-sp.png.webp'); %>" media="(max-width:767px)" type="image/webp">
										<source srcset="<%= getRelativePath('/assets/images/index/img_index_mv_logo3-sp.png'); %>" media="(max-width:767px)">
										<source srcset="<%= getRelativePath('/assets/images/index/img_index_mv_logo3.png.webp'); %>" type="image/webp">
										<img src="<%= getRelativePath('/assets/images/index/img_index_mv_logo3.png'); %>" alt="許可証一覧">
									</picture>	  
								</a>
							</div>
						</div>
					</div> 
				  </div>
​

var getTimeout = function(){var e=setTimeout,b={};setTimeout=function(a,c){var d=e(a,c);b[d]=[Date.now(),c];return d};return function(a){return(a=b[a])?Math.max(a[1]-Date.now()+a[0],0):NaN}}();

​

function sanitisePercentage(i){

    return Math.min(0,Math.max(0,i));

}

​

// Slider

var percentTime;
10
var tick;

var progressBar = document.querySelector('.swiper-hero-progress');

​

var mySwiper = new Swiper('.swiper-container', {

    effect: 'slide',
// got DOM element

const cursor = document.querySelector('#cursor');

const cursorCircle = cursor.querySelector('.cursor__circle');

​

//variables which defines coordinates of 

const mouse = { x: -0, y: -100 }; // mouse pointer's coordinates

const pos = { x: 0, y: 0 }; // cursor's coordinates

const speed = 0.1; // between 0 and 1

​
10
const updateCoordinates = e => {

  mouse.x = e.clientX;
   var swiper = new Swiper('.js-news-swiper', {
      slidesPerView: 'auto',
      centeredSlides: true,
      spaceBetween: 20,
      speed: 1500,
      pagination: {
        el: '.swiper-pagination',
        clickable: true
      },
      navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev'
      },
      autoplay: {
        delay: 2000,
        disableOnInteraction: false
      },
      loop: true,
      watchSlidesProgress: true
    });
    var mySwiper = new Swiper(".js-ticker", {	
        infinite: true,
        loop: true,
        slidesPerView: 'auto',
        speed: 8000,
        spaceBetween: 32,
        centeredSlides: true,
        autoplay: {
          delay: 0,
          disableOnInteraction: false,
          reverseDirection: false,
        },
      });

function diff(start, end) {
    start = document.getElementById("start").value; //to update time value in each input bar
    end = document.getElementById("end").value; //to update time value in each input bar
    
    start = start.split(":");
    end = end.split(":");
    var startDate = new Date(0, 0, 0, start[0], start[1], 0);
    var endDate = new Date(0, 0, 0, end[0], end[1], 0);
    var diff = endDate.getTime() - startDate.getTime();
    var hours = Math.floor(diff / 1000 / 60 / 60);
    diff -= hours * 1000 * 60 * 60;
    var minutes = Math.floor(diff / 1000 / 60);

    return (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes;
}
/**
 * dateUtils
 * Format Date using php's format string.  Date to/From ymd. Get Today's date as ymd or Date, with no time.
 *
 * @type {{todayYMD: (function(): string), ymdToDate: (function(*): Date), is_ymd: ((function(*): boolean)|*), today: (function(): Date), format: ((function((Date|string|number), string=, string=): string)|*), dateToYMD: (function(*): string), dateToDay: (function(*): Date), setLanguage(*): ({shortMonth, shortDay, longMonth, longDay})}}
 */
const dateUtils = {
    version: "2024-02-22",

    dateToDay: function(date){return new Date((new Date(date)).setHours(0, 0, 0, 0) );
    },

    dateToYMD: function date(date) {return this.dateToDay(date).toISOString().split('T')[0];},

    today: function() {return new Date((new Date()).setHours(0, 0, 0, 0) );},

    todayYMD: function() {return this.today().toISOString().split('T')[0];},

    ymdToDate: function(ymd) {return ymd.length === 10 ? this.dateToDay(ymd) : new Date(ymd); },

    is_ymd: function(value, dateOnly = true) {
        if(value === null || !isNaN(value) || typeof value !== 'string')
            return false;
        if(dateOnly) {
            if(value.length !== 10)
                return false;
            const regex = /^\d\d\d\d[-.\\\/_](0[1-9]|1[0-2])[-.\\\/_](0[1-9]|[1-2][0-9]|3[0|1])$/gm;
            return value.match(regex) !== null;
        }
        if(value.length < 10 || value.length > 27)
            return false;
        const regex =
           /^\d\d\d\d[-.\\\/_](0[1-9]|1[0-2])[-.\\\/_](0[1-9]|[1-2][0-9]|3[0|1])($|([ T]([0-1]\d|2[0-4]):[0-5]\d:[0-5]\d))/gm;
        return value.match(regex) !== null;
    },

    /**
     * Formats a date according to the given format string in PHP style
     *
     * @param {Date|string|number} inputDate - The date to be formatted. Can be a Date object, a date string, or a timestamp.
     * @param {string} [formatPhpStyle="d/M/y"] - The format string to be used for formatting the date. Defaults to "d/M/y"
     *  https://www.php.net/manual/en/datetime.format.php.
     * @param {string} [language="en"] - Englinsh en, Spanish es
     * @returns {string} - The formatted date string.
     * @throws {Error} - If an error occurs during the formatting process.
     */
    format: function(inputDate, formatPhpStyle = "d/M/y", language = "en")  {
        let lang = this.setLanguage(language);
        if(inputDate === null)
            return "";
        try {
            function padZero(value) {return value < 10  ? `0${value}` : `${value}`;}
            let date;
            if(inputDate instanceof Date)
                date = inputDate;
            else if(typeof inputDate === 'object')
                return "[object]";
            else if(isNaN(inputDate))
                date = this.is_ymd(inputDate) ?
                    new Date(`${inputDate}T00:00:00`) : new Date(inputDate);
            else
                date = new Date(inputDate);

            const parts = {
                d: padZero(date.getDate()),
                j: date.getDate(),
                D: lang.shortDay[date.getDay()],
                l: lang.longDay[date.getDay()],
                w: date.getDay(),

                m: padZero(date.getMonth() + 1),
                n: date.getMonth() + 1,
                M: lang.shortMonth[date.getMonth()],
                F: lang.longMonth[date.getMonth()],

                Y: date.getFullYear(),
                y: date.getFullYear().toString().slice(-2),

                H: padZero(date.getHours()),
                G: date.getHours(),
                h: padZero(date.getHours() > 12 ? date.getHours() - 12 : date.getHours()),
                g: date.getHours() > 12 ? date.getHours() - 12 : date.getHours(),
                i: padZero(date.getMinutes()),
                s: padZero(date.getSeconds()),

                a: date.getHours() < 12 ? 'am' : 'pm',
                A: date.getHours() < 12 ? 'AM' : 'PM',
            };

            let skip = false;
            let ret = [];
            for(let i = 0, len = formatPhpStyle.length; i < len; ++i) {
                let c = formatPhpStyle[i];
                if(c === "\\") {
                    skip = true;
                    continue;
                }
                if(skip) {
                    skip = false;
                    ret.push(c);
                    continue;
                }
                ret.push(parts.hasOwnProperty(c) ? parts[c] : c);
            }
            return ret.join("");
        } catch(error) {
            console.log("ERROR: fmt.date arguments:", arguments);
            console.log("       fmt.date error:", error);
            return inputDate;
        }
    },

    setLanguage(language) {
        switch(language.toLowerCase()) {
            case 'es':
                return {
                    longMonth: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto',
                        'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
                    shortMonth: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
                    longDay: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
                    shortDay: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'],
                };
            case 'en':
            default:
                return {
                    longMonth: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
                        'October', 'November', 'December'],
                    shortMonth: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
                    longDay: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
                    shortDay: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
                };
        }
    },

};
function scrollBanner() {
      jQuery(document).on('scroll', function(){
      var scrollPos = jQuery(this).scrollTop();
        jQuery('.home_banner').css({
          'top' : (scrollPos/4)+'px',
        });
      });    
      }
scrollBanner(); 


// With out function


jQuery(document).ready(function(){
	
	jQuery(window).on('scroll', function(){
		var scrollTop = jQuery(window).scrollTop();
		jQuery('.home_banner').css({'top': (scrollTop/4) +'px'});
		
	});
});
class TLoadComplete{
    constructor( callbackFunc, frequency ){
        this.callback = callbackFunc || (()=>{ console.log("completed")});
        this.frequency = frequency || 500;
    }
 
    start(){
        if (this.started) return;
        this.started = true;
        let me = this;
        this.images = [...document.images];
        this.interval = setInterval(()=>{
            let result = me.images.filter(el => !el.complete).length == 0 && document.fonts.ready;
            if (result) {
                me.callback();
                console.log("completed");
                me.stop();
            }
        }, me.frequency)
    }
 
    stop(){
        clearTimeout(this.interval);
        this.started = false;
    }
}
const waitLoad = ( statusFunc )=>{
    var imagesLoaded=false;
    var fontsLoaded=false;

    let interval = setInterval(()=>{
        fontsLoaded = fontsLoaded || document.fonts.ready;
        imagesLoaded = imagesLoaded || ([...document.images].filter(el => !el.complete).length == 0);
        statusFunc( fontsLoaded && imagesLoaded );
        if (fontsLoaded && imagesLoaded) clearInterval(interval);
    }, 500);
}

// use waitLoad( ( state ) => console.log(state) )
header{
    background-color: #333;
    color: #fff;
    padding: 10px 0;
}

nav ul{
    list-style: none;
    display: flex;
    justify-content: center;
}
nav li{
    margin: 0 20px;
}
nav a{
    text-decoration: none;
    color: #fff;
}
const chatInput = document.querySelector(".chat-input textarea");
const sendChatBtn = document.querySelector(".chat-input span");
const chatbox = document.querySelector(".chatbox");

let userMessage;
const API_KEY = "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";

let createChatLi = (message, className) => {
    // Create a chat <li> element with the passed message and className
    const chatLi = document.createElement("li");
    chatLi.classList.add("chat", className);
    let chatContent = className === "outgoing" ? `<p>${message}</p>` : ` <span class="material-symbols-outlined">
    smart_toy
  </span><p>${message}</p>`;
  chatLi.innerHTML = chatContent;
  return chatLi;
}
const generateResponse = (incomingChatLi) => {
    const API_URL = "https://api.openai.com/v1/chat/completions";
    const messageElement = incomingChatLi.querySelector("p");
    const requestOption = {
        method: "POST",
        headers: {
            "Content-Type" : "application/json",
            "Authorization": `Bearer ${API_KEY}`
        },
        body: JSON.stringify({
            model: "gpt-3.5-turbo",
            messages: [{role: "user", content: userMessage}]
        })
            
        
    }
    // Send POST request to API, get response
    fetch(API_URL, requestOption).then(res => res.json()).then(data => {
        messageElement.textContent = data.choices[0].message.content;
    }).catch((error) => {
        messageElement.textContent = "Oops! Something went horribly wrong. Please try again.";
    })
}

const handleChat = () => {
    userMessage = chatInput.value.trim();
    if(!userMessage) return;

    // Append the user's message to the chatbox
    chatbox.appendChild(createChatLi(userMessage, "outgoing"));

    setTimeout(() => {
        const incomingChatLi = createChatLi("...", "incoming")
        chatbox.appendChild(incomingChatLi);
        generateResponse(incomingChatLi);
    },600);

}
sendChatBtn.addEventListener("click", handleChat)
try {history.replaceState({content: document.title}, document.title, document.location.href);} catch(e) {}
/** Vanilla javascript **/

    // Get the value of the checked radio button, undefined on not checked or not found
   let radioButtonValue = (document.querySelector("input[name='radioName']:checked") || {}).value || undefined

    // Check radio button with value ...
    (document.querySelector("input[name='radioName'][value='A']") || {}).checked=true;

/** jQuery **/

    // Get the value of the checked radio button, undefined on not checked or not found
   let radioButtonValue = $("input[name='radioName']:checked").val();

    // Check radio button with value ...
   $("input[name='radioName'][value='A']").prop('checked',true);
 //HTML





<div class="custom-mouse"></div>





//CSS


.custom-mouse{
    border: none;
    background-color: #fff;
    transform: translate(-50%, -100%);
    width: 20px;
    height: 20px;
    border-radius: 50%;
    position: absolute;
    top: 0;
}



//JS


let customMouse = document.querySelector(".custom-mouse");
window.addEventListener("mousemove", function(details) {
   let xValue = details.clientX;
   let yValue = details.clientY;

   setTimeout(() => {
       customMouse.style.top = `${yValue}px`;
       customMouse.style.left = `${xValue}px`;
         
   }, 100);


});
dataLayer.push({
  ecommerce: {
    currencyCode: "EUR",
    purchase: {
      actionField: {
        coupon: "",
        affiliation: "Online Store",
        transaction_id: 4091243,
        revenue: 5.37,
        new: 1,
        shipping: 4.99,
        id: "4091243",
        option: "paypal_payment_method_handler",
        tax: 1.02
      },
      products: [
        {
          quantity: 1,
          item_name: "Baby-Gießer Glitter",
          item_id: 2000578486402,
          id: "2000578486402",
          name: "Baby-Gießer Glitter",
          type: "product",
          p_id: "",
          variant: "",
          brand: "Simba",
          price: 1.4,
          category: "Sandspielzeug"
        }
      ]
    }
  },
  session-: "380c5d93a281755852731a6997eeff34",
  google_tag_params: {ecomm_totalvalue: 6.39, ecomm_pagetype: "purchase"}
})
 
HTML

 <nav>
      <ul>
          <li class="item">Home</li>
          <li class="item">Content</li>
          <li class="item">About</li>
          <li class="item">Contact Us</li>

      </ul>
  </nav>


  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js"></script>
  <script src="script.js"></script>


CSS


body{
    background-color: #fff;
    overflow: hidden;
}
.container{
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    
}
.item{
    color: grey;
    font-size: large;
    font-weight: bolder;
    cursor: pointer;
}


JS


let itemList = document.querySelectorAll(".item");


itemList.forEach(function (item, index) {

    let animation = gsap.to(item, {color: "black",x:3,y: -3, ease: "", duration:0.3, paused:true  })
    
    item.addEventListener("mouseenter", function() {
        animation.play()
    })
    item.addEventListener("mouseleave", function() {
        animation.reverse()
    })
})

const uuid = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
}

export default uuid;
function replaceURLTextWithLink(text) {
 
            // Put the URL to variable $1 after visiting the URL
            const Rexp =/((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g;
 
            // Replace the RegExp content by HTML element
            return text.replace(Rexp,
                "<a href='$1' target='_blank'>$1</a>");
}
function MyPage() {
  const [theme, setTheme] = useState('dark');
  return (
    <ThemeContext.Provider value={theme}>
      <Form />
      <Button onClick={() => {
        setTheme('light');
      }}>
        Switch to light theme
      </Button>
    </ThemeContext.Provider>
  );
}
// Avia Layout Builder in custom post types

function avf_alb_supported_post_types_mod( array $supported_post_types )
{
  $supported_post_types[] = 'case_studies';
  return $supported_post_types;
}
add_filter('avf_alb_supported_post_types', 'avf_alb_supported_post_types_mod', 10, 1);

function avf_metabox_layout_post_types_mod( array $supported_post_types )
{
 $supported_post_types[] = 'case_studies';
 return $supported_post_types;
}
add_filter('avf_metabox_layout_post_types', 'avf_metabox_layout_post_types_mod', 10, 1);
import { useLocation } from "react-router-dom";

const ProfileTwo = () => {
  const location = useLocation();
  const data = location.state;

  return (
    <div>
      <p>Name: {data.name}</p>
      <p>Age: {data.age}</p>
      Hello
    </div>
  );
};

export default ProfileTwo;
import { useNavigate } from "react-router-dom";

const ProfileOne = () => {
  const navigate = useNavigate();
  const data = { name: "John", age: 30 };

  const handleClick = () => {
    navigate("/profile-two", { state: data });
  };

  return <button onClick={handleClick}>Go to ProfileTwo</button>;
};

export default ProfileOne;
// importing
import ReactPaginate from 'react-paginate';

// handling the pagination
const [page, setPage] = useState(0);
const handlePageClick = (num) => {
  setPage(num);
};

// fetching all the employee details from the mongoDB database
const [loadedEmployees, setLoadedEmployees] = useState();
useEffect(() => {
  const fetchEmployees = async () => {
    try {
      const responseData = await sendRequest(
        `http://localhost:5000/api/employees/emp?page=${page}`
      );
      setLoadedEmployees(responseData.employees);
    } catch (err) {
      console.log("Error in fetching employees: "+err);
    }
  };
  fetchEmployees();
}, [sendRequest, page]);


// returning this component
<ReactPaginate
  containerClassName="flex gap-2 justify-center mt-4"
  pageClassName="text-gray-500"
  activeClassName="text-gray-900 border-2 border-black px-2"
  previousClassName="text-gray-500"
  nextClassName="text-gray-500"
  breakLabel="..."
  nextLabel="next >"
  onPageChange={(selected) => handlePageClick(selected.selected + 1)}
  pageRangeDisplayed={2}
  marginPagesDisplayed={1}
  pageCount={pageCount}
  previousLabel="< previous"
  renderOnZeroPageCount={null}
/>



// backend - controller methods
const getEmployeeCount = async (req, res, next) => {
  let employeeCount;
  try {
    employeeCount = await Employee.countDocuments();
  } catch (err) {
    const error = new HttpError(
      'Fetching employee count failed, please try again later.',
      500
    );
    return next(error);
  }

  res.json({ employeeCount });
  console.log("DEBUG -- Employee-Controller - Fetching employee count successful!");
};
const getEmployees = async (req, res, next) => {
  const page = req.query.page || 0;
  const employeesPerPage = 2; 

  let allEmployees;
  try {
    allEmployees = await Employee
      .find()
      .skip(page * employeesPerPage)
      .limit(employeesPerPage);
  } catch (err) {
    const error = new HttpError(
      'Fetching Employees failed, please try again later.',
      500
    );
    return next(error);
  }

  if (!allEmployees || allEmployees.length === 0) {
    return next(new HttpError('No employees found.', 404));
  }

  res.json({
    employees: allEmployees.map((emp) => emp.toObject({ getters: true })),
  });
  console.log("DEBUG -- Employee-Controller - Fetching employees successful!");
};
var number;
Console.WriteLine("Enter a number:");
number = Convert.ToInt32(Console.ReadLine());
if (IsPrime(number))
{
    Console.WriteLine("**" + number + " is a prime number**");
}
else
{
    Console.WriteLine("**" + number + " is not a prime number**");
}

public static bool IsPrime(int number)
{
    if (number <= 1) return false;
    if (number == 2) return true;
    if (number % 2 == 0) return false;
    var boundary = (int)Math.Floor(Math.Sqrt(number));
    for (int i = 3; i <= boundary; i += 2)
        if (number % i == 0)
            return false;
    return true;
}
import axios from "axios"; //Check this for more information

const [user, SetUser] = useState({
  name = "",
  username = "",
  email = "",
});

const { name, username, email } = user;

const onInputChange = (e) => {
  setUser({ ...user, [e.target.name]: e.target.value }); //This will append info when type
}

const onSubmit = async (e) => {
  e.preventDefault(); //This will prevent showing info in url.
  await axios.post("https://localhost:8080/user") //Link to backend server
  //We use async and await here to guarantee get the data before submit.
};

<form onSubmit = {(e) => onSubmit(e)}>
  <input
	value={name}
	onChange={(e) => onInputChange(e)}
	/>
</form>
let shelf = ["Think and Grow Rich", "Four-Hour Work Week", "The Power of I AM", "Eat That Frog", "Harry Potter"];
input[type=text],
input[type=password] {
    ...
    width: calc(100% - 20px);
}
   <canvas id="my_canvas" width="250" height="250"></canvas>

//To draw the half circle with canvas
  var ctx = document.getElementById("my_canvas").getContext("2d");
  var al = 0;
  var start = 4.72;
  var cw = ctx.canvas.width;
  var ch = ctx.canvas.height;
  var diff;
  var counter = 0;
  var gradient = ctx.createLinearGradient(0, 0, 0, 250);
  gradient.addColorStop("0.0", "white");
  gradient.addColorStop("1.0", "#ae4e86");
  function progressSim() {
    diff = ((al / 100) * Math.PI * 2 * 10).toFixed(2);
    counter = (al * 0.6).toFixed(0);
    $("#clock_text > span").text(counter);
    ctx.clearRect(0, 0, cw, ch);
    ctx.lineWidth = 55;
    ctx.strokeStyle = gradient;
    ctx.beginPath();
    ctx.arc(125, 130, 80, start, diff / 10 + start, false);
    ctx.stroke();
    if (al >= 50) {
      clearTimeout(sim);
      // Add scripting here that will run when progress completes
    }
    al++;
  }
  var sim = setInterval(progressSim, 30);
});
const truncate = (str, n) => {
  return str?.length > n ? str.substr(0, n - 1) + " ..." : str;
}
   function enterTransfer(address to) public payable {
     
    emit EnteredTransfer(block.timestamp, msg.sender, to, msg.value);
    
   }
contract Transaction {
    event EnteredTransfer(
        uint256 indexed date,
        address from,
        address indexed to,
        uint256 value
    );
}
function setUrlParam(param, value) {
    const url = new URL(window.location.href);
    url.searchParams.set(param, value);
    window.history.pushState({}, "", url);
}

function deleteUrlParam(param) {
    const url = new URL(window.location.href);
    url.searchParams.delete(param);
    window.history.pushState({}, "", url);
}
<style>
body{
background:#f9f9fb;    
}
.view-account{
background:#FFFFFF; 
margin-top:20px;
}
.view-account .pro-label {
font-size: 13px;
padding: 4px 5px;
position: relative;
top: -5px;
margin-left: 10px;
display: inline-block
}

.view-account .side-bar {
padding-bottom: 30px
}

.view-account .side-bar .user-info {
text-align: center;
margin-bottom: 15px;
padding: 30px;
color: #616670;
border-bottom: 1px solid #f3f3f3
}

.view-account .side-bar .user-info .img-profile {
width: 120px;
height: 120px;
margin-bottom: 15px
}

.view-account .side-bar .user-info .meta li {
margin-bottom: 10px
}

.view-account .side-bar .user-info .meta li span {
display: inline-block;
width: 100px;
margin-right: 5px;
text-align: right
}

.view-account .side-bar .user-info .meta li a {
color: #616670
}

.view-account .side-bar .user-info .meta li.activity {
color: #a2a6af
}

.view-account .side-bar .side-menu {
text-align: center
}

.view-account .side-bar .side-menu .nav {
display: inline-block;
margin: 0 auto
}

.view-account .side-bar .side-menu .nav>li {
font-size: 14px;
margin-bottom: 0;
border-bottom: none;
display: inline-block;
float: left;
margin-right: 15px;
margin-bottom: 15px
}

.view-account .side-bar .side-menu .nav>li:last-child {
margin-right: 0
}

.view-account .side-bar .side-menu .nav>li>a {
display: inline-block;
color: #9499a3;
padding: 5px;
border-bottom: 2px solid transparent
}

.view-account .side-bar .side-menu .nav>li>a:hover {
color: #616670;
background: none
}

.view-account .side-bar .side-menu .nav>li.active a {
color: #40babd;
border-bottom: 2px solid #40babd;
background: none;
border-right: none
}

.theme-2 .view-account .side-bar .side-menu .nav>li.active a {
color: #6dbd63;
border-bottom-color: #6dbd63
}

.theme-3 .view-account .side-bar .side-menu .nav>li.active a {
color: #497cb1;
border-bottom-color: #497cb1
}

.theme-4 .view-account .side-bar .side-menu .nav>li.active a {
color: #ec6952;
border-bottom-color: #ec6952
}

.view-account .side-bar .side-menu .nav>li .icon {
display: block;
font-size: 24px;
margin-bottom: 5px
}

.view-account .content-panel {
padding: 30px
}

.view-account .content-panel .title {
margin-bottom: 15px;
margin-top: 0;
font-size: 18px
}

.view-account .content-panel .fieldset-title {
padding-bottom: 15px;
border-bottom: 1px solid #eaeaf1;
margin-bottom: 30px;
color: #616670;
font-size: 16px
}

.view-account .content-panel .avatar .figure img {
float: right;
width: 64px
}

.view-account .content-panel .content-header-wrapper {
position: relative;
margin-bottom: 30px
}

.view-account .content-panel .content-header-wrapper .actions {
position: absolute;
right: 0;
top: 0
}

.view-account .content-panel .content-utilities {
position: relative;
margin-bottom: 30px
}

.view-account .content-panel .content-utilities .btn-group {
margin-right: 5px;
margin-bottom: 15px
}

.view-account .content-panel .content-utilities .fa {
font-size: 16px;
margin-right: 0
}

.view-account .content-panel .content-utilities .page-nav {
position: absolute;
right: 0;
top: 0
}

.view-account .content-panel .content-utilities .page-nav .btn-group {
margin-bottom: 0
}

.view-account .content-panel .content-utilities .page-nav .indicator {
color: #a2a6af;
margin-right: 5px;
display: inline-block
}

.view-account .content-panel .mails-wrapper .mail-item {
position: relative;
padding: 10px;
border-bottom: 1px solid #f3f3f3;
color: #616670;
overflow: hidden
}

.view-account .content-panel .mails-wrapper .mail-item>div {
float: left
}

.view-account .content-panel .mails-wrapper .mail-item .icheck {
background-color: #fff
}

.view-account .content-panel .mails-wrapper .mail-item:hover {
background: #f9f9fb
}

.view-account .content-panel .mails-wrapper .mail-item:nth-child(even) {
background: #fcfcfd
}

.view-account .content-panel .mails-wrapper .mail-item:nth-child(even):hover {
background: #f9f9fb
}

.view-account .content-panel .mails-wrapper .mail-item a {
color: #616670
}

.view-account .content-panel .mails-wrapper .mail-item a:hover {
color: #494d55;
text-decoration: none
}

.view-account .content-panel .mails-wrapper .mail-item .checkbox-container,
.view-account .content-panel .mails-wrapper .mail-item .star-container {
display: inline-block;
margin-right: 5px
}

.view-account .content-panel .mails-wrapper .mail-item .star-container .fa {
color: #a2a6af;
font-size: 16px;
vertical-align: middle
}

.view-account .content-panel .mails-wrapper .mail-item .star-container .fa.fa-star {
color: #f2b542
}

.view-account .content-panel .mails-wrapper .mail-item .star-container .fa:hover {
color: #868c97
}

.view-account .content-panel .mails-wrapper .mail-item .mail-to {
display: inline-block;
margin-right: 5px;
min-width: 120px
}

.view-account .content-panel .mails-wrapper .mail-item .mail-subject {
display: inline-block;
margin-right: 5px
}

.view-account .content-panel .mails-wrapper .mail-item .mail-subject .label {
margin-right: 5px
}

.view-account .content-panel .mails-wrapper .mail-item .mail-subject .label:last-child {
margin-right: 10px
}

.view-account .content-panel .mails-wrapper .mail-item .mail-subject .label a,
.view-account .content-panel .mails-wrapper .mail-item .mail-subject .label a:hover {
color: #fff
}

.view-account .content-panel .mails-wrapper .mail-item .mail-subject .label-color-1 {
background: #f77b6b
}

.view-account .content-panel .mails-wrapper .mail-item .mail-subject .label-color-2 {
background: #58bbee
}

.view-account .content-panel .mails-wrapper .mail-item .mail-subject .label-color-3 {
background: #f8a13f
}

.view-account .content-panel .mails-wrapper .mail-item .mail-subject .label-color-4 {
background: #ea5395
}

.view-account .content-panel .mails-wrapper .mail-item .mail-subject .label-color-5 {
background: #8a40a7
}

.view-account .content-panel .mails-wrapper .mail-item .time-container {
display: inline-block;
position: absolute;
right: 10px;
top: 10px;
color: #a2a6af;
text-align: left
}

.view-account .content-panel .mails-wrapper .mail-item .time-container .attachment-container {
display: inline-block;
color: #a2a6af;
margin-right: 5px
}

.view-account .content-panel .mails-wrapper .mail-item .time-container .time {
display: inline-block;
text-align: right
}

.view-account .content-panel .mails-wrapper .mail-item .time-container .time.today {
font-weight: 700;
color: #494d55
}

.drive-wrapper {
padding: 15px;
background: #f5f5f5;
overflow: hidden
}

.drive-wrapper .drive-item {
width: 130px;
margin-right: 15px;
display: inline-block;
float: left
}

.drive-wrapper .drive-item:hover {
box-shadow: 0 1px 5px rgba(0, 0, 0, .1);
z-index: 1
}

.drive-wrapper .drive-item-inner {
padding: 15px
}

.drive-wrapper .drive-item-title {
margin-bottom: 15px;
max-width: 100px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis
}

.drive-wrapper .drive-item-title a {
color: #494d55
}

.drive-wrapper .drive-item-title a:hover {
color: #40babd
}

.theme-2 .drive-wrapper .drive-item-title a:hover {
color: #6dbd63
}

.theme-3 .drive-wrapper .drive-item-title a:hover {
color: #497cb1
}

.theme-4 .drive-wrapper .drive-item-title a:hover {
color: #ec6952
}

.drive-wrapper .drive-item-thumb {
width: 100px;
height: 80px;
margin: 0 auto;
color: #616670
}

.drive-wrapper .drive-item-thumb a {
-webkit-opacity: .8;
-moz-opacity: .8;
opacity: .8
}

.drive-wrapper .drive-item-thumb a:hover {
-webkit-opacity: 1;
-moz-opacity: 1;
opacity: 1
}

.drive-wrapper .drive-item-thumb .fa {
display: inline-block;
font-size: 36px;
margin: 0 auto;
margin-top: 20px
}

.drive-wrapper .drive-item-footer .utilities {
margin-bottom: 0
}

.drive-wrapper .drive-item-footer .utilities li:last-child {
padding-right: 0
}

.drive-list-view .name {
width: 60%
}

.drive-list-view .name.truncate {
max-width: 100px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis
}

.drive-list-view .type {
width: 15px
}

.drive-list-view .date,
.drive-list-view .size {
max-width: 60px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis
}

.drive-list-view a {
color: #494d55
}

.drive-list-view a:hover {
color: #40babd
}

.theme-2 .drive-list-view a:hover {
color: #6dbd63
}

.theme-3 .drive-list-view a:hover {
color: #497cb1
}

.theme-4 .drive-list-view a:hover {
color: #ec6952
}

.drive-list-view td.date,
.drive-list-view td.size {
color: #a2a6af
}

@media (max-width:767px) {
.view-account .content-panel .title {
    text-align: center
}
.view-account .side-bar .user-info {
    padding: 0
}
.view-account .side-bar .user-info .img-profile {
    width: 60px;
    height: 60px
}
.view-account .side-bar .user-info .meta li {
    margin-bottom: 5px
}
.view-account .content-panel .content-header-wrapper .actions {
    position: static;
    margin-bottom: 30px
}
.view-account .content-panel {
    padding: 0
}
.view-account .content-panel .content-utilities .page-nav {
    position: static;
    margin-bottom: 15px
}
.drive-wrapper .drive-item {
    width: 100px;
    margin-right: 5px;
    float: none
}
.drive-wrapper .drive-item-thumb {
    width: auto;
    height: 54px
}
.drive-wrapper .drive-item-thumb .fa {
    font-size: 24px;
    padding-top: 0
}
.view-account .content-panel .avatar .figure img {
    float: none;
    margin-bottom: 15px
}
.view-account .file-uploader {
    margin-bottom: 15px
}
.view-account .mail-subject {
    max-width: 100px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis
}
.view-account .content-panel .mails-wrapper .mail-item .time-container {
    position: static
}
.view-account .content-panel .mails-wrapper .mail-item .time-container .time {
    width: auto;
    text-align: left
}
}

@media (min-width:768px) {
.view-account .side-bar .user-info {
    padding: 0;
    padding-bottom: 15px
}
.view-account .mail-subject .subject {
    max-width: 200px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis
}
}

@media (min-width:992px) {
.view-account .content-panel {
    min-height: 800px;
    border-left: 1px solid #f3f3f7;
    margin-left: 200px
}
.view-account .mail-subject .subject {
    max-width: 280px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis
}
.view-account .side-bar {
    position: absolute;
    width: 200px;
    min-height: 600px
}
.view-account .side-bar .user-info {
    margin-bottom: 0;
    border-bottom: none;
    padding: 30px
}
.view-account .side-bar .user-info .img-profile {
    width: 120px;
    height: 120px
}
.view-account .side-bar .side-menu {
    text-align: left
}
.view-account .side-bar .side-menu .nav {
    display: block
}
.view-account .side-bar .side-menu .nav>li {
    display: block;
    float: none;
    font-size: 14px;
    border-bottom: 1px solid #f3f3f7;
    margin-right: 0;
    margin-bottom: 0
}
.view-account .side-bar .side-menu .nav>li>a {
    display: block;
    color: #9499a3;
    padding: 10px 15px;
    padding-left: 30px
}
.view-account .side-bar .side-menu .nav>li>a:hover {
    background: #f9f9fb
}
.view-account .side-bar .side-menu .nav>li.active a {
    background: #f9f9fb;
    border-right: 4px solid #40babd;
    border-bottom: none
}
.theme-2 .view-account .side-bar .side-menu .nav>li.active a {
    border-right-color: #6dbd63
}
.theme-3 .view-account .side-bar .side-menu .nav>li.active a {
    border-right-color: #497cb1
}
.theme-4 .view-account .side-bar .side-menu .nav>li.active a {
    border-right-color: #ec6952
}
.view-account .side-bar .side-menu .nav>li .icon {
    font-size: 24px;
    vertical-align: middle;
    text-align: center;
    width: 40px;
    display: inline-block
}
}
</style>

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">
<div class="container">
    <div class="view-account">
        <section class="module">
            <div class="module-inner">
                <div class="side-bar">
                    <div class="user-info">
                        <img class="img-profile img-circle img-responsive center-block" src="https://bootdey.com/img/Content/avatar/avatar1.png" alt="">
                        <ul class="meta list list-unstyled">
                            <li class="name">Rebecca Sanders
                                <label class="label label-info">UX Designer</label>
                            </li>
                            <li class="email"><a href="#">Rebecca.S@website.com</a></li>
                            <li class="activity">Last logged in: Today at 2:18pm</li>
                        </ul>
                    </div>
            		<nav class="side-menu">
        				<ul class="nav">
        					<li class="active"><a href="#"><span class="fa fa-user"></span> Profile</a></li>
        					<li><a href="#"><span class="fa fa-cog"></span> Settings</a></li>
        					<li><a href="#"><span class="fa fa-credit-card"></span> Billing</a></li>
        					<li><a href="#"><span class="fa fa-envelope"></span> Messages</a></li>
        					
        					<li><a href="user-drive.html"><span class="fa fa-th"></span> Drive</a></li>
        					<li><a href="#"><span class="fa fa-clock-o"></span> Reminders</a></li>
        				</ul>
        			</nav>
                </div>
                <div class="content-panel">
                    <h2 class="title">Profile<span class="pro-label label label-warning">PRO</span></h2>
                    <form class="form-horizontal">
                        <fieldset class="fieldset">
                            <h3 class="fieldset-title">Personal Info</h3>
                            <div class="form-group avatar">
                                <figure class="figure col-md-2 col-sm-3 col-xs-12">
                                    <img class="img-rounded img-responsive" src="https://bootdey.com/img/Content/avatar/avatar1.png" alt="">
                                </figure>
                                <div class="form-inline col-md-10 col-sm-9 col-xs-12">
                                    <input type="file" class="file-uploader pull-left">
                                    <button type="submit" class="btn btn-sm btn-default-alt pull-left">Update Image</button>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-md-2 col-sm-3 col-xs-12 control-label">User Name</label>
                                <div class="col-md-10 col-sm-9 col-xs-12">
                                    <input type="text" class="form-control" value="Rebecca">
                                </div>
                            </div>
        
                            <div class="form-group">
                                <label class="col-md-2 col-sm-3 col-xs-12 control-label">First Name</label>
                                <div class="col-md-10 col-sm-9 col-xs-12">
                                    <input type="text" class="form-control" value="Rebecca">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-md-2 col-sm-3 col-xs-12 control-label">Last Name</label>
                                <div class="col-md-10 col-sm-9 col-xs-12">
                                    <input type="text" class="form-control" value="Sanders">
                                </div>
                            </div>
                        </fieldset>
                        <fieldset class="fieldset">
                            <h3 class="fieldset-title">Contact Info</h3>
                            <div class="form-group">
                                <label class="col-md-2  col-sm-3 col-xs-12 control-label">Email</label>
                                <div class="col-md-10 col-sm-9 col-xs-12">
                                    <input type="email" class="form-control" value="Rebecca@website.com">
                                    <p class="help-block">This is the email </p>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-md-2  col-sm-3 col-xs-12 control-label">Twitter</label>
                                <div class="col-md-10 col-sm-9 col-xs-12">
                                    <input type="text" class="form-control" value="SpeedyBecky">
                                    <p class="help-block">Your twitter username</p>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-md-2  col-sm-3 col-xs-12 control-label">Linkedin</label>
                                <div class="col-md-10 col-sm-9 col-xs-12">
                                    <input type="url" class="form-control" value="https://www.linkedin.com/in/lorem">
                                    <p class="help-block">eg. https://www.linkedin.com/in/yourname</p>
                                </div>
                            </div>
                        </fieldset>
                        <hr>
                        <div class="form-group">
                            <div class="col-md-10 col-sm-9 col-xs-12 col-md-push-2 col-sm-push-3 col-xs-push-0">
                                <input class="btn btn-primary" type="submit" value="Update Profile">
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </section>
    </div>
</div>
function printPDFfromURL(pdf) { 
	var iframe = document.createElement('iframe');
	iframe.style.display = 'none';
	document.body.appendChild(iframe);

	iframe.onload = function() {
		iframe.contentWindow.print();
		setTimeout(()=>{
			iframe.remove()
		}, 60000);
	};
	iframe.src = pdf;
}

//use:
//  printPDFfromURL("http://localhost/path_pdf.pdf");
const { id, version } = await document.interestCohort();
console.log('FLoC ID:', id);
console.log('FLoC version:', version);
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';

// Initialize Apollo Client
const client = new ApolloClient({
  uri: 'http://localhost:4000/GraphiQL',
  cache: new InMemoryCache(),
});

// GraphQL query
const GET_BOOKS = gql`
  query {
  getBook(id: 6) {
    author
    name
  }
  getAllBooks {
    name
  }
  bookInfo(id:"book1"){
  name
  author
  }
}
`;

// Function to fetch data
export async function getBooks() {
  const { data } = await client.query({
    query: GET_BOOKS,
  });
  return data;
}


// GraphQL mutation
const CREATE_BOOKS = gql`
mutation{
  createBook(author: "mohsin khan", name: "allah akbar"){
 author
 name
 id
}
}
`;

// Function to fetch data
export async function getBooks() {
  const { data } = await client.mutate({
    mutation: CREATE_BOOKS,
  });
  return data;
}


// call this in page.js

import { getBooks } from './apollo-client';

const graphql = () => {
  getBooks().then((data) => {
    console.log(data);
  });
}

graphql()
openDatabase(
  // Name
  &#39;mydatabase&#39;,
  // Version
  1,
  // Display name
  &#39;mydatabase&#39;,
  // Estimated size
  5000000,
  // Creation callback
  function (db) {
    db.transaction(
      // Transaction callback
      function (tx) {
        // Execute SQL statement
        tx.executeSql(
          // SQL statement
          &#39;create table rainstorms (mood text, severity int)&#39;,
          // Arguments
          [],
          // Success callback
          function () {
            // Execute SQL statement
            tx.executeSql(
              // SQL statement
              &#39;insert into rainstorms values (?, ?)&#39;,
              // Arguments
              [&#39;somber&#39;, 6],
              // Success callback
              function () {
                // Execute SQL statement
                tx.executeSql(
                  // SQL statement
                  &#39;select * from rainstorms where mood = ?&#39;,
                  // Arguments
                  [&#39;somber&#39;],
                  // Success callback
                  function (tx, res) {
                    // Do something with the result
                    var row = res.rows.item(0);
                    console.log(
                      &#39;rainstorm severity: &#39; +
                        row.severity +
                        &#39;,  my mood: &#39; +
                        row.mood,
                    );
                  },
                );
              },
            );
          },
        );
      },
      // Error callback
      function (err) {
        console.log(&#39;Transaction failed!: &#39; + err);
      },
      // Success callback);
      function () {
        console.log(&#39;Transaction succeeded!&#39;);
      },
    );
  },
);

//HTML

<div id="progress-bar"></div>



//CSS

#progress-bar {
  height: 5px;
  background-color: grey;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
}




//JS

const progressBar = document.getElementById('progress-bar');

window.addEventListener('scroll', function() {
  const scrollTop = window.scrollY;
  const documentHeight = document.documentElement.scrollHeight;
  const windowHeight = window.innerHeight;
  const progress = scrollTop / (documentHeight - windowHeight);
  progressBar.style.width = `${progress * 100}%`;
});

// ParentComponent.js:


import React, { useState } from 'react';
import ChildComponent from './ChildComponent';

const ParentComponent = () => {
  const [parameterFromChild, setParameterFromChild] = useState('');

  // Callback function to receive the parameter from the child
  const handleChildParameter = (parameter) => {
    setParameterFromChild(parameter);
  };

  return (
    <div>
      <h1>Parent Component</h1>
      
      {/* Render ChildComponent and pass the callback function as a prop */}
      <ChildComponent onParameterChange={handleChildParameter} />

      {/* Display the parameter received from the child */}
      {parameterFromChild && (
        <p>Parameter received from child: {parameterFromChild}</p>
      )}
    </div>
  );
};

export default ParentComponent;




//ChildComponent.js:
import React, { useState } from 'react';

const ChildComponent = ({ onParameterChange }) => {
  const [childParameter, setChildParameter] = useState('');

  const handleButtonClick = () => {
    // Update the childParameter state
    setChildParameter('Hello from ChildComponent!');
    
    // Invoke the callback function in the parent with the parameter
    onParameterChange('Hello from ChildComponent!');
  };

  return (
    <div>
      <h2>Child Component</h2>

      <button onClick={handleButtonClick} className="bg-blue-500 text-white px-4 py-2">
        Click me
      </button>
    </div>
  );
};

export default ChildComponent;
Object.defineProperty(String.prototype, "SayHi", {
    value: function SayHi() {
        return "Hi " + this + "!";
    },
    writable: true,
    configurable: true
});

console.log("Charlie".SayHi());
function getNumWords( string ) {

  // Split the string where there is spaces, then count the array length
  return string.split( ' ' ).length
}
function getRandom10CharString() {
    const timestamp = Date.now().toString(36); // Convert timestamp to base 36
    const randomString = Math.random().toString(36).substr(2); // Generate a random base 36 string
    const combinedString = timestamp + randomString; // Combine the two strings
    return combinedString.substr(0, 10); // Return the first 10 characters
}

console.log(getRandom10CharString());
 <ul className='rating'>
    {Array.from({ length: 10 }, (_, i) => (
      <li key={`rating-${i + 1}`}>
        <input
          type='radio'
          id={`num${i + 1}`}
          name='rating'
          value={i + 1}
          onChange={handleChange}
          checked={selected === i + 1}
        />
        <label htmlFor={`num${i + 1}`}>{i + 1}</label>
      </li>
    ))}
  </ul>
// Variable 'search' initialized with the string that will be used for the Google search
let search = "Google * and SEO";

// Replace the first space character in the 'search' string with a plus sign
let searchQ = search.replace(' ', '+').trim();
// Construct the Google search URL using the modified 'searchQ' string and setting the results limit to 1000
let searchUrl = `https://www.google.com/search?q=%22${searchQ}%22&num=1000`;

// URL to a raw list of English stop words from the NLTK library hosted on GitHub
let stopwordsUrl = "https://gist.githubusercontent.com/sebleier/554280/raw/7e0e4a1ce04c2bb7bd41089c9821dbcf6d0c786c/NLTK's%20list%20of%20english%20stopwords";

// Initialize 'stopWords' as a Set to store unique stop words
let stopWords = new Set();

// Asynchronously fetch the list of stopwords from the provided URL
fetch(stopwordsUrl)
  .then(response => {
    // Check if the network response is ok; otherwise throw an error
    if (!response.ok) throw new Error('Network response was not ok');
    return response.text(); // Return the response text (stop words) to be processed
  })
  .then(stopwordsData => {
    // Split the stopwords data by newlines and add each trimmed word to the 'stopWords' Set
    stopwordsData.split(/\n/).forEach(word => stopWords.add(word.trim()));
    return fetch(searchUrl); // Fetch the Google search results next
  })
  .then(response => {
    // Check if the network response is ok; otherwise throw an error
    if (!response.ok) throw new Error('Network response was not ok');
    return response.text(); // Return the search HTML to be processed
  })
  .then(data => {
    // Parse the returned HTML string into a DOM Document object
    let _htmlDoc = new DOMParser().parseFromString(data, "text/html");

    // Define a threshold percentile for word frequency analysis
    const bottomPercentile = 0.98;

    // Process and filter h3 text content from the Google search results
    let processedTexts = Array.from(_htmlDoc.querySelectorAll('h3')).map(h3 => 
      h3.textContent.trim().toLowerCase() // Remove whitespace, convert to lower case
      .replace(/[^\w\s]|_/g, "") // Remove punctuation and underscores
      .split(/\s+/).filter(word => !stopWords.has(word)) // Split into words and filter out stop words
    );

    // Count the frequency of each word across all h3 elements
    let wordCounts = processedTexts.flatMap(words => words).reduce((acc, word) => {
        acc[word] = (acc[word] || 0) + 1; // Increment word count or initialize it to 1
        return acc;
    }, {});

    // Sort the frequencies to determine the threshold for common words
    let sortedCounts = Object.values(wordCounts).sort((a, b) => a - b);
    let thresholdIndex = Math.floor(sortedCounts.length * bottomPercentile);
    let thresholdValue = sortedCounts[thresholdIndex];

    // Filter out the words that are more frequent than the threshold
    let frequentWords = new Set(Object.keys(wordCounts).filter(word => wordCounts[word] > thresholdValue));

    // Reconstruct texts by removing the frequent words and ensure they are more than single words
    let reconstructedText = new Set(processedTexts
      .map(words => words.filter(word => !frequentWords.has(word)).join(' '))
      .filter(text => text.split(' ').length > 1));

    // Log each reconstructed text to the console
    reconstructedText.forEach(text => console.log(text));
  })
  .catch(error => console.error('Fetch error:', error)); // Catch and log any errors during the fetch process
Math.ceil();
Math.floor();
Math.sqrt();

// Array Length
arrayName.length 

// Push & POP

var myList = ["item1","item2","item3","item4"];

myList.push("item4"); // first
myList.unshift("item0"); // Last

var lastElement = myList.pop(); // first
var firstElement = myList.shift(); // last

// Splice & Slice

var list = [
  "saturday", // 0 = -7
  "sunday", // 1 = -6
  "monday", // 2 = -5
  "tuesday", // 3 = -4
  "wednesday", // 4 = -3
  "thursday", // 5 = -2
  "friday", // 6 = -1
];

var portion = list.slice(2, 5);
console.log(portion);

slice(startingIndex, afterEndingIndex)
splice(startingIndex, numberOfElement)

// shallow copy
// deep copy

// Marge Array - concat()

var list1 =[];
var list2 =[];
var list3 =[];

var list4 = list1.concate(list2);
var list = list1.concate(list2,list3);
var list = [].concate(list1,list2,list3);

// Array Sorting - Number

var list = [
  5,4,18,44,9,4,78,1,68,49,71,7,74
];

var length = list.length-1;

for(var i=0; i<length; i++) {
  for(var j=0; j<length; j++) {
    if(list[j] > list[j+1]) {
      [ list[j], list[j+1] ] = [ list[j+1], list[j] ];
    }
  }
}
console.log(list);

// Split and Join

/**
 * /**
 *@NApiVersion 2.1
 *@NScriptType ClientScript
 */
define(["N/format", "N/search"], function (format, search) {
  validateLine = (context) => {
    try {
      var recObj = context.currentRecord;
      var returnValue = true;
      var alertMessage;

      if (context.sublistId == "recmachcustrecord_hcg_employee3") {
        //get current start and end date, and compare with all the lines start and end date wether it line between those date or not
        var CurrentLineIndex = recObj.getCurrentSublistIndex({
          sublistId: "recmachcustrecord_hcg_employee3",
        });

        log.debug("CurrentLineIndex", CurrentLineIndex);

        var currentLineStartDate = recObj.getCurrentSublistValue({
          sublistId: "recmachcustrecord_hcg_employee3",
          fieldId: "custrecord_hcg_start_date6",
        }); //get current start date

        var currentLineEndDate = recObj.getCurrentSublistValue({
          sublistId: "recmachcustrecord_hcg_employee3",
          fieldId: "custrecord_hcg_end_date6",
        }); //get current end date

        log.debug("current currentLineStartDate ", currentLineStartDate + " currentLineEndDate " + currentLineEndDate);

        var currentLineStartDate = new Date(currentLineStartDate);
        var currentLineEndDate = new Date(currentLineEndDate);

        log.debug("current currentLineStartDate ", currentLineStartDate + " currentLineEndDate " + currentLineEndDate);

        var lineCount = recObj.getLineCount({
          sublistId: "recmachcustrecord_hcg_employee3",
        });
        log.debug("lineCount", lineCount);

        for (var i = 0; i < lineCount; i++) {
          if (i != CurrentLineIndex) {
            //current editing index should not be compared. else it would be comparing same index values that would satisfy the condition.
            log.debug("inside loop i=", i);
            var startDateLine = recObj.getSublistValue({
              sublistId: "recmachcustrecord_hcg_employee3",
              fieldId: "custrecord_hcg_start_date6",
              line: i,
            }); //get start date of line

            var endDateLine = recObj.getSublistValue({
              sublistId: "recmachcustrecord_hcg_employee3",
              fieldId: "custrecord_hcg_end_date6",
              line: i,
            }); //get end date of line

            startDateLine = new Date(startDateLine);
            endDateLine = new Date(endDateLine);

            log.debug("startDateLine ", startDateLine + " endDateLine " + endDateLine);

            //if current start date and current end date  is in between the existing startDateLine and endDateLine then give alert
            if (
              (currentLineStartDate >= startDateLine && currentLineEndDate <= endDateLine) || //current start date and current end date lies between any already present start date and end date.
              (currentLineStartDate >= startDateLine && currentLineStartDate <= endDateLine) || //Current start date lies between any already present start and end date.(this means date is overlapping)
              (currentLineEndDate >= startDateLine && currentLineEndDate <= endDateLine) // Current end date lies between any already present start and end date.(this means date is overlapping)
            ) {
              //|| (currentLineEndDate >= startDateLine && currentLineEndDate <= endDateLine)
              log.debug("condition matched");
              returnValue = false;
              alertMessage = "Start Date and End Date should not be between the existing date range";

              alert(alertMessage);

              break;
            }
          }
        }

        return returnValue;
      }
    } catch (error) {
      log.error("error in validate line =", error);
    }
  };

  return {
    validateLine: validateLine,
  };
});
document.onreadystatechange = function () {
  if (document.readyState === "complete") {
    // Here fire whatever you want when all rendered
  }
}
${true ? "this part run when true" : "this part run when false" }
// in UE script, make sure you resolve properly the suitlet external URL:
var suitletURL = url.resolveScript({
        scriptId: 'customscript_your_suitlet_scriptid',
        deploymentId: 'customdeploy_your_suitlet_deploymentid',
        returnExternalUrl: true
});

var response = https.post({
        url : suitletURL,
        headers : myHeaders,
        body : myBody
});
const express = require('express');
const app = express();

// Our first foute
app.get('/home', (request, response, next) => {
  console.log(request);
  response.send('<h1>Welcome Ironhacker. :)</h1>');
});

// Start the server
app.listen(3000, () => console.log('My first app listening on port 3000! '));
// ./src/components/Counter.jsx
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div className="Counter">
      <h2>Counter</h2>

      <p>You clicked {count} times</p>

      <button onClick={() => setCount((prevCount) => prevCount - 1)}> - </button>
      <button onClick={() => setCount((prevCount) => prevCount + 1)}> + </button>
    </div>
  );
}

export default Counter;
// index.js

fetch("https://api.spacexdata.com/v4/launches")
  .then((response) => { 
    return response.json();
  })
  .then((data) => {
    console.log("Parsed response: ", data);
  })
  .catch( (err) => console.log(err));

// 
// index.js

fetch("https://api.spacexdata.com/v4/launches")
  .then((response) => response.json())
  .then((data) => {

  data.forEach((launchObj) => {
    const patchImage = launchObj.links.patch.small;
    const imgElement = document.createElement("img");

    imgElement.setAttribute("src", patchImage);
    imgElement.setAttribute("width", 200);
    document.body.appendChild(imgElement);
  });

}).catch((err) => console.log(err));
function my_scripts() {
     if(!is_admin() {
          wp_deregister_script('jquery');
          wp_enqueue_script('jquery', '//code.jquery.com/jquery-latest.min.js');
     }
}
add_action('wp_enqueue_scripts', 'my_scripts');


//To sort string 
Array.sort((a, b) => ("" + a).localeCompare(b, undefined, { numeric: true }));
//----------------------------------------------------
//To sort numbers
Array.sort((a,b) => a - b)

//----------------------------------------------------
//Convert epoch time to day - month - year
function convertEpochToDMY(epoch) {
    let date = new Date(epoch * 1000); 
    let day = date.getDate();
    let month = date.getMonth() + 1; 
    let year = date.getFullYear();
    day = day < 10 ? '0' + day : day;
    month = month < 10 ? '0' + month : month;

    return day + '-' + month + '-' + year;
}
//----------------------------------------------------
//this takes the start and end epoch val and gives out array of months 
function monthArray(start, end) {
  const arr = [];
  let dt = new Date(start);
  while (dt <= end) {
    arr.push(dt.toLocaleString("en-US", { month: "short" }));
    dt.setMonth(dt.getMonth() + 1);
  }
  return arr;
} // output [Dec, Jan]

//----------------------------------------------
const monthNames = [
  "Jan",
  "Feb",
  "Mar",
  "Apr",
  "May",
  "Jun",
  "Jul",
  "Aug",
  "Sep",
  "Oct",
  "Nov",
  "Dec",
];

//function getMonthNames(startMonth, endMonth) {
//  let result = [];
//  for (let i = startMonth; i <= endMonth; i++) {
//    result.push({ label: monthNames[i - 1], value: i });
//  }
//  return result;
// }
// this takes start and end month nos and gives list range of months
function getMonthNames(startMonth, endMonth) {
  let result = [];
  let month = startMonth;

  while (true) {
    result.push({ label: monthNames[month - 1], value: month });
    if (month === endMonth) {
      break;
    }
    month = (month % 12) + 1;
  }
  const sortedRes = result.sort((a, b) => (a.value - b.value) * -1);

  return sortedRes;
}
//---------------------------------------------------
export function convertToBMK(input) {
  return Math.abs(Number(input)) >= 1.0e9
    ? (Math.abs(Number(input)) / 1.0e9).toFixed(2) + " B"
    : Math.abs(Number(input)) >= 1.0e6
    ? (Math.abs(Number(input)) / 1.0e6).toFixed(2) + " M"
    : Math.abs(Number(input)) >= 1.0e3
    ? (Math.abs(Number(input)) / 1.0e3).toFixed(2) + " K"
    : Math.abs(Number(input));
// To use lazy loading, set a data-lazy attribute
// on your img tags and leave off the src

<img data-lazy="img/lazyfonz1.png"/>

$('.lazy').slick({
  lazyLoad: 'ondemand',
  slidesToShow: 3,
  slidesToScroll: 1
});
				
let now = new Date();
alert( now ); // показывает текущие дату и время
let now = new Date();
alert( now ); // показывает текущие дату и время
var obj = {
  x: 45,
  b: {
    func: function(){alert('a')},
    name: "b"
  },
  a: "prueba"
};

var nw = moveProp(obj, "a", "x"); //-- move 'a' to position of 'x'
console.log(nw, obj);


//--

function moveProp(obj, moveKey, toKey){
  var temp = Object.assign({}, obj)
  var tobj;
  var resp = {};

  tobj = temp[moveKey];
  delete temp[moveKey];
  for(var prop in temp){
    if (prop===toKey) resp[moveKey] = tobj;
    resp[prop] = temp[prop]; 
  }
  return resp;
}
CREATE OR ALTER PROCEDURE DATE_TO_CHAR(TDATE TIMESTAMP, FORMAT VARCHAR(100)) RETURNS (
	RESULT VARCHAR(100)
)
AS
DECLARE SDATE VARCHAR(100);
DECLARE DD VARCHAR(2);
DECLARE MM VARCHAR(2);
DECLARE YY VARCHAR(4);
DECLARE HH VARCHAR(2);
DECLARE MI VARCHAR(2);
DECLARE SS VARCHAR(2);
DECLARE ZZZ VARCHAR(3);
DECLARE XFORMAT VARCHAR(100);
DECLARE AM VARCHAR(2);
BEGIN
	XFORMAT = UPPER(FORMAT);
	SDATE = CAST(TDATE AS VARCHAR(100));
	YY = SUBSTRING(SDATE FROM 1 FOR 4);
	MM = SUBSTRING(SDATE FROM 6 FOR 2);
	DD = SUBSTRING(SDATE FROM 9 FOR 2);
	HH = SUBSTRING(SDATE FROM 12 FOR 2);
	MI = SUBSTRING(SDATE FROM 15 FOR 2);
	SS = SUBSTRING(SDATE FROM 18 FOR 2);
	ZZZ = SUBSTRING(SDATE FROM 21 FOR 3);

	XFORMAT = REPLACE(XFORMAT, 'YYYY', YY);
	XFORMAT = REPLACE(XFORMAT, 'MM', MM);
	XFORMAT = REPLACE(XFORMAT, 'DD', DD);
	XFORMAT = REPLACE(XFORMAT, 'YY', SUBSTRING(YY FROM 3 FOR 2));
	XFORMAT = REPLACE(XFORMAT, 'HH24', HH);

	AM = 'AM';

	IF (HH='12') THEN
	BEGIN
		AM = 'M';
		IF (MI > '00') THEN 
		BEGIN
			AM='PM';
		END
	END
	
	IF (HH='00') THEN 
	BEGIN
		HH='12';
		AM='AM';
	END
	
	IF (HH>'12') THEN
	BEGIN
		HH = TRIM(CAST(CAST(HH AS INTEGER)-12 AS VARCHAR(2)));
		IF (CHAR_LENGTH(HH)<2) THEN 
		BEGIN
			HH='0'||HH;
		END
		AM='PM';
	END
	XFORMAT = REPLACE(XFORMAT, 'HH12', HH);
	XFORMAT = REPLACE(XFORMAT, 'HH', HH);
	XFORMAT = REPLACE(XFORMAT, 'MI', MI);
	XFORMAT = REPLACE(XFORMAT, 'SS', SS);
	XFORMAT = REPLACE(XFORMAT, 'ZZZ', ZZZ);

	RESULT = XFORMAT;
	SUSPEND;
END;
const http = require('http');
const path = require('path');
const fs = require('fs');
const fsPromises = require('fs').promises;
const EventEmitter = require('events');
const logEvents = require('./logEvents'); // custom module

// define the web server port
const PORT = process.env.PORT || 3500;

// event emitter will listen for events and log them to corresponding files
const myEmitter = new EventEmitter();
myEmitter.on('log', (msg, fileName) => logEvents(msg, fileName));


// function that will serve the file (response)
const serveFile = async (filePath, contentType, response) => {
  try {
    const rawData = await fsPromises.readFile(
      filePath, 
      !contentType.includes('image') ? 'utf8' : ''
    );
    const data = contentType === 'application/json' 
      ? JSON.parse(rawData) : rawData;
    response.writeHead(
      filePath.includes('404.html') ? 404 : 200, 
      {'Content-Type': contentType}
    );
    response.end(
      contentType === 'application/json' ? JSON.stringify(data) : data
    );
  } catch (err) {
    console.log(err);
    myEmitter.emit('log', `${err.name}: ${err.message}`, 'errLog.txt');
    response.statusCode = 500; // internal server error
    response.end();
  }
}
// create and configure the server
const server = http.createServer((req, res) => {
  console.log(req.url, req.method);
  myEmitter.emit('log', `${req.url}\t${req.method}`, 'reqLog.txt');

  // store file extension of the request url
  const extension = path.extname(req.url);

  let contentType;

  // manage contentType according to file extension of the url
  switch (extension) {
    case '.css':
      contentType = 'text/css';
      break;
    case '.js':
      contentType = 'text/javascript';
      break;
    case '.json':
      contentType = 'application/json';
      break;
    case '.jpg':
      contentType = 'image/jpeg';
      break;
    case '.png':
      contentType = 'image/png';
      break;
    case '.txt':
      contentType = 'text/plain';
      break;
    default:
      contentType = 'text/html';
  }

  let filePath =
    contentType === 'text/html' && req.url === '/'
      ? path.join(__dirname, 'views', 'index.html')
      : contentType === 'text/html' && req.url.slice(-1) === '/' // if last character in url is '/'
        ? path.join(__dirname, 'views', req.url, 'index.html') // req.url will specify the subdir
        : contentType === 'text/html' // if req.url is not a slash and last char not a slash
          ? path.join(__dirname, 'views', req.url) // just look for url in the views folder
          : path.join(__dirname, req.url); // if url not in views, just use req.url

  // makes .html extension not required int the browser
  if (!extension && req.url.slice(-1) !== '/') filePath += '.html';

  // serve the file if it exists
  const fileExists = fs.existsSync(filePath);
  if (fileExists) {
    serveFile(filePath, contentType, res);
  } 
  // if file does not exist, response will vary
  else {
    switch (path.parse(filePath).base) {
      case 'old-page.html':
        res.writeHead(301, {'Location': 'new-page.html'}); // redirect to new page
        res.end(); // end the response
        break;
      case 'www-page.html':
        res.writeHead(301, {'Location': '/'}); // redirect to root page
        res.end(); // end the response
        break;
      default:
        // serve a 404 response
        serveFile(path.join(__dirname, 'views', '404.html'), 'text/html', res);
    };
    // https://nodejs.org/api/path.html#pathparsepath
  }
});

server.listen(PORT, () => console.log(`Server running and listening on port ${PORT}`));
var HampLoanerAjaxUtils = Class.create();
HampLoanerAjaxUtils.prototype = Object.extendsObject(global.AbstractAjaxProcessor, {
	validateDates: function() {
		var MAX_MONTHS_START_DATE = 3; // Allow reservations with start date within 3 months
		var MAX_MONTHS_RETURN_DATE = 6; // Allow reservations with return date within 6 months from start date

		var startDateUserFormat = this.getParameter('sysparm_startdate');
		var startDate = HAMUtils.getDateInInternalFormat(startDateUserFormat);

		var returnDateUserFormat = this.getParameter('sysparm_returndate');
		var returnDate = HAMUtils.getDateInInternalFormat(returnDateUserFormat);

		var gDate = new GlideDateTime();
		var currentDate = gDate.getLocalDate();
		var res = {};
		var sdt;
		if (!gs.nil(startDate)) {
			sdt = new GlideDateTime(startDate);
			var cdt = new GlideDateTime(currentDate);
			var maxsdt = new GlideDateTime(currentDate);
			maxsdt.addMonthsUTC(MAX_MONTHS_START_DATE);
			if (sdt.before(cdt)) {
				res.isStartDateValid = false;
				res.startDateErrorMsg = gs.getMessage(
					'{0} is not valid. Select a start date on or after current date', [startDate]
				);
			} else if (sdt.after(maxsdt)) {
				res.isStartDateValid = false;
				res.startDateErrorMsg = gs.getMessage(
					'{0} is not valid. Select a start date within {1} months from current date',
					[startDate, String(MAX_MONTHS_START_DATE)]
				);
			} else {
				res.isStartDateValid = true;
			}
		}
		if (!gs.nil(returnDate)) {
			sdt = new GlideDateTime(startDate);
			var rdt = new GlideDateTime(returnDate);
			var maxrdt = new GlideDateTime(startDate);
			maxrdt.addMonthsUTC(MAX_MONTHS_RETURN_DATE);
			if (rdt.onOrBefore(sdt)) {
				res.isReturnDateValid = false;
				res.returnDateErrorMsg = gs.getMessage(
					'{0} is not valid. Select a return date after the selected start date', [returnDate]
				);
			} else if (rdt.after(maxrdt)) {
				res.isReturnDateValid = false;
				res.returnDateErrorMsg = gs.getMessage(
					'{0} is not valid. Select a return date within {1} months from the selected start date',
					[returnDate, String(MAX_MONTHS_RETURN_DATE)]
				);
			} else {
				res.isReturnDateValid = true;
			}
		}
		return JSON.stringify(res);
	},
	isLoanerModelsExist: function () {
		var location = this.getParameter('sysparm_location');
		if (!gs.nil(this.getParameter('sysparm_model'))) {
			var model = this.getParameter('sysparm_model');
			if (new sn_hamp.HampLoanerUtils().isLoanerAssetExist(location, model)) {
				return 'yes';
			}
		}
		if (new sn_hamp.HampLoanerUtils().isLoanerAssetExist(location)) {
			return 'modelNotPresent';
		}
		return 'noLoanerModels';
	},
	isLoanerAssetAvailable: function () {
		var model = this.getParameter('sysparm_model');
		var location = this.getParameter('sysparm_location');
		var startDateUserFormat = this.getParameter('sysparm_start_date');
		var returnDateUserFormat = this.getParameter('sysparm_return_date');
		var leadTimeInDays = this.getParameter('sysparm_lead_time');

		var startDate = HAMUtils.getDateInInternalFormat(startDateUserFormat);
		var returnDate = HAMUtils.getDateInInternalFormat(returnDateUserFormat);

		var isLoanerAssetAvailable = new sn_hamp.HAMAssetReservationUtils().isLoanerAssetAvailableBetweenDates(
			model,
			location,
			startDate,
			returnDate,
			leadTimeInDays
		);

		var message = '';
		if (!isLoanerAssetAvailable) {
			message = gs.getMessage(
				'There are no loaner assets available for this time period. If you choose to submit, your request will join a waitlist.' // eslint-disable-line
			);
		}

		return JSON.stringify({
			isAvailable: isLoanerAssetAvailable,
			message: message,
		});
	},
	getLoanerOrder: function() {
		var sysId = this.getParameter('sysparm_loaner');
		var loanerId;
		var tableName = this.getParameter('sysparm_table');
		if (tableName === sn_hamp.HampLoanerUtils.LOANER_TASK_TABLE) {
			loanerId = new global.GlideQuery(sn_hamp.HampLoanerUtils.LOANER_TASK_TABLE)
				.withAcls()
				.where('sys_id', sysId)
				.select('loaner_order')
				.toArray(1);
			loanerId = loanerId[0].loaner_order;
		} else {
			loanerId = sysId;
		}
		var response = new global.GlideQuery(sn_hamp.HampLoanerUtils.LOANER_ORDER_TABLE)
			.withAcls()
			.where('sys_id', loanerId)
			.selectOne('asset.sys_id', 'asset.display_name', 'asset_stockroom')
			.get();
		return JSON.stringify(response);
	},
	type: 'HampLoanerAjaxUtils',
});
var HampLoanerUtils = Class.create();
HampLoanerUtils.prototype = {
	initialize: function () { },
	getModelsWithLoanerAssets: function (location) {
		var filter;
		var modelsarray = [];
		var assetsGa = new GlideAggregate('alm_asset');
		HampLoanerUtils.addLoanerBaseQuery(assetsGa, location);
		assetsGa.addQuery('install_status', 'NOT IN', HampLoanerUtils.ASSET_IN_USE_STATUSES);
		assetsGa.addQuery('excluded_from_ham', false);
		assetsGa.setGroup(true);
		assetsGa.groupBy('model.sys_id');
		assetsGa.query();
		while (assetsGa.next()) {
			modelsarray.push(assetsGa.getValue('model.sys_id'));
		}
		var loanerOrdersGa = new GlideAggregate(HampLoanerUtils.LOANER_ORDER_TABLE);
		HampLoanerUtils.addInUseFunctioningAssetsQuery(loanerOrdersGa, location, '');
		loanerOrdersGa.setGroup(true);
		loanerOrdersGa.groupBy('model.sys_id');
		loanerOrdersGa.query();
		while (loanerOrdersGa.next()) {
			modelsarray.push(loanerOrdersGa.getValue('model.sys_id'));
		}
		if(HAMUtils.HAS_ONLY_TNI_ENTITLEMENT) {
			var filteredModels = HAMUtils.filterOutNonTNIModels(modelsarray);
			filter = 'sys_idIN' + filteredModels;
		}
		else {
			filter = 'sys_idIN' + modelsarray;
		}
		return filter;
	},
	getAllLoanerAssetsOfStockroom: function (stockroomGr) {
		var assets = [];
		assets = assets.concat(this.getAllLoanerAssetsInStockroom(stockroomGr));
		assets = assets.concat(this.getAllInUseLoanerAssetsOfAStockroom(stockroomGr));
		return assets;
	},
	getAllLoanerAssetsInStockroom: function (stockroomGr) {
		var eamModelExt = HAMUtils.getEAMModelClasses();
		var eamAssetExt = HAMUtils.getEAMAssetClasses();
		var assetsGa = new GlideAggregate('alm_asset');
		assetsGa.addQuery('asset_function', 'loaner');
		assetsGa.addQuery('stockroom', stockroomGr.getUniqueValue());
		// Exclude EAM assets and EAM models
		assetsGa.addQuery('model.sys_class_name', 'NOT IN', eamModelExt);
		assetsGa.addQuery('sys_class_name', 'NOT IN', eamAssetExt);
		assetsGa.setGroup(true);
		assetsGa.groupBy('sys_id');
		assetsGa.query();

		var assetsarray = [];
		while (assetsGa.next()) {
			assetsarray.push(assetsGa.getValue('sys_id'));
		}
		return assetsarray;
	},
	getAllInUseLoanerAssetsOfAStockroom: function (stockroomGr) {
		var loanerOrdersGa = new GlideAggregate(HampLoanerUtils.LOANER_ORDER_TABLE);
		loanerOrdersGa.addQuery('asset_stockroom', stockroomGr.getUniqueValue());
		loanerOrdersGa.addQuery('asset.install_status', HAMConstants.ASSET_STATUSES.IN_USE);
		loanerOrdersGa.addQuery('asset.asset_function', 'loaner');
		loanerOrdersGa.addQuery('stage', HampLoanerUtils.STAGE_DEPLOYED);
		loanerOrdersGa.setGroup(true);
		loanerOrdersGa.groupBy('asset.sys_id');
		loanerOrdersGa.query();

		var assetsarray = [];
		while (loanerOrdersGa.next()) {
			assetsarray.push(loanerOrdersGa.getValue('asset.sys_id'));
		}
		return assetsarray;
	},
	getFunctioningAssets: function (location, model) {
		var functioningAssets = [];
		functioningAssets = functioningAssets.concat(this.getInStockFunctioningAssets(location, model));
		functioningAssets = functioningAssets.concat(this.getInUseFunctioningAssets(location, model));
		return functioningAssets;
	},
	getInStockFunctioningAssets: function (location, model) {
		var assetsGa = new GlideAggregate('alm_asset');
		HampLoanerUtils.addLoanerBaseQuery(assetsGa, location, model);
		HampLoanerUtils.addInStockFunctioningAssetsQuery(assetsGa);
		assetsGa.setGroup(true);
		assetsGa.groupBy('sys_id');
		assetsGa.query();

		var assetsarray = [];
		while (assetsGa.next()) {
			assetsarray.push(assetsGa.getValue('sys_id'));
		}
		return assetsarray;
	},
	getInUseFunctioningAssets: function (location, model) {
		var loanerOrdersGa = new GlideAggregate(HampLoanerUtils.LOANER_ORDER_TABLE);
		HampLoanerUtils.addInUseFunctioningAssetsQuery(loanerOrdersGa, location, model);
		loanerOrdersGa.setGroup(true);
		loanerOrdersGa.groupBy('asset.sys_id');
		loanerOrdersGa.query();

		var assetsarray = [];
		while (loanerOrdersGa.next()) {
			assetsarray.push(loanerOrdersGa.getValue('asset.sys_id'));
		}
		return assetsarray;
	},
	getActiveAssetAllocations: function (location, model, startDate, returnDate, leadTime, forLoanerOrder) {
		var loanerOrdersGa = new GlideAggregate(HampLoanerUtils.LOANER_ORDER_TABLE);
		loanerOrdersGa.addQuery('location', location);
		loanerOrdersGa.addQuery('model', model);
		if (forLoanerOrder) {
			loanerOrdersGa.addQuery('sys_id', '!=', forLoanerOrder);
		}

		HampLoanerUtils.addLoanerOrdersOverlapQuery(loanerOrdersGa, startDate, returnDate, leadTime);
		HampLoanerUtils.addDomainFilterQuery(loanerOrdersGa);

		var activeStages = [HampLoanerUtils.STAGE_NEW, HampLoanerUtils.STAGE_PREPARE, HampLoanerUtils.STAGE_DEPLOYED];
		loanerOrdersGa.addQuery('stage', activeStages);

		loanerOrdersGa.setGroup(true);
		loanerOrdersGa.groupBy('asset.sys_id');
		loanerOrdersGa.query();

		var assetsarray = [];
		while (loanerOrdersGa.next()) {
			assetsarray.push(loanerOrdersGa.getValue('asset.sys_id'));
		}
		return assetsarray;
	},
	getAssetsAvailableToAllocate: function (location, model, startDate, returnDate, leadTime, forLoanerOrder) {
		var functioningAssets = this.getFunctioningAssets(location, model);
		// eslint-disable-next-line max-len
		var activeAllocations = this.getActiveAssetAllocations(location, model, startDate, returnDate, leadTime, forLoanerOrder);
		var availableAssets = [];
		for (var i = 0; i < functioningAssets.length; i++) {
			if (activeAllocations.indexOf(functioningAssets[i]) === -1) {
				availableAssets.push(functioningAssets[i]);
			}
		}
		return availableAssets;
	},
	getLoanerAssets: function (current) {
		var loanerOrderGr = null;
		if (current.getTableName() === HampLoanerUtils.LOANER_ORDER_TABLE) {
			loanerOrderGr = current;
		} else if (current.getTableName() === HampLoanerUtils.LOANER_TASK_TABLE) {
			loanerOrderGr = current.loaner_order;
		}
		if (gs.nil(loanerOrderGr)) {
			return '';
		}

		var location = loanerOrderGr.location;
		var model = loanerOrderGr.model;
		var startDate = loanerOrderGr.start_date;
		var returnDate = loanerOrderGr.return_date;
		var leadTime = loanerOrderGr.lead_time;

		var assetsarray = this.getAssetsAvailableToAllocate(location, model, startDate, returnDate, leadTime);
		var filter = 'sys_idIN' + assetsarray;
		return filter;
	},
	updateAssetPrepared: function (current) {
		new global.GlideQuery('sn_hamp_loaner_asset_order')
			.where('sys_id', current.loaner_order)
			.update({
				asset_prepared: true,
			});
	},
	updateAssetStockroomOnLoanerOrder: function (loanerTaskGr) {
		var assetStockroom = loanerTaskGr.loaner_order.asset.stockroom;
		if (!gs.nil(assetStockroom)) {
			new global.GlideQuery(HampLoanerUtils.LOANER_ORDER_TABLE)
				.where('sys_id', loanerTaskGr.loaner_order)
				.update({
					asset_stockroom: assetStockroom,
				});
		}
	},
	updateReturnedOn: function (current) {
		var gDate = new GlideDateTime();
		new global.GlideQuery('sn_hamp_loaner_asset_order')
			.where('sys_id', current.loaner_order)
			.update({
				returned_on: gDate.getLocalDate(),
			});
	},
	updateAsset: function (assetId, assetData, isConsumable) {
		if (isConsumable) { delete assetData.work_notes; }

		new global.GlideQuery('alm_asset')
			.where('sys_id', assetId)
			.update(assetData);

		if (assetData.work_notes) {
			var assetGr = HAMUtils.getAsGlideRecord(HAMConstants.ALM_ASSET_TABLE, assetId);
			assetGr.work_notes = assetData.work_notes;
			assetGr.update();
		}
	},
	cancelLoanerOrder: function (loanerOrderId) {
		var isAssetDeployed = new global.GlideQuery(HampLoanerUtils.LOANER_TASK_TABLE)
			.where('loaner_order', loanerOrderId)
			.where('task_name', 'deploy')
			.where('state', 3)
			.selectOne()
			.isPresent();
		if (isAssetDeployed) {
			gs.addErrorMessage(gs.getMessage('Loaner asset order cannot be cancelled once the asset is deployed'));
			return;
		}

		var loanerOrderGr = new global.GlideQuery('sn_hamp_loaner_asset_order')
			.where('sys_id', loanerOrderId)
			.toGlideRecord();
		loanerOrderGr.query();
		loanerOrderGr.next();
		loanerOrderGr.stage = 'cancelled';
		loanerOrderGr.work_notes = gs.getMessage('Loaner order is cancelled by {0}', gs.getUserDisplayName());
		loanerOrderGr.update();

		new global.GlideQuery('sn_hamp_loaner_asset_task')
			.where('loaner_order', loanerOrderId)
			.where('active', true)
			.updateMultiple({
				state: 4,
			});
	},
	triggerLoanerFlow: function (loanerOrder) {
		var defaultFlow = 'sn_hamp.loaner_asset_request_flow';
		var LOANER_DECISION_ID = 'f9a23e38739310107e88ef66fbf6a7db';
		var decisionInputs = {};
		decisionInputs.loaner_asset_order = loanerOrder.sys_id;
		var flow = HAMUtils.getFlowFromDecisionTable(LOANER_DECISION_ID, decisionInputs, defaultFlow);
		var inputs = {};
		inputs.current = loanerOrder;
		inputs.table_name = 'sn_hamp_loaner_asset_order';
		var flowContextID = sn_hamp.HAMUtils.triggerFlowAsyncronously(flow, inputs);
		if (!gs.nil(flowContextID)) {
			new global.GlideQuery(HampLoanerUtils.LOANER_ORDER_TABLE)
				.where('sys_id', loanerOrder.sys_id)
				.update({
					flow_context: flowContextID,
				});
		}
	},
	earlyReturnLoanerAsset: function (loanerOrder, loanerAsset, returnedOn, stockroom, isAssetFunctional) {
		var loanerGq = new global.GlideQuery(HampLoanerUtils.LOANER_ORDER_TABLE)
			.where('sys_id', loanerOrder);
		var loanerGr = loanerGq.toGlideRecord();
		loanerGr.query();
		loanerGr.next();
		var returnedOnInternalFormat = HAMUtils.getDateInInternalFormat(returnedOn);
		loanerGq.update({
			asset_returned: 'Y',
			returned_on: returnedOnInternalFormat,
			is_asset_functional: isAssetFunctional,
		});
		var reclaimTaskId;
		new global.GlideQuery(HampLoanerUtils.LOANER_TASK_TABLE)
			.where('loaner_order', loanerOrder)
			.where('task_name', 'reclaim')
			.selectOne('sys_id')
			.ifPresent(function (task) {
				reclaimTaskId = task.sys_id;
			});
		if (!gs.nil(reclaimTaskId)) {
			new global.GlideQuery(HampLoanerUtils.LOANER_TASK_TABLE)
				.where('sys_id', reclaimTaskId)
				.update({
					state: 3,
					assigned_to: gs.getUserID(),
					return_stockroom: stockroom,
				});
		} else {
			var loanerTaskGr = new GlideRecord('sn_hamp_loaner_asset_task');
			loanerTaskGr.initialize();
			loanerTaskGr.setValue('parent', loanerOrder);
			loanerTaskGr.setValue('loaner_order', loanerOrder);
			loanerTaskGr.setValue('task_name', 'reclaim');
			loanerTaskGr.setValue('state', 3);
			loanerTaskGr.setValue('assigned_to', gs.getUserID());
			loanerTaskGr.setValue('return_stockroom', stockroom);
			loanerTaskGr.setValue('short_description', gs.getMessage('Reclaim loaner asset from user'));
			// eslint-disable-next-line max-len
			loanerTaskGr.setValue('description', gs.getMessage('Reclaim loaner asset from user and return to loaner pool'));
			reclaimTaskId = loanerTaskGr.insert();
		}

		var reclaimLoanerTaskGr = HAMUtils.getAsGlideRecord(HampLoanerUtils.LOANER_TASK_TABLE, reclaimTaskId);
		this.updateAssetOnReturn(reclaimLoanerTaskGr);
	},
	updateAssetOnReturn: function (loanerTaskGr /* reclaim task */) {
		var returnStockroom = String(loanerTaskGr.return_stockroom);

		var loanerOrderGr = loanerTaskGr.loaner_order;
		var isAssetFunctional = String(loanerOrderGr.is_asset_functional);

		var loanerAssetGr = loanerOrderGr.asset;
		var loanerAssetID = loanerAssetGr.sys_id;

		var assetUpdateJSON = {};
		assetUpdateJSON = {
			install_status: parseInt(HAMConstants.ASSET_STATUSES.IN_STOCK, 10),
			substatus: HAMConstants.ASSET_SUB_STATUSES.AVAILABLE,
			stockroom: returnStockroom,
			reserved_for: null,
			assigned_to: null,
			assigned: null,
			install_date: null,
			managed_by: null,
		};

		var msgParams = [loanerAssetGr.getDisplayValue(), loanerTaskGr.getDisplayValue()];
		if (isAssetFunctional === 'N') {
			assetUpdateJSON.substatus = HAMConstants.ASSET_SUB_STATUSES.PENDING_REPAIR;
			// eslint-disable-next-line max-len
			assetUpdateJSON.work_notes = gs.getMessage('Asset {0} updated to state In stock and substate Pending repair as part of task {1}', msgParams);
		} else {
			// eslint-disable-next-line max-len
			assetUpdateJSON.work_notes = gs.getMessage('Asset {0} updated to state In stock and substate Available as part of task {1}', msgParams);
		}

		// Check if the asset is part of another loaner order
		var otherLoanerOrder = HampLoanerUtils.getAnotherLoanerOrderWithAsset(loanerAssetID, loanerOrderGr);

		// If asset is part of another loaner orders, then do not clear process fields
		// as it would result in consumable records getting merged.
		if (gs.nil(otherLoanerOrder)) {
			assetUpdateJSON.process_table = null;
			assetUpdateJSON.process_id = null;
		}

		this.updateAsset(loanerAssetID, assetUpdateJSON, HAMUtils.isConsumableClassAsset(loanerAssetGr));

		// If not part of another loaner order, return. Else stamp other loaner order details on asset
		if (gs.nil(otherLoanerOrder)) { return; }

		var otherLoanerOrderStage = String(otherLoanerOrder.stage);
		if (otherLoanerOrderStage === HampLoanerUtils.STAGE_NEW
			|| otherLoanerOrderStage === HampLoanerUtils.STAGE_PREPARE) {
			assetUpdateJSON = {
				install_status: parseInt(HAMConstants.ASSET_STATUSES.IN_STOCK, 10),
				substatus: HAMConstants.ASSET_SUB_STATUSES.RESERVED,
				stockroom: returnStockroom,
				reserved_for: String(otherLoanerOrder.requested_for),
				assigned_to: null,
				assigned: null,
				install_date: null,
				managed_by: null,
				process_table: otherLoanerOrder.getTableName(),
				process_id: otherLoanerOrder.getUniqueValue(),
			};

			if (isAssetFunctional === 'N') {
				assetUpdateJSON.substatus = HAMConstants.ASSET_SUB_STATUSES.PENDING_REPAIR;
			} else {
				assetUpdateJSON.work_notes = this.getAssetReservedWorkNote(loanerAssetGr, otherLoanerOrder);
			}

			this.updateAsset(loanerAssetID, assetUpdateJSON, HAMUtils.isConsumableClassAsset(loanerAssetGr));
		}
	},
	updateAssetOnPrepareCompletion: function (prepareTaskGr) {
		var loanerOrderGr = prepareTaskGr.loaner_order;
		var requestedFor = String(loanerOrderGr.requested_for);

		var loanerAssetGr = loanerOrderGr.asset;
		var loanerAssetID = String(loanerAssetGr.sys_id);

		var msgParams = [loanerAssetGr.getDisplayValue(), prepareTaskGr.getDisplayValue()];
		// eslint-disable-next-line max-len
		var preparedWorkNote = gs.getMessage('Asset {0} updated to state In stock and substate Pending install as part of task {1}', msgParams);

		var assetUpdateJSON = {
			install_status: parseInt(HAMConstants.ASSET_STATUSES.IN_STOCK, 10),
			substatus: HAMConstants.ASSET_SUB_STATUSES.PENDING_INSTALL,
			reserved_for: requestedFor,
			process_table: HampLoanerUtils.LOANER_ORDER_TABLE,
			process_id: String(loanerOrderGr.sys_id),
			work_notes: preparedWorkNote,
		};

		this.updateAsset(loanerAssetID, assetUpdateJSON, HAMUtils.isConsumableClassAsset(loanerAssetGr));
	},
	updateAssetOnDeployCompletion: function (deployTaskGr) {
		var loanerOrderGr = deployTaskGr.loaner_order;

		var loanerAssetGr = loanerOrderGr.asset;
		var loanerAssetID = String(loanerAssetGr.sys_id);

		var msgParams = [loanerAssetGr.getDisplayValue(), deployTaskGr.getDisplayValue()];
		var deployedWorkNote = gs.getMessage('Asset {0} updated to state In Use as part of task {1}', msgParams);

		var installStatus;
		if (HAMUtils.isConsumableClassAsset(loanerAssetGr)) {
			installStatus = parseInt(HAMConstants.ASSET_STATUSES.CONSUMED, 10);
		} else {
			installStatus = parseInt(HAMConstants.ASSET_STATUSES.IN_USE, 10);
		}

		var timeNow = new GlideDateTime().toString();
		var assetUpdateJSON = {
			install_status: installStatus,
			substatus: null,
			location: String(loanerOrderGr.location),
			work_notes: deployedWorkNote,
			assigned: timeNow,
			install_date: timeNow,
			process_table: HampLoanerUtils.LOANER_ORDER_TABLE,
			process_id: String(loanerOrderGr.sys_id),
		};

		if (String(loanerOrderGr.request_type) !== HampLoanerUtils.LOANER_ORDER_TYPE_THIRD_PARTY) {
			assetUpdateJSON.assigned_to = String(loanerOrderGr.requested_for);
		}

		if (String(loanerOrderGr.request_type) === HampLoanerUtils.LOANER_ORDER_TYPE_THIRD_PARTY) {
			// Explictily marking null to overcome glidequery issue.
			// current.reserved_for.nil() returns false even though reserved_for is null
			assetUpdateJSON.managed_by = String(loanerOrderGr.opened_by);
			assetUpdateJSON.assigned_to = null;
			assetUpdateJSON.reserved_for = null;
		}

		this.updateAsset(loanerAssetID, assetUpdateJSON, HAMUtils.isConsumableClassAsset(loanerAssetGr));
	},
	canOrderBeCancelled: function (loanerOrder) {
		if (gs.hasRole('inventory_user')) {
			return true;
		}
		var canCancel = false;
		new global.GlideQuery('sn_hamp_loaner_asset_order')
			.where('sys_id', loanerOrder)
			.selectOne('opened_by', 'requested_for')
			.ifPresent(function (rec) {
				if (rec.opened_by === gs.getUserID() || rec.requested_for === gs.getUserID()) {
					canCancel = true;
				}
			});
		return canCancel;
	},
	isAssetAvailable: function (current) {
		var loanerOrderGr;
		if (current.getTableName() === HampLoanerUtils.LOANER_ORDER_TABLE) {
			loanerOrderGr = current;
		} else if (current.getTableName() === HampLoanerUtils.LOANER_TASK_TABLE) {
			loanerOrderGr = current.loaner_order;
		}
		var selectedAsset = String(loanerOrderGr.asset);
		var availableAssets = this.getAssetsAvailableToAllocate(
			loanerOrderGr.location,
			loanerOrderGr.model,
			loanerOrderGr.start_date,
			loanerOrderGr.return_date,
			loanerOrderGr.lead_time,
			loanerOrderGr.sys_id
		);
		if (availableAssets.indexOf(selectedAsset) !== -1) {
			return true;
		}
		return false;
	},
	canAccess: function (loanerOrder) {
		var res = new global.GlideQuery(HampLoanerUtils.LOANER_TASK_TABLE)
			.where('loaner_order', loanerOrder.sys_id)
			.where('assigned_to', gs.getUserID())
			.selectOne()
			.isPresent();
		return res;
	},
	isLoanerAssetExist: function (location, model) {
		var assets = new GlideRecord('alm_asset');
		HampLoanerUtils.addLoanerBaseQuery(assets, location, model);
		assets.addQuery('install_status', 'NOT IN', HampLoanerUtils.ASSET_IN_USE_STATUSES);
		assets.addQuery('excluded_from_ham', false)
		assets.query();
		if (assets.hasNext()) {
			return true;
		}

		var loanerOrdersGa = new GlideAggregate(HampLoanerUtils.LOANER_ORDER_TABLE);
		HampLoanerUtils.addInUseFunctioningAssetsQuery(loanerOrdersGa, location, '');
		loanerOrdersGa.query();
		return loanerOrdersGa.hasNext();
	},
	getFunctioningLoanerAssetsCount: function (location, model) {
		var inStockFunctioningAssets = this.getInStockFunctioningLoanerAssetsCount(location, model);
		var inUseFunctioningAssets = this.getInUseFunctioningLoanerAssetsCount(location, model);
		return (inStockFunctioningAssets + inUseFunctioningAssets);
	},
	getInStockFunctioningLoanerAssetsCount: function (location, model) {
		var assetsGa = new GlideAggregate('alm_asset');
		HampLoanerUtils.addLoanerBaseQuery(assetsGa, location, model);
		HampLoanerUtils.addInStockFunctioningAssetsQuery(assetsGa);
		assetsGa.addQuery('excluded_from_ham', false);
		assetsGa.addAggregate('SUM', 'quantity');
		assetsGa.groupBy('model');
		assetsGa.query();
		if (assetsGa.next()) {
			return (parseInt(assetsGa.getAggregate('SUM', 'quantity'), 10));
		}
		return 0;
	},
	getInUseFunctioningLoanerAssetsCount: function (location, model) {
		var loanerOrdersGa = new GlideAggregate(HampLoanerUtils.LOANER_ORDER_TABLE);
		HampLoanerUtils.addInUseFunctioningAssetsQuery(loanerOrdersGa, location, model);
		loanerOrdersGa.addAggregate('COUNT');
		loanerOrdersGa.query();
		if (loanerOrdersGa.next()) {
			return (parseInt(loanerOrdersGa.getAggregate('COUNT'), 10));
		}
		return 0;
	},
	isWaitlistedEditable: function (loanerOrderGr) {
		var stage = loanerOrderGr.getValue('stage');
		if (stage === HampLoanerUtils.STAGE_NEW) {
			return true;
		}
		if (stage === HampLoanerUtils.STAGE_PREPARE) {
			var prepareTask = new global.GlideQuery(HampLoanerUtils.LOANER_TASK_TABLE)
				.where('loaner_order', loanerOrderGr.getUniqueValue())
				.where('task_name', HampLoanerUtils.TASK_PREPARE)
				.select('state')
				.toArray(1);
			if (prepareTask[0] && parseInt(prepareTask[0].state, 10) === HampLoanerUtils.TASK_CLOSED_COMPLETE) {
				return false;
			}
			return true;
		}
		return false;
	},
	isPrepareTaskClosedComplete: function (loanerOrderGr) {
		var stage = loanerOrderGr.getValue('stage');
		if (stage === HampLoanerUtils.STAGE_NEW) {
			return false;
		}
		var prepareTask = new global.GlideQuery(HampLoanerUtils.LOANER_TASK_TABLE)
			.where('loaner_order', loanerOrderGr.getUniqueValue())
			.where('task_name', HampLoanerUtils.TASK_PREPARE)
			.select('state')
			.toArray(1);
		if (prepareTask[0] && parseInt(prepareTask[0].state, 10) === HampLoanerUtils.TASK_CLOSED_COMPLETE) {
			return true;
		}
		return false;
	},
	isLoanerFieldEditable: function (loanerOrderGr, field) {
		switch (field) {
		case 'asset':
			return !this.isPrepareTaskClosedComplete(loanerOrderGr);
		case 'model':
			return !this.isPrepareTaskClosedComplete(loanerOrderGr);
		default:
			return true;
		}
	},
	getAssetReservedWorkNote: function (assetGr, loanerOrderGr) {
		var msgParams = [assetGr.getDisplayValue(), loanerOrderGr.getDisplayValue()];
		// eslint-disable-next-line max-len
		var workNote = gs.getMessage('Asset {0} updated to state In stock and substate Reserved due to selection on loaner asset order {1}', msgParams);
		return workNote;
	},
	compareOrdersStartDates: function (loanerOrder1, loanerOrder2) {
		return HAMUtils.compareDates(String(loanerOrder1.start_date), String(loanerOrder2.start_date));
	},
	setAssetStatusOnSelection: function (loanerOrderGr, selectedAssetGr) {
		var selectedAssetID = selectedAssetGr.sys_id.toString();
		var selectionWorkNote = this.getAssetReservedWorkNote(selectedAssetGr, loanerOrderGr);

		var otherLoanerOrder;
		var assetUpdateJSON = {};

		if (HAMUtils.isConsumableClassAsset(selectedAssetGr)) {
			var processedConsumableID = HampLoanerUtils.splitConsumableOnLoanerOrder(loanerOrderGr);
			if (selectedAssetID !== processedConsumableID) {
				// A new consumable with required attributes record is created in this case.
				loanerOrderGr.setValue('asset', processedConsumableID);
			}
		}
		var setAssetID = loanerOrderGr.getValue('asset');

		// Check if selected asset is already part of another loaner order.
		otherLoanerOrder = HampLoanerUtils.getAnotherLoanerOrderWithAsset(selectedAssetID, loanerOrderGr);

		// If it is part of another loaner order, but the other loaner order start date comes first, do nothing.
		// Else update the consumable with incoming loaner asset order details.
		if (!gs.nil(otherLoanerOrder) && this.compareOrdersStartDates(loanerOrderGr, otherLoanerOrder) !== '>') {
			return;
		}

		assetUpdateJSON = {
			install_status: parseInt(HAMConstants.ASSET_STATUSES.IN_STOCK, 10),
			substatus: HAMConstants.ASSET_SUB_STATUSES.RESERVED,
			reserved_for: String(loanerOrderGr.requested_for),
			process_table: HampLoanerUtils.LOANER_ORDER_TABLE,
			process_id: loanerOrderGr.getUniqueValue(),
			work_notes: selectionWorkNote,
		};
		this.updateAsset(setAssetID, assetUpdateJSON, HAMUtils.isConsumableClassAsset(selectedAssetGr));
	},
	setAssetStatusOnRemoval: function (loanerOrderGr, assetGr, isCancelledOrDeleted) {
		// If loaner asset orders not in New, Prepare are deleted, do nothing.
		if (isCancelledOrDeleted === HampLoanerUtils.LOANER_ORDER_ACTION_DELETED) {
			var loanerOrderStage = String(loanerOrderGr.stage);
			if (!((loanerOrderStage === HampLoanerUtils.STAGE_NEW)
				|| (loanerOrderStage === HampLoanerUtils.STAGE_PREPARE))) { return; }
		}

		var assetId = assetGr.sys_id.toString();
		var otherLoanerOrderStage;
		var dateComp;

		// If the asset is removed from the loaner asset order which is not the one with earliest start date
		// do nothing
		var otherLoanerOrder = HampLoanerUtils.getAnotherLoanerOrderWithAsset(assetId, loanerOrderGr);
		if (!gs.nil(otherLoanerOrder)) {
			otherLoanerOrderStage = String(otherLoanerOrder.stage);
			if (otherLoanerOrderStage === HampLoanerUtils.STAGE_DEPLOYED) { return; }

			dateComp = this.compareOrdersStartDates(loanerOrderGr, otherLoanerOrder);
			if (dateComp === '<' && (otherLoanerOrderStage === HampLoanerUtils.STAGE_NEW
				|| otherLoanerOrderStage === HampLoanerUtils.STAGE_PREPARE)) { return; }
		}

		// If the asset is removed from the loaner asset order with the earliest start date
		// move the asset to a state of available
		var msgParams = [assetGr.getDisplayValue(), loanerOrderGr.getDisplayValue()];
		var removalWorkNote;
		if (isCancelledOrDeleted === HampLoanerUtils.LOANER_ORDER_ACTION_CANCELLED) {
			// eslint-disable-next-line max-len
			removalWorkNote = gs.getMessage('Asset {0} updated to state In stock and substate Available due to cancellation of loaner asset order {1}', msgParams);
		} else if (isCancelledOrDeleted === HampLoanerUtils.LOANER_ORDER_ACTION_DELETED) {
			// eslint-disable-next-line max-len
			removalWorkNote = gs.getMessage('Asset {0} updated to state In stock and substate Available due to deletion of loaner asset order {1}', msgParams);
		} else {
			// eslint-disable-next-line max-len
			removalWorkNote = gs.getMessage('Asset {0} updated to state In stock and substate Available due to removal from loaner asset order {1}', msgParams);
		}

		var assetUpdateJSON = {};
		assetUpdateJSON = {
			install_status: parseInt(HAMConstants.ASSET_STATUSES.IN_STOCK, 10),
			substatus: HAMConstants.ASSET_SUB_STATUSES.AVAILABLE,
			reserved_for: null,
			process_table: null,
			process_id: null,
			work_notes: removalWorkNote,
		};

		this.updateAsset(assetId, assetUpdateJSON, HAMUtils.isConsumableClassAsset(assetGr));

		// If the asset is part of another active loaner order with a greater start date,
		// set the asset as reserved for that order.
		if (!gs.nil(otherLoanerOrder)) {
			otherLoanerOrderStage = String(otherLoanerOrder.stage);
			if (dateComp === '>' && (otherLoanerOrderStage === HampLoanerUtils.STAGE_NEW
				|| otherLoanerOrderStage === HampLoanerUtils.STAGE_PREPARE)) {
				var selectionWorkNote = this.getAssetReservedWorkNote(assetGr, otherLoanerOrder);
				assetUpdateJSON = {
					install_status: parseInt(HAMConstants.ASSET_STATUSES.IN_STOCK, 10),
					substatus: HAMConstants.ASSET_SUB_STATUSES.RESERVED,
					reserved_for: String(otherLoanerOrder.requested_for),
					work_notes: selectionWorkNote,
					process_table: otherLoanerOrder.getTableName(),
					process_id: otherLoanerOrder.getUniqueValue(),
				};
				this.updateAsset(assetId, assetUpdateJSON, HAMUtils.isConsumableClassAsset(assetGr));
			}
		}
	},
	showLoanerAssetOrdersListOnAsset: function (assetGr) {
		/** ***********************************************************************************
			* Hiding loaner order related list for consumables if they are not supported by process columns
			*********************************************************************************** */
		if (HAMUtils.isConsumableClassAsset(assetGr) && !HAMUtils.isConsumablesSupportedByProcess()) {
			return false;
		}
		if (assetGr.getValue('asset_function') === HAMConstants.ASSET_FUNCTION.LOANER) {
			return true;
		}

		var showLoanerAssetOrders = false;
		if (HAMUtils.isConsumableClassAsset(assetGr)) {
			/** ***********************************************************************************
			* Consumable history can only be got in conjunction with install status and stockroom.
			*********************************************************************************** */
			if (assetGr.getValue('install_status') === HAMConstants.ASSET_STATUSES.IN_STOCK) {
				showLoanerAssetOrders = new global.GlideQuery(HampLoanerUtils.LOANER_ORDER_TABLE)
					.whereNotNull('asset')
					.where('model', assetGr.getValue('model'))
					.where('asset_stockroom', assetGr.getValue('stockroom'))
					.selectOne()
					.isPresent();
			}
			return showLoanerAssetOrders;
		}

		/** ***********************************************************************************
		* In case of Asset, Hardware, Facility, Bundle class, check if record is in orders.
		*********************************************************************************** */
		showLoanerAssetOrders = new global.GlideQuery(HampLoanerUtils.LOANER_ORDER_TABLE)
			.where('asset', assetGr.getUniqueValue())
			.selectOne()
			.isPresent();
		return showLoanerAssetOrders;
	},
	type: 'HampLoanerUtils',
};
HampLoanerUtils.addDomainFilterQuery = function (records) {
	if (global.ModelUtils.isDomainSeparationEnabled()) {
		var domainID = new global.AssetManagementBaseJob().getCurrentDomainSysId();
		records.addQuery('sys_domain', domainID);
	}
};
HampLoanerUtils.getLoanerCommonBaseQuery = function (location, model) {
	var assets = new GlideAggregate('alm_asset');
	assets.addQuery('asset_function', 'loaner');
	if (!(HAMUtils.isConsumablesSupportedByProcess())) {
		var consumableExt = HAMUtils.getTableExtensions(HAMConstants.ALM_CONSUMABLE_TABLE);
		assets.addQuery('sys_class_name', 'NOT IN', consumableExt);
	}
	// Exclude EAM assets and EAM models
	var eamModelExt = HAMUtils.getEAMModelClasses();
	assets.addQuery('model.sys_class_name', 'NOT IN', eamModelExt);
	var eamAssetExt = HAMUtils.getEAMAssetClasses();
	assets.addQuery('sys_class_name', 'NOT IN', eamAssetExt);
	assets.addQuery('sys_class_name', '!=', 'alm_license');
	if (!gs.nil(model)) {
		assets.addQuery('model', model);
	}
	HampLoanerUtils.addDomainFilterQuery(assets);
	return assets.getEncodedQuery();
};
HampLoanerUtils.getLoanerBaseQueryWithLocation = function (location, commonBaseQuery) {
	var baseQueryWithLocation = commonBaseQuery;
	if (!gs.nil(location)) {
		baseQueryWithLocation += '^location=' + location;
		baseQueryWithLocation += '^NQ' + commonBaseQuery + '^locationISEMPTY^stockroom.location=' + location;
	}
	return baseQueryWithLocation;
};
HampLoanerUtils.addLoanerBaseQuery = function (assets, location, model) {
	var commonBaseQuery = HampLoanerUtils.getLoanerCommonBaseQuery(location, model);
	var baseQueryWithLocation = HampLoanerUtils.getLoanerBaseQueryWithLocation(location, commonBaseQuery);
	assets.addEncodedQuery(baseQueryWithLocation);
};
HampLoanerUtils.addInStockFunctioningAssetsQuery = function (assets) {
	// Assets are considered functioning if the state and substatus are:
	// state: in_stock (6) | substatus: available, reserved, pending_install
	// OR state: in_use (1)
	var validInstallStatus = HAMConstants.ASSET_STATUSES.IN_STOCK;
	var validSubstatus = [
		HAMConstants.ASSET_SUB_STATUSES.AVAILABLE,
		HAMConstants.ASSET_SUB_STATUSES.RESERVED,
		HAMConstants.ASSET_SUB_STATUSES.PENDING_INSTALL,
	];
	assets.addQuery('install_status', validInstallStatus);
	assets.addQuery('substatus', validSubstatus)
		.addOrCondition('substatus', '');
	HampLoanerUtils.addDomainFilterQuery(assets);
};
HampLoanerUtils.addInUseFunctioningAssetsQuery = function (loanerOrders, location, model) {
	var validStatus = [HAMConstants.ASSET_STATUSES.IN_USE];
	if (HAMUtils.isConsumablesSupportedByProcess()) {
		validStatus.push(HAMConstants.ASSET_STATUSES.CONSUMED);
	}
	loanerOrders.addQuery('location', location);
	if (!gs.nil(model)) {
		loanerOrders.addQuery('model', model);
	}
	loanerOrders.addQuery('asset.install_status', validStatus);
	loanerOrders.addQuery('asset.asset_function', 'loaner');
	loanerOrders.addQuery('stage', HampLoanerUtils.STAGE_DEPLOYED);
	HampLoanerUtils.addDomainFilterQuery(loanerOrders);
};
HampLoanerUtils.convertDateStringToDateObj = function (dateString) {
	var date = new Date();
	date.setFullYear(dateString.substring(0, 4));
	date.setMonth(dateString.substring(5, 7) - 1);
	date.setDate(dateString.substring(8, 10));
	date.setHours(0, 0, 0, 0);
	return date;
};
HampLoanerUtils.convertDateObjToDateString = function (date) {
	var yearStr = String(date.getFullYear());
	var monthStr = String(date.getMonth() + 1);
	if (monthStr.length === 1) { monthStr = '0' + monthStr; }
	var dateStr = String(date.getDate());
	if (dateStr.length === 1) { dateStr = '0' + dateStr; }
	return yearStr + '-' + monthStr + '-' + dateStr;
};
HampLoanerUtils.getPreparationStartDate = function (startDate, leadTime) {
	var leadTimeInDays = parseInt(leadTime, 10);
	var minusDays = 0 - leadTimeInDays;

	var preparationStartDateObj = HampLoanerUtils.convertDateStringToDateObj(String(startDate));
	if (leadTimeInDays > 0) {
		preparationStartDateObj.setDate(preparationStartDateObj.getDate() + minusDays);
	}
	var preparationStartDateStr = HampLoanerUtils.convertDateObjToDateString(preparationStartDateObj);

	var currentDateStr = new GlideDateTime().getLocalDate().toString();
	var currentDateObj = HampLoanerUtils.convertDateStringToDateObj(currentDateStr);

	if ((preparationStartDateObj.getTime() - currentDateObj.getTime()) <= 0) {
		return currentDateStr;
	}
	return preparationStartDateStr;
};
HampLoanerUtils.addLoanerOrdersOverlapQuery = function (loanerOrders, startDate, returnDate, leadTime, isGlideQuery) {
	var preparationStartDate = HampLoanerUtils.getPreparationStartDate(startDate, leadTime);
	if (isGlideQuery) {
		var enhancedQuery = loanerOrders.where('preparation_start_date', '<=', returnDate);
		enhancedQuery = enhancedQuery.where('return_date', '>=', preparationStartDate);
		return enhancedQuery;
	}
	loanerOrders.addQuery('start_date', '<=', returnDate);
	loanerOrders.addQuery('return_date', '>=', preparationStartDate);
	return loanerOrders;
};
HampLoanerUtils.convertUTCtoTimezone = function (utcTime, timeZone) {
	if (!gs.nil(timeZone)) {
		var gr = new GlideScheduleDateTime(utcTime);
		var currentTime = gr.convertTimeZone('UTC', timeZone);
		return new GlideDateTime(currentTime);
	}
	return utcTime;
};
HampLoanerUtils.getTimezoneOfLocation = function (location) {
	var locObj = new global.GlideQuery('cmn_location')
		.get(location, ['time_zone']);
	if (!gs.nil(locObj) && !gs.nil(locObj._value) && !gs.nil(locObj._value.time_zone)) {
		return locObj._value.time_zone;
	}
	return '';
};
HampLoanerUtils.splitConsumableOnLoanerOrder = function (loanerOrderGr) {
	var quantity = 1; // Only consumables with quantity 1 can be requested as of now.

	var consumableID = loanerOrderGr.getValue('asset');
	var consumableGr = HAMUtils.getAsGlideRecord(HAMConstants.ALM_ASSET_TABLE, consumableID);
	var newConsumableID = consumableID;

	if (quantity < parseInt(consumableGr.getValue('quantity'), 10)) {
		newConsumableID = new global.Consumables().split(
			consumableID,
			quantity,
			consumableGr.getValue('install_status'),
			HAMConstants.ASSET_SUB_STATUSES.RESERVED,
			'',
			consumableGr.getValue('stockroom'),
			consumableGr.getValue('location'),
			'',
			'loaner', {
				process_table: loanerOrderGr.getTableName(),
				process_id: loanerOrderGr.getUniqueValue(),
				reserved_for: loanerOrderGr.getValue('requested_for'),
			}
		);
	}
	return newConsumableID;
};
HampLoanerUtils.consumableMergeConditionCheck = function (consumableGr) {
	var canMerge = true;
	if (consumableGr.getValue('process_table') === HampLoanerUtils.LOANER_ORDER_TABLE
		&& !gs.nil(consumableGr.getValue('process_id'))) {
		canMerge = false;
	}
	return canMerge;
};
HampLoanerUtils.getAnotherLoanerOrderWithAsset = function (assetId, excludeLoanerOrderGr) {
	var loanerOrder = '';
	var assetExists = new global.GlideQuery(HampLoanerUtils.LOANER_ORDER_TABLE)
		.where('asset', assetId)
		.where('sys_id', '!=', String(excludeLoanerOrderGr.sys_id))
		.where('stage', 'IN', [
			HampLoanerUtils.STAGE_NEW,
			HampLoanerUtils.STAGE_PREPARE,
			HampLoanerUtils.STAGE_DEPLOYED,
		])
		.where('is_waitlisted', false)
		.orderBy('start_date')
		.toGlideRecord();
	assetExists.setLimit(1);
	assetExists.query();
	if (assetExists.next()) {
		loanerOrder = assetExists;
	}
	return loanerOrder;
};
HampLoanerUtils.canCloseLoanerTask = function (loanerTaskGr) {
	var hasAccess = gs.getUser().hasRole('itil') || gs.hasRole('inventory_user')
	|| String(loanerTaskGr.assigned_to) === gs.getUserID();
	return (hasAccess && (loanerTaskGr.getValue('state') === '1' || loanerTaskGr.getValue('state') === '2'));
};
HampLoanerUtils.validateFieldsForLoaner = function (loanerTaskGr) {
	var message;
	var msgParams = [];
	if ((loanerTaskGr.getValue('task_name') === 'prepare') && loanerTaskGr.getValue('state') !== '4') {
		// check mandatory fields are filled on Prepare task
		if (!loanerTaskGr.loaner_order.asset) {
			msgParams.push(loanerTaskGr.loaner_order.asset.getLabel());
		}
		if (msgParams.length > 0) {
			message = gs.getMessage('The following mandatory fields are not filled in: {0}', msgParams.join(', '));
			gs.addErrorMessage(message);
		}
		if (loanerTaskGr.loaner_order.asset) {
			message = (new sn_hamp.HAMLicensingUtility()).getExcludedAssetErrorMessage(loanerTaskGr.loaner_order.asset);
			if(!gs.nil(message)) {
				msgParams.push(message);
				//Next 2 lines have been added as a workaround to avoid 2 error messages from appearing in Classic workspace, will be removed once platform fix is done.
				var inputURL = String(gs.action.getGlideURI());
				if (inputURL.indexOf('.do?') === -1) {
					gs.addErrorMessage(message);
				}
			}
		}
	} else if ((loanerTaskGr.getValue('task_name') === 'reclaim') && loanerTaskGr.getValue('state') !== '4') {
		// check mandatory fields are filled on Reclaim task
		if (!loanerTaskGr.getValue('return_stockroom')) {
			msgParams.push(loanerTaskGr.return_stockroom.getLabel());
		}
		if (msgParams.length > 0) {
			message = gs.getMessage('The following mandatory fields are not filled in: {0}', msgParams.join(', '));
			gs.addErrorMessage(message);
		}
		var msg;
		if (loanerTaskGr.loaner_order.asset_returned.toString() === 'N') {
			// eslint-disable-next-line max-len
			msg = gs.getMessage('To complete the task, update {0} value to Yes', loanerTaskGr.loaner_order.asset_returned.getLabel());
			msgParams.push(loanerTaskGr.loaner_order.asset_returned.getLabel());
			gs.addErrorMessage(msg);
		}
		if (loanerTaskGr.loaner_order.is_asset_functional.toString() === '') {
			// eslint-disable-next-line max-len
			msg = gs.getMessage('To complete the task, update {0} value to either Yes or No', loanerTaskGr.loaner_order.is_asset_functional.getLabel());
			msgParams.push(loanerTaskGr.loaner_order.is_asset_functional.getLabel());
			gs.addErrorMessage(msg);
		}
	}
	if (msgParams.length === 0) {
		if (loanerTaskGr.getValue('state') !== '4') {
			loanerTaskGr.state = 3;
		}
		loanerTaskGr.update();
	}
	if (loanerTaskGr.getValue('state') !== '3') { // redirect to task page only if its incomplete
		return loanerTaskGr;
	}
	return loanerTaskGr.loaner_order.getRefRecord();
};
HampLoanerUtils.LOANER_ORDER_TABLE = 'sn_hamp_loaner_asset_order';
HampLoanerUtils.LOANER_TASK_TABLE = 'sn_hamp_loaner_asset_task';
HampLoanerUtils.STAGE_NEW = 'new';
HampLoanerUtils.STAGE_PREPARE = 'prepare';
HampLoanerUtils.STAGE_DEPLOYED = 'deployed';
HampLoanerUtils.STAGE_COMPLETED = 'completed';
HampLoanerUtils.STAGE_CANCELLED = 'cancelled';
HampLoanerUtils.TASK_CLOSED_COMPLETE = 3;
HampLoanerUtils.TASK_PREPARE = 'prepare';
HampLoanerUtils.LOANER_ORDER_ACTION_CANCELLED = 'cancelled';
HampLoanerUtils.LOANER_ORDER_ACTION_DELETED = 'deleted';
HampLoanerUtils.LOANER_ORDER_TYPE_THIRD_PARTY = 'for_third_party_user';
HampLoanerUtils.ASSET_IN_USE_STATUSES = [HAMConstants.ASSET_STATUSES.IN_USE,
	HAMConstants.ASSET_STATUSES.CONSUMED];
var HAMAssetReservationUtils = Class.create();
HAMAssetReservationUtils.prototype = {
	initialize: function () { },

	isLoanerAssetAvailableBetweenDates: function (model, location, fromStartDate, toReturnDate, leadTime) { // eslint-disable-line
		var assetsAvailable = new sn_hamp.HampLoanerUtils().getFunctioningLoanerAssetsCount(location, model);
		if (assetsAvailable === 0) { return false; }

		var startDate = String(fromStartDate);
		var returnDate = String(toReturnDate);
		var leadTimeInDays = parseInt(leadTime, 10);
		var preparationStartDate = HampLoanerUtils.getPreparationStartDate(startDate, leadTimeInDays);

		var overlappingOrdersStartDates = [preparationStartDate];
		var overlappingOrdersEndDates = [returnDate];

		var overlappingOrdersGq = new global.GlideQuery('sn_hamp_loaner_asset_order')
			.where('model', model)
			.where('location', location)
			.where('is_waitlisted', false)
			.where('stage', '!=', HampLoanerUtils.STAGE_COMPLETED)
			.where('stage', '!=', HampLoanerUtils.STAGE_CANCELLED);
		overlappingOrdersGq = HampLoanerUtils.addLoanerOrdersOverlapQuery(
			overlappingOrdersGq,
			startDate,
			returnDate,
			leadTimeInDays,
			true /* isGlideQuery */
		);

		overlappingOrdersGq.select('preparation_start_date', 'return_date')
			.forEach(function (loanerOrder) {
				overlappingOrdersStartDates.push(loanerOrder.preparation_start_date);
				overlappingOrdersEndDates.push(loanerOrder.return_date);
			});

		overlappingOrdersStartDates.sort();
		overlappingOrdersEndDates.sort();

		var totalRequests = overlappingOrdersStartDates.length;
		var assetsReturned = 0;
		var assetsDeparted = 0;
		var assetsNeeded = 0;

		while ((assetsDeparted < totalRequests) && (assetsReturned < totalRequests)) {
			if (overlappingOrdersStartDates[assetsDeparted] <= overlappingOrdersEndDates[assetsReturned]) {
				assetsNeeded += 1;
				assetsDeparted += 1;
			} else if (overlappingOrdersStartDates[assetsDeparted] > overlappingOrdersEndDates[assetsReturned]) {
				assetsNeeded -= 1;
				assetsReturned += 1;
			}
			if (assetsNeeded > assetsAvailable) {
				return false;
			}
		}
		return true;
	},

	type: 'HAMAssetReservationUtils',
};
<script setup lang="ts">
import { shallowRef } from 'vue';
import { RouterLink } from 'vue-router';
import IconAngle from './icons/IconAngle.vue';
import IconEmail from './icons/IconEmail.vue';
import IconEmployeeGroup from './icons/IconEmployeeGroup.vue';
import IconExclamation from './icons/IconExclamation.vue';
import IconHome from './icons/IconHome.vue';

const isSidebarOpen = shallowRef<Boolean>(false)

function toggleSidebar() {
  isSidebarOpen.value = !isSidebarOpen.value;
}

</script>

<template>
  <div class="wrapper">
    <aside :vue:is-open="isSidebarOpen">
      <ul class="sidebar-head">
        <li>
          <img src="@/assets/logo.png" alt="logo" width="32" height="32">
        </li>
        <li>
          <button class="sidebar-toggle" :class="isSidebarOpen ? 'toggle-button' : ''">
            <IconAngle @click="toggleSidebar" />
          </button>
        </li>
      </ul>

      <h4 :transparent="!isSidebarOpen">Menu</h4>

      <ul>
        <li>
          <router-link to="/">
            <IconHome />
            <Transition name="fade">
              <span v-show="isSidebarOpen">Home</span>
            </Transition>
          </router-link>
        </li>
        <li>
          <router-link to="/about">
            <IconExclamation />
            <Transition name="fade">
              <span v-show="isSidebarOpen">About</span>
            </Transition>
          </router-link>
        </li>
        <li>
          <router-link to="/team">
            <IconEmployeeGroup />
            <Transition name="fade">
              <span v-show="isSidebarOpen">Team</span>
            </Transition>
          </router-link>
        </li>
        <li>
          <router-link to="/contact">
            <IconEmail />
            <Transition name="fade">
              <span v-show="isSidebarOpen">Contact</span>
            </Transition>
          </router-link>
        </li>
      </ul>
    </aside>
  </div>
</template>

<style scoped lang="scss">
@use '@/assets/scss/colors' as clr;

$sidebar-width: 4rem;
$toggle-duration: 300ms;
$sidebar-padding-inline-start: 1rem;

aside {
  color: clr.$primary;
  background: clr.$bg-dark;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  padding-block: 1rem;
  transition: all $toggle-duration;
  width: $sidebar-width;
}

aside[vue\:is-open=true] {
  width: 3 * $sidebar-width;
}

ul {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  padding-block-end: 1rem;
}

img {
  object-fit: contain;
}

li {
  min-width: fit-content;
  cursor: pointer;
  padding-inline-start: $sidebar-padding-inline-start;

  &:hover {
    color: clr.$secondary;
    background-color: lighten($color: clr.$bg-dark, $amount: 5);
  }

  & a {
    // border-right: 0.25rem solid white;
    display: flex;
    align-items: center;
    column-gap: 0.75rem;
    position: relative;
    padding-block: 0.5rem;
  }

  a.router-link-exact-active::after {
    content: '';
    position: absolute;
    right: 0;
    width: 0.25rem;
    height: 100%;
    background-color: clr.$secondary;
  }
}
.sidebar-head {
  position: relative;
  // padding-block-end: 4rem;
}

.sidebar-toggle {
  padding-inline-start: $sidebar-padding-inline-start;
}

h4 {
  padding-block-end: 1rem;
  padding-inline-start: $sidebar-padding-inline-start;
  user-select: none;
  pointer-events: none;
  opacity: 0.5;
  text-transform: uppercase;
  font-size: 0.75rem;
  letter-spacing: 0.125ch;
  transition: opacity $toggle-duration;
}

h4[transparent=true] {
  opacity: 0;
}

button {
  cursor: pointer;
  position: absolute;
  transition-duration: $toggle-duration;
  transition-property: transform, left, top;
  left: 0;
  top: 1rem;
  transform: translateX(0%) translateY(2rem) rotateZ(0deg);

  &.toggle-button {
    left: 100%;
    top: 0;
    transform: translateX(-100%) translateY(0rem) rotateZ(180deg);
  }
}

.fade-enter-active,
.fade-leave-active {
  transition-property: opacity, transform;
  transition-duration: $toggle-duration;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateX(-100%);
}
</style>
import { onMounted, onUnmounted, ref } from 'vue'

function useScreenOrientation() {
  const portrait = window.matchMedia('(orientation: portrait)')
  const orientation = ref(portrait.matches ? 'portrait' : 'landscape')

  function orientationListener(e: MediaQueryListEvent) {
    orientation.value = e.matches ? 'portrait' : 'landscape'
  }

  onMounted(() => {
    portrait.addEventListener('change', orientationListener)
  })

  onUnmounted(() => {
    portrait.removeEventListener('change', orientationListener)
  })

  return orientation
}

export {
  useScreenOrientation,
  useScreenOrientation as default,
}
<template>
  <div
    :style="styleGeneral"
    aria-label="container-scroll"
    :class="`container ${this.scroll ? 'containerScroll' : ''}`"
  >
    <div
      aria-label="subcontainer-scroll"
      ref="component"
      class="subcontainer"
      :style="styleSubcontainer"
    >
      <slot />
    </div>
  </div>
</template>

<script>
import ResizeObserver from 'resize-observer-polyfill';

export default {
  name: 'ScrollShadow',
  data() {
    let styleGeneral = this.styleContainer;
    styleGeneral += `--scrollColor:${this.scrollColor};`;
    styleGeneral += `--shadow:${this.isShadow ? this.shadow : ''};`;
    styleGeneral += `--scrollPadding:${this.scrollPadding};`;
    styleGeneral += `--scrollWidth:${this.scrollWidth};`;
    styleGeneral += `--scrollColorHover:${this.scrollColorHover}`;

    return {
      scroll: false,
      component: null,
      RO: null,
      styleGeneral,
      classGeneral: 'container'
    };
  },
  props: {
    styleContainer: { type: String, default: '' },
    styleSubcontainer: { type: String, default: '' },
    // Scroll color
    scrollColor: { type: String, default: '#c5c5c5' },
    // Left scroll padding
    scrollPadding: { type: String, default: '0px' },
    // Scroll Width
    scrollWidth: { type: String, default: '8px' },
    // Scroll color when hover
    scrollColorHover: { type: String, default: '#a6a6a6' },
    shadow: {
      type: String,
      default:
        '0 2px 4px rgba(0, 0, 0, 0.2) inset, 0 -2px 4px rgba(0, 0, 0, 0.2) inset'
    },
    // Verify shadow is visible
    isShadow: { type: Boolean, default: true }
  },
  mounted() {
    const refComponent = this.$refs.component;

    const RO = new ResizeObserver(() => {
      if (refComponent.clientHeight < refComponent.scrollHeight) {
        this.scroll = true;
      } else {
        this.scroll = false;
      }
    });

    RO.observe(refComponent);
  }
};
</script>

<style scoped>
.containerScroll {
  box-shadow: var(--shadow);
}
.container {
  width: 100%;
  overflow-y: hidden;
  box-sizing: border-box;
  display: flex;
}
.subcontainer {
  padding-right: var(--scrollPadding);
  overflow-y: auto;
  flex: 1;
  scrollbar-color: var(--scrollColor);
  scrollbar-width: thin;
}
.subcontainer::-webkit-scrollbar {
  width: var(--scrollWidth);
  background: transparent;
}
.subcontainer::-webkit-scrollbar-track {
  background: 'transparent';
}
.subcontainer::-webkit-scrollbar-thumb {
  background: var(--scrollColor);
  border-radius: 5px;
  overflow: hidden;
}
.subcontainer::-webkit-scrollbar-thumb:hover {
  background: var(--scrollColorHover);
}
</style>
 Save
const randomID = new Date().getTime().toString().substring(3, 10)
[0:01:10.271] Script completed in scope global: script
Script execution history and recovery available here
Time: 0:00:00.165 id: esri_1[glide.20] primary_hash=-1044066828 (connpid=16123892) for: SELECT cmdb0.`sys_id` FROM cmdb cmdb0  WHERE cmdb0.`sys_class_path` LIKE '/!!%' AND cmdb0.`sys_class_name` = 'cmdb_ci_computer' AND cmdb0.`serial_number` IS NOT NULL  AND cmdb0.`asset` IS NULL  /* esri069, gs:71C93306939A7D102D82BF1C5CBA10DC, tx:6ef93f46939a7d102d82bf1c5cba1041, hash:-1044066828 */ 
[0:00:00.015] Compacting large row block (file.write: alm_asset 10000 rows 160000 saveSize)
[0:00:00.015] Compacting large row block (file.write: alm_asset 10000 rows 160000 saveSize)
[0:00:00.015] Compacting large row block (file.write: alm_asset 10000 rows 160000 saveSize)
[0:00:00.014] Compacting large row block (file.write: alm_asset 10000 rows 160000 saveSize)
[0:00:00.015] Compacting large row block (file.write: alm_asset 10000 rows 160000 saveSize)
[0:00:00.014] Compacting large row block (file.write: alm_asset 10000 rows 160000 saveSize)
[0:00:00.015] Compacting large row block (file.write: alm_asset 10000 rows 160000 saveSize)
[0:00:00.014] Compacting large row block (file.write: alm_asset 10000 rows 160000 saveSize)
[0:00:00.015] Compacting large row block (file.write: alm_asset 10000 rows 160000 saveSize)
[0:00:00.015] Compacting large row block (file.write: alm_asset 10000 rows 160000 saveSize)
[0:00:00.380] id: esri_1[glide.2 (connpid=16123874)] for: DBQuery#loadResultSet[alm_asset: ci=NULL^serial_numberISNOTEMPTY]
Time: 0:00:00.115 id: esri_1[glide.2] primary_hash=-1351908010 (connpid=16123874) for: SELECT alm_asset0.`sys_id` FROM alm_asset alm_asset0  WHERE alm_asset0.`ci` IS NULL  AND alm_asset0.`serial_number` IS NOT NULL  /* esri069, gs:71C93306939A7D102D82BF1C5CBA10DC, tx:6ef93f46939a7d102d82bf1c5cba1041, hash:-1351908010 */ 
[0:00:00.002] Expanding large row block (file.read: alm_asset, 10000 rows, 160000 dataSize)
[0:00:00.012] Compacting large row block (file.write: alm_asset 7492 rows 119872 saveSize)
*** Script: Match found: KVP4DGD29L
*** Script: Match found: C02TF7AMGTFM
*** Script: Match found: M7L4HFRXHD
*** Script: Match found: C02NPB7YG3QD
*** Script: Match found: VWV6XW22X1
*** Script: Match found: A92F011004613
*** Script: Match found: KVHH0QQG2X
*** Script: Match found: 632024000026
*** Script: Match found: A7PU011009006
*** Script: Match found: 000000000000000000000000000000000000000000047
*** Script: Match found: C02FN47VMD6R
*** Script: Match found: 12CVBY3
*** Script: Match found: 87
*** Script: Match found: H6GB762
*** Script: Match found: 58CXNH2
*** Script: Match found: CN88EBW0Q6
*** Script: Match found: MMYF.105266..ATI
*** Script: Match found: C02GJ0TXMD6R
*** Script: Match found: MTFYHCDT25
*** Script: Match found: C02DRAZZMD6R
*** Script: Match found: BBEC.502477..ATI
*** Script: Match found: FVFHJ0YVQ05P
*** Script: Match found: MNYF.101492..ATI
*** Script: Match found: FP22PYXQ4Q
*** Script: Match found: 54XXN73
*** Script: Match found: JXPWV6JJW0
*** Script: Match found: CNCCDDN19L
*** Script: Match found: XH9FMFJ7LK
*** Script: Match found: VQGKV4M06K
*** Script: Match found: LX7LD29CJY
*** Script: Match found: C02FN470MD6R
*** Script: Match found: C02FN47UMD6R
*** Script: Match found: X124YW9FNQ
*** Script: Match found: 87
*** Script: Match found: C02FN01MML88
*** Script: Match found: MQ6DY4T3V5
*** Script: Match found: MTF3VKG6LJ
*** Script: Match found: M7L7GH9VP4
*** Script: Match found: GCDJF2PY6N
*** Script: Match found: 81
*** Script: Match found: C44MRXWXW7
*** Script: Match found: XL4L471K9C
*** Script: Match found: YMQWQQKGF2
*** Script: Match found: C02TK2GYHF1R
*** Script: Match found: N2W0CXP2N4
*** Script: Match found: NGF7DW4R2M
*** Script: Match found: C02GJ0TVMD6R
*** Script: Match found: K32QD4J57H
*** Script: Match found: XL6L3906KV
*** Script: Match found: 76L17S2
*** Script: Match found: X7NW6QW291
*** Script: Match found: XL9DFYQHF7
*** Script: Match found: 87YR0S2
*** Script: Match found: H2WH313GQ6P0
*** Script: Match found: TV3V3PJWHL
*** Script: Match found: RV0NL40JLX
*** Script: Match found: FVFGG1C7Q05N
*** Script: Match found: J9H96QQF4X
*** Script: Match found: C02DRAZ6MD6R
*** Script: Match found: N95WP9167Q
*** Script: Match found: 70
*** Script: Match found: 57
*** Script: Match found: 86MWNZ3
*** Script: Match found: C02XK13JJGH6
*** Script: Match found: FTX1639R35M
*** Script: Match found: XWY34GTXM5
*** Script: Match found: C02H325DDV7P
*** Script: Match found: LQJ565TGGN
*** Script: Match found: C02YJ0PCJGH6
*** Script: Match found: 1P5J082
*** Script: Match found: C02DK4JZMD6R
*** Script: Match found: HW59XP92TX
*** Script: Match found: D25LL0J3F8JC
*** Script: Match found: T0WK941VHW
*** Script: Match found: C02G37PEMD6R
*** Script: Match found: C5KPMH3
*** Script: Match found: 64167FB9AD8C
*** Script: Match found: BBEC.509353..ATI
*** Script: Match found: C02X655XJGH6
*** Script: Match found: KVP4DGD29L
*** Script: Match found: 65063D3
*** Script: Match found: T637QHYVGY
*** Script: Match found: C02WL09EHTDF
*** Script: Match found: VVKKXXHHH9
*** Script: Match found: C02FP6P5MD6R
*** Script: Match found: C02G7111MD6R
*** Script: Match found: C02XV34VJHD3
*** Script: Match found: M6XCV9L75C
*** Script: Match found: FTX1607AJH8
*** Script: Match found: P6D4PGXK0J
*** Script: Match found: 80
*** Script: Match found: VK6D96XQLG
*** Script: Match found: FVFHJ2U5Q05P
*** Script: Match found: 80
*** Script: Match found: WDFCWJFQ14
*** Script: Match found: C6TZX23
*** Script: Match found: C02DG12VMD6R
*** Script: Match found: 000000000000000000000000000000000000000000047
*** Script: Match found: C02F75NCQ05N
*** Script: Match found: C02G710QMD6R
*** Script: Match found: C07YD0XYJYVY
*** Script: Match found: H2WHR0QUQ6NW
*** Script: Match found: JR36GH2
*** Script: Match found: A61H011005986
*** Script: Match found: FVFHJ0YZQ05P
*** Script: Match found: C02FN5LRMD6R
*** Script: Match found: H4TH20GRPN7C
*** Script: Match found: 9BDJ0T2
*** Script: Match found: G1C2614P7X
*** Script: Match found: VJ92GLW9Y5
*** Script: Match found: C994WR3FXP
*** Script: Match found: 81
*** Script: Match found: JQ0K44MJWH
*** Script: Match found: C02DC2CBPN7C
*** Script: Match found: GLCM7YL6T7
*** Script: Match found: WDCWV26THJ
*** Script: Match found: C07SN1CUG1J1
*** Script: Match found: 442539942
*** Script: Match found: C02FN47DMD6R
*** Script: Match found: C02DRB00MD6R
*** Script: Match found: 10
*** Script: Match found: IUEC.731218.ATI
*** Script: Match found: D7KQX9GQFV
*** Script: Match found: BFHS9Y2
*** Script: Match found: H4TFD0PHPN7C
*** Script: Match found: C02XV43FJGH6
*** Script: Match found: C02G325SQ05R
*** Script: Match found: 51
*** Script: Match found: XGQGTH29LW
*** Script: Match found: C02FN46DMD6R
*** Script: Match found: YD4WQ3LK9V
*** Script: Match found: GVQ397X30G
*** Script: Match found: JPBCG4W12Z
*** Script: Match found: C02FH82GMD6R
*** Script: Match found: C02FN01SML88
*** Script: Match found: C02DM0XRMD6T
*** Script: Match found: C02GC58WQ05N
*** Script: Match found: WVCJC64L54
*** Script: Match found: TK7K21796N
*** Script: Match found: V59V52CWX6
*** Script: Match found: C02FG6DFMD6R
*** Script: Match found: 81
*** Script: Match found: NHXQ7K92T7
*** Script: Match found: X162DL03XV
*** Script: Match found: GL9QVJ2P40
*** Script: Match found: 81
*** Script: Match found: YJJGR4G9DD
*** Script: Match found: XK1FWXDFX7
*** Script: Match found: WW4PLX2X33
*** Script: Match found: FYVP6RL1F2
*** Script: Match found: C02NQ0D5G3QD
*** Script: Match found: 82
*** Script: Match found: G4FXJFJ2DN
*** Script: Match found: C02WJ37XHTDF
*** Script: Match found: 82
*** Script: Match found: A5C4011118436
*** Script: Match found: A93E011006607
*** Script: Match found: PH9RF722M2
*** Script: Match found: 28LLPN3
[0:00:00.002] Expanding large row block (file.read: alm_asset, 10000 rows, 160000 dataSize)
[0:00:00.015] Compacting large row block (file.write: alm_asset 10000 rows 160000 saveSize)
*** Script: Match found: QGPJ7G2V32
*** Script: Match found: PD4NCJJKJ6
*** Script: Match found: H2WFR8DAQ6NV
*** Script: Match found: PW54V3QWKV
*** Script: Match found: 4DZMRQ3
*** Script: Match found: C02FK4MGMD6R
*** Script: Match found: H2WFL0UDPJJ9
*** Script: Match found: Q2KCF2Q3KF
*** Script: Match found: JJ47QD71RH
*** Script: Match found: HTFPKHGCHK
*** Script: Match found: 20
*** Script: Match found: JX0LPN3
*** Script: Match found: PXLC43L30F
*** Script: Match found: RQYC6Q2WC5
*** Script: Match found: C02FL08PMD6R
*** Script: Match found: 792102000543
*** Script: Match found: WNTDT6TFD6
*** Script: Match found: C02DR9KGMD6R
*** Script: Match found: C02FN3XVMD6R
*** Script: Match found: WPKT91FPYF
*** Script: Match found: Q6J5R9NXJP
*** Script: Match found: C07SN0U6G1J2
*** Script: Match found: H4TG815FPN7C
*** Script: Match found: GD700WJPG1
*** Script: Match found: JJ7C3G2
*** Script: Match found: FXF7562
*** Script: Match found: N12HY2VD6P
*** Script: Match found: TKQHK06T4P
*** Script: Match found: H2WHP12QQ6NW
*** Script: Match found: 82
*** Script: Match found: WCAZAA747453
*** Script: Match found: YP6GK0461V
*** Script: Match found: C02G37P6MD6R
*** Script: Match found: W2GTC6JXCF
*** Script: Match found: MJ0G9WFY
*** Script: Match found: 6V4BXG2
*** Script: Match found: C02G711LMD6R
*** Script: Match found: FVFGP4SQQ05N
*** Script: Match found: FYVP6RL1F2
*** Script: Match found: C02FN01JML88
*** Script: Match found: QHX2MP2KTM
*** Script: Match found: A92F011006067
*** Script: Match found: 7B2KNN3
*** Script: Match found: H2WJF0EYQ6P0
*** Script: Match found: C02XV4HFJGH6
*** Script: Match found: R26W1QVKFV
*** Script: Match found: C02F11H2Q05N
*** Script: Match found: 27
*** Script: Match found: C02DF4ECMD6R
*** Script: Match found: LW44M7P73W
*** Script: Match found: G2KXGF3Y3M
*** Script: Match found: KJVNY9097C
*** Script: Match found: P21T2CYLX2
*** Script: Match found: 70
*** Script: Match found: 4NZ31Q2
*** Script: Match found: JJ954J3
*** Script: Match found: Y4475HK333
*** Script: Match found: NDXXPYX276
*** Script: Match found: 46
*** Script: Match found: QY54WWYG9C
*** Script: Match found: XDX44MVKCQ
*** Script: Match found: 06F930G
*** Script: Match found: FVFHJ0ZKQ05P
*** Script: Match found: GG102145
*** Script: Match found: 632016000060
*** Script: Match found: VH242MG2P6
*** Script: Match found: C02DC03NML86
*** Script: Match found: WNTDT6TFD6
*** Script: Match found: WVHT4QKYQ5
*** Script: Match found: Q7H7YJNJ0W
*** Script: Match found: W4TJ3Q13Y1
*** Script: Match found: 29
*** Script: Match found: DTF6WW1
*** Script: Match found: C02RH01JG8WM
*** Script: Match found: XCR9QMM6TV
*** Script: Match found: 27
*** Script: Match found: 9WFL0T2
*** Script: Match found: XH2JQ3C7G2
*** Script: Match found: YC3WDQ03YP
*** Script: Match found: P2PHHY2C9D
*** Script: Match found: WFQGWF9G0V
*** Script: Match found: H2WH312GQ6P0
*** Script: Match found: RXM9XH09QR
*** Script: Match found: JJ47QD71RH
*** Script: Match found: H2WJJ04LQ6P0
*** Script: Match found: 82
*** Script: Match found: C02M61CKFD59
*** Script: Match found: 4P321Q2
*** Script: Match found: C02FN46TMD6R
*** Script: Match found: 721523000029
*** Script: Match found: TJFX1W7Q4X
*** Script: Match found: C02DC02PML86
*** Script: Match found: C02GK0QRMD6T
*** Script: Match found: C07QM0A6G1J1
*** Script: Match found: TQWRWG292J
*** Script: Match found: 1Q5VBY3
*** Script: Match found: H2WJF0H1Q6P0
*** Script: Match found: VDGQ0HFWTY
*** Script: Match found: VDHJ7QK549
*** Script: Match found: 82
*** Script: Match found: FVFHJ0ZPQ05P
*** Script: Match found: WVNQWN66T2
*** Script: Match found: C02Z70KBLVDM
*** Script: Match found: C02DR9KKMD6R
*** Script: Match found: C02NQ0EQG3QD
*** Script: Match found: C02DG12WMD6R
*** Script: Match found: VP7XKW0232
*** Script: Match found: LQJ565TGGN
*** Script: Match found: A5C4011116895
*** Script: Match found: RXYLV6C07P
*** Script: Match found: WP4QYQ9N9D
*** Script: Match found: C02NQ055G3QD
*** Script: Match found: C02G37PAMD6R
*** Script: Match found: 000000000000000000000000000000000000000000047
*** Script: Match found: 27WGLQ2
*** Script: Match found: C07SN0TTG1J2
*** Script: Match found: C02GJ0TTMD6R
*** Script: Match found: C02YJ2JTJGH6
*** Script: Match found: MXF9DK210Q
*** Script: Match found: Q4NNF7L9CF
*** Script: Match found: VNB3Y51823
*** Script: Match found: H2WJF0WVQ6P0
*** Script: Match found: P9L7XWDHVQ
*** Script: Match found: LXMVH6KMH4
*** Script: Match found: C02DT1FEMD6R
*** Script: Match found: C02M60YPFD59
*** Script: Match found: W4R93MH71R
*** Script: Match found: 632024000027
*** Script: Match found: C02DG12NMD6R
*** Script: Match found: C02FN47QMD6R
*** Script: Match found: C02TK249HF1R
*** Script: Match found: X1VQC22GM7
*** Script: Match found: 9ZGPM53
*** Script: Match found: A4Y4011019972
*** Script: Match found: LHXCXQMMPH
*** Script: Match found: V0QPJ6P9HW
*** Script: Match found: QQF9PT94WW
*** Script: Match found: C02G37P7MD6R
*** Script: Match found: C02VL2REHTDF
*** Script: Match found: 51
*** Script: Match found: C02C32EELVDM
*** Script: Match found: XT9KX3XH9X
*** Script: Match found: MXBCMCP0TZ
*** Script: Match found: C02G7119MD6R
*** Script: Match found: FYVP6RL1F2
*** Script: Match found: C07DC09XPJJ9
*** Script: Match found: FVWF9HJ70N
*** Script: Match found: TDLX93TY02
*** Script: Match found: C19KWVY3HK
*** Script: Match found: G17MJP21CP
*** Script: Match found: C02G711AMD6R
*** Script: Match found: C02FN46YMD6R
*** Script: Match found: V4W2T0917F
*** Script: Match found: HTM6NPHT7W
*** Script: Match found: X54WFQLNWM
*** Script: Match found: 6KWL4W3
*** Script: Match found: TMQQH6NV26
*** Script: Match found: XGFWJJ6WM4
*** Script: Match found: NYXVMJ9GH6
*** Script: Match found: JVJC9KQ0QT
*** Script: Match found: C02G7118MD6R
*** Script: Match found: C02FN465MD6R
*** Script: Match found: DYXNHWW73W
*** Script: Match found: C02RH01WG8WM
*** Script: Match found: 66QLRQ2
*** Script: Match found: X19GY2WYLH
*** Script: Match found: NJ6417KLJH
*** Script: Match found: A7AK011001248
[0:00:00.003] Expanding large row block (file.read: alm_asset, 10000 rows, 160000 dataSize)
[0:00:00.016] Compacting large row block (file.write: alm_asset 10000 rows 160000 saveSize)
*** Script: Match found: FOC1802U1BW
*** Script: Match found: WCAWZ1332959
*** Script: Match found: A7AK011007413
*** Script: Match found: 54
*** Script: Match found: W4M9561L42
*** Script: Match found: FGHPZ33
*** Script: Match found: 3PMLHR2
*** Script: Match found: QK9QXWXCW4
*** Script: Match found: LPY3H9Y5LX
*** Script: Match found: YT6927PPGP
*** Script: Match found: DFJW4WPG2X
*** Script: Match found: Q00HT0CFCG
*** Script: Match found: C02M60YPFD59
*** Script: Match found: A7AK011001244
*** Script: Match found: R7Q4KVKG9J
*** Script: Match found: P14RYY0WTG
*** Script: Match found: D25V60J5J1GP
*** Script: Match found: 48S07S2
*** Script: Match found: C07FT1VQQ6P0
*** Script: Match found: FVFHJ1GTQ05P
*** Script: Match found: HTF6WW1
*** Script: Match found: J31MVM21WH
*** Script: Match found: PNR46WGMXG
*** Script: Match found: VQXXPNX7M9
*** Script: Match found: C02DG132MD6R
*** Script: Match found: FVFHK3D1Q05P
*** Script: Match found: FVFHJ0ZJQ05P
*** Script: Match found: 82
*** Script: Match found: C02Z70L1LVDM
*** Script: Match found: T75527XTF7
*** Script: Match found: LX97LFCQMC
*** Script: Match found: A7PU011009087
*** Script: Match found: H2WFT0T7Q6P0
*** Script: Match found: H4LY921XV3
*** Script: Match found: VNB3B49463
*** Script: Match found: H2WHK0VEQ6NW
*** Script: Match found: 87KWMR2
*** Script: Match found: XCR9HD6YV7
*** Script: Match found: C02YJ20PJGH6
*** Script: Match found: X939JQGJXD
*** Script: Match found: C02FN47GMD6R
*** Script: Match found: 3952GC2
*** Script: Match found: 47MSMV2
*** Script: Match found: CNGXC24539
*** Script: Match found: H2WJ10ZSQ6P0
*** Script: Match found: HWMQLQWN6J
*** Script: Match found: C02FK1QEMD6R
*** Script: Match found: 9X5S4X3
*** Script: Match found: 27
*** Script: Match found: C02FN01FML88
*** Script: Match found: YL0JFV5WR4
*** Script: Match found: TWG70RVYW3
*** Script: Match found: C02DG12RMD6R
*** Script: Match found: C02FN46PMD6R
*** Script: Match found: HNRGJB2
*** Script: Match found: Q0V7TKX0WJ
*** Script: Match found: J09YFC45P9
*** Script: Match found: C02M60YSFD59
*** Script: Match found: D4X7RLXQRX
*** Script: Match found: 82
*** Script: Match found: H2WJF0LVQ6P0
*** Script: Match found: 26LLPN3
*** Script: Match found: VM2T6KX1XY
*** Script: Match found: P34MCYKQJR
*** Script: Match found: YQ27FH3XL4
*** Script: Match found: CND8F2S0KG
*** Script: Match found: J29N02V70X
*** Script: Match found: JP26HC747T
*** Script: Match found: FVFHN2CQQ05P
*** Script: Match found: W25X46R95X
*** Script: Match found: WGQXW0XC92
*** Script: Match found: 85JLZD3
*** Script: Match found: C02DT0BGMD6R
*** Script: Match found: C02DP89MMD6R
*** Script: Match found: BBEC.538181..ATI
*** Script: Match found: N0G19WNPJL
*** Script: Match found: C02DRAZLMD6R
*** Script: Match found: VQV04JX5N6
*** Script: Match found: C02F30BPMD6R
*** Script: Match found: Y6GCXTLJ7K
*** Script: Match found: R9NFP069VC
*** Script: Match found: 8DGTLS1
*** Script: Match found: JFX6XM43VJ
*** Script: Match found: H2WJJ010Q6P0
*** Script: Match found: PJY9V3HX3T
*** Script: Match found: G7DGMFWJKP
*** Script: Match found: CQ1FTP6KF4
*** Script: Match found: Q7V5H7LPWX
*** Script: Match found: HQM217L09T
*** Script: Match found: QMFWQ425XH
*** Script: Match found: C02G37NUMD6R
*** Script: Match found: V9TT6G7QF1
*** Script: Match found: DD136120226006
*** Script: Match found: NNFGP09G6K
*** Script: Match found: C07QM0A7G1J1
*** Script: Match found: WF4219TK76
*** Script: Match found: C1MPJ6MAG944
*** Script: Match found: JJ2444N3X2
*** Script: Match found: L7QD9LFH12
*** Script: Match found: LVL49RCXL2
*** Script: Match found: WMAZA8295008
*** Script: Match found: C02MD323FD59
*** Script: Match found: 81
*** Script: Match found: HTHQLVVNH7
*** Script: Match found: YVP2H639W3
*** Script: Match found: XP4Y2T97K7
*** Script: Match found: H2WJF0L3Q6P0
*** Script: Match found: H2WJF1GBQ6P0
*** Script: Match found: R59T3C2J4X
*** Script: Match found: CNDX247497
*** Script: Match found: YY39QGJ4N4
*** Script: Match found: XFMGVF499W
*** Script: Match found: V43WP9RXHY
*** Script: Match found: C02FN46AMD6R
*** Script: Match found: CJ4RYQ7WCY
*** Script: Match found: XN65G6X3HT
*** Script: Match found: 000000000000000000000000000000000000000000047
*** Script: Match found: 4BJD2Z3
*** Script: Match found: JMJ6DY4W39
*** Script: Match found: C02G7117MD6R
*** Script: Match found: FVFGP4U2Q05N
*** Script: Match found: C02G6132Q05R
*** Script: Match found: 81
*** Script: Match found: YR372XCY39
*** Script: Match found: VJWNVVQM23
*** Script: Match found: M24CQXYTG2
*** Script: Match found: 12D6SN2
*** Script: Match found: C02CK052MD6R
*** Script: Match found: 632015000581
*** Script: Match found: 632016000061
*** Script: Match found: VT090H62D0
*** Script: Match found: M46233YMVP
*** Script: Match found: 80511200093
*** Script: Match found: YDJ2WH97DP
*** Script: Match found: H2WJH0K8Q6P0
*** Script: Match found: R47WH362G6
*** Script: Match found: CN57DF30BP
*** Script: Match found: C02T5195H040
*** Script: Match found: C07QM0A5G1J1
*** Script: Match found: 27
*** Script: Match found: 2DNC3G2
*** Script: Match found: C02KF1D8FFT4
*** Script: Match found: 9TF6WW1
*** Script: Match found: 27
*** Script: Match found: YK9DN2P6HG
*** Script: Match found: CND9D4GB4R
*** Script: Match found: FNHT6M39TH
*** Script: Match found: R4NY0W029P
*** Script: Match found: KT2HCWC091
*** Script: Match found: 4NZ31Q2
*** Script: Match found: 93N1NV2
*** Script: Match found: QV7VQ0K7D1
*** Script: Match found: FOC1802X1J6
*** Script: Match found: XD23RVW7XM
*** Script: Match found: HPD4YXY42J
*** Script: Match found: 82
*** Script: Match found: FV73QGCXMK
*** Script: Match found: H7GYYDHJ70
*** Script: Match found: 54
*** Script: Match found: H00W2XT72L
*** Script: Match found: H2WF113XQ6NV
*** Script: Match found: PMT2FT9MY9
*** Script: Match found: C02G711DMD6R
*** Script: Match found: H2WJF0FBQ6P0
*** Script: Match found: 7FGZ6S2
*** Script: Match found: HYF4W12DX4
*** Script: Match found: GXRR97F205
*** Script: Match found: 000000000000000000000000000000000000000000047
*** Script: Match found: C02LL723FD59
*** Script: Match found: XGCH7RTXLL
*** Script: Match found: C02GM16EMD6R
*** Script: Match found: Y96KFLVXKM
*** Script: Match found: C02G710LMD6R
*** Script: Match found: C02Z22GNLVCF
*** Script: Match found: VG6XF2JXH5
*** Script: Match found: C02DRCY3MD6R
[0:00:00.002] Expanding large row block (file.read: alm_asset, 10000 rows, 160000 dataSize)
[0:00:00.019] Compacting large row block (file.write: alm_asset 10000 rows 160000 saveSize)
*** Script: Match found: M24L7RD2VP
*** Script: Match found: VRCYVYTQKC
*** Script: Match found: TV5VYXNW9P
*** Script: Match found: CNGCQ88043
*** Script: Match found: C02RT2SFG8WM
*** Script: Match found: Q6P1W6TH9P
*** Script: Match found: CW9F2P46Q0
*** Script: Match found: C02G7113MD6R
*** Script: Match found: C07YD0Y1JYVY
*** Script: Match found: K72M7N6H1J
*** Script: Match found: FC7GWCWFTP
*** Script: Match found: C4ZXTQ3
*** Script: Match found: NHYXFKW6WD
*** Script: Match found: C02G37PGMD6R
*** Script: Match found: 88SGN32
*** Script: Match found: TY7DNQ7952
*** Script: Match found: 10C2F8A
*** Script: Match found: C02DT1FGMD6R
*** Script: Match found: C02GD2HCMD6R
*** Script: Match found: QN2PF6V2D0
*** Script: Match found: C02G711JMD6R
*** Script: Match found: 000000000000000000000000000000000000000000047
*** Script: Match found: J4QJGD7K7Q
*** Script: Match found: JX2L3VXPWD
*** Script: Match found: 81
*** Script: Match found: C02DC0YMML86
*** Script: Match found: 70
*** Script: Match found: V73TC7N1XY
*** Script: Match found: X7D91L64DX
*** Script: Match found: FM2NKVCWJ9
*** Script: Match found: A5C4011118467
*** Script: Match found: F79C07LTXN
*** Script: Match found: CN59NFW0VS
*** Script: Match found: QTF43RP0WP
*** Script: Match found: A61D011004605
*** Script: Match found: MXH5XKXVKX
*** Script: Match found: C02FN46ZMD6R
*** Script: Match found: H244GC2
*** Script: Match found: WQP24TW7KK
*** Script: Match found: T90HJCM90P
*** Script: Match found: C07SN0TXG1J2
*** Script: Match found: 55
*** Script: Match found: A5C4011123823
*** Script: Match found: YRCVW0VP36
*** Script: Match found: GCBHMV2
*** Script: Match found: T6JWK057XM
*** Script: Match found: W9HFWNRF2W
*** Script: Match found: CHKP5S3
*** Script: Match found: W0FLMJ70YG
*** Script: Match found: 1
*** Script: Match found: 6X9XFC2
*** Script: Match found: FVFHJ0YYQ05P
*** Script: Match found: WG7DY66G1F
*** Script: Match found: H2WH30QKQ6P0
*** Script: Match found: DD136120224012
*** Script: Match found: C02GK0HDMD6T
*** Script: Match found: FY621R0Q26
*** Script: Match found: 29
*** Script: Match found: CNBH100389
*** Script: Match found: FVFHJ0ZNQ05P
*** Script: Match found: V46VKTVHWL
*** Script: Match found: HPXYVP37RX
*** Script: Match found: 12Q0S22
*** Script: Match found: C02FF0ESMD6R
*** Script: Match found: WC4KVF4F99
*** Script: Match found: QL6F9RM630
*** Script: Match found: H2WJQ03HQ6P0
*** Script: Match found: C02DG139MD6R
*** Script: Match found: 27
*** Script: Match found: X742HYD9MQ
*** Script: Match found: C5TSMH3
*** Script: Match found: FOC1802U1CR
*** Script: Match found: G37RYL9Q0W
*** Script: Match found: RYQ7MFDWY1
*** Script: Match found: QTJNVW67XL
*** Script: Match found: C02FN46WMD6R
*** Script: Match found: A7PU011007186
*** Script: Match found: C02FLAAEMD6R
*** Script: Match found: G4FKJM2
*** Script: Match found: C02G703JML88
*** Script: Match found: FOC1802Y7C4
*** Script: Match found: 6SSKMV2
*** Script: Match found: FVFF699AQ6LR
*** Script: Match found: C77DPY2
*** Script: Match found: A61H011005971
*** Script: Match found: 86
*** Script: Match found: W4Y7H1JFDH
*** Script: Match found: C02G37KQMD6R
*** Script: Match found: 70
*** Script: Match found: YQY6TJ4LYD
*** Script: Match found: 8VTY373
*** Script: Match found: G7DSYD3
*** Script: Match found: C02FN01TML88
*** Script: Match found: C02FN47EMD6R
*** Script: Match found: YQ167QD6RV
*** Script: Match found: D3C2GC2
*** Script: Match found: 87
*** Script: Match found: P4426Y6T4N
*** Script: Match found: H2WJF0L8Q6P0
*** Script: Match found: JLH214PRY9
*** Script: Match found: P9HK3YPL44
*** Script: Match found: C02TK2GYHF1R
*** Script: Match found: C02FN35JQ05N
*** Script: Match found: QL3WNH7Y7Y
*** Script: Match found: WCKPX0Q0QF
*** Script: Match found: 347GQ73
*** Script: Match found: R46Q71F2PW
*** Script: Match found: C02F734PMD6R
*** Script: Match found: C02G132JMD6R
*** Script: Match found: QN6N07CNV9
*** Script: Match found: FG60PFJXH6
*** Script: Match found: H2WH312QQ6P0
*** Script: Match found: C02DG12ZMD6R
*** Script: Match found: LH6N5VKMXX
*** Script: Match found: LVL49RCXL2
*** Script: Match found: R66907XDGQ
*** Script: Match found: WRFPMF7050
*** Script: Match found: Y33V932GY7
*** Script: Match found: A5AY011012590
*** Script: Match found: TWGDGP42HY
*** Script: Match found: CNDCGB8006
*** Script: Match found: YR4D4LFTXN
*** Script: Match found: JMR6RN2
*** Script: Match found: 792108000013
*** Script: Match found: C02DR3BRMD6R
*** Script: Match found: XD2700PH70
*** Script: Match found: VX1X90G6L7
*** Script: Match found: C02DV1L2MD6R
*** Script: Match found: C02DRAYWMD6R
*** Script: Match found: D25QR09YGQ17
*** Script: Match found: XCKQC5707Q
*** Script: Match found: WC435P694R
*** Script: Match found: D25LG2USF8JC
*** Script: Match found: V0VQ95WJNW
*** Script: Match found: HV29PD67TC
*** Script: Match found: DS/NTW-094TKJ-1280
*** Script: Match found: C02D90PYMD6R
*** Script: Match found: C02DT0V4MD6R
*** Script: Match found: W0WXHL79V2
*** Script: Match found: H2WJF1G8Q6P0
*** Script: Match found: X27VXVN77V
*** Script: Match found: Y0H993CQV2
*** Script: Match found: Q1W1Q0QXGC
*** Script: Match found: VWFYCQQJW6
*** Script: Match found: C02DC8B3MD6R
*** Script: Match found: P7HFW2TXGC
*** Script: Match found: MQTXD0YJXP
*** Script: Match found: 81
*** Script: Match found: QVMQQWJKTM
*** Script: Match found: VF5293F41X
*** Script: Match found: C02G711BMD6R
*** Script: Match found: 85
*** Script: Match found: H2WJF04AQ6P0
*** Script: Match found: 18
*** Script: Match found: JH6HF4V264
*** Script: Match found: FX6QK00P6F
*** Script: Match found: PXY29QKJJM
*** Script: Match found: VM9XDH2CX2
*** Script: Match found: WU2Q10076150
*** Script: Match found: 63MSMV2
*** Script: Match found: 7HDKJM2
*** Script: Match found: W1JQCJWFD9
*** Script: Match found: C02DJ0NKMD6R
*** Script: Match found: 70.L1XX.801169..TWCC
*** Script: Match found: 3Y3SVV3
*** Script: Match found: C02RT2PKG8WM
*** Script: Match found: H3KW67P59R
*** Script: Match found: A61H011006924
*** Script: Match found: C07SN0TXG1J2
*** Script: Match found: GQ65900MR6
*** Script: Match found: C02GD0E4ML7M
*** Script: Match found: YV7CYQ5K7M
*** Script: Match found: C02FF1TNMD6T
*** Script: Match found: FVFHJ0ZTQ05P
*** Script: Match found: F5V2MD4G9X
*** Script: Match found: FM5VBY3
*** Script: Match found: C02G7115MD6R
*** Script: Match found: WPWR49QT25
*** Script: Match found: C07YH30BJYW0
[0:00:00.004] Expanding large row block (file.read: alm_asset, 10000 rows, 160000 dataSize)
[0:00:00.016] Compacting large row block (file.write: alm_asset 10000 rows 160000 saveSize)
*** Script: Match found: YHY77N47HW
*** Script: Match found: C02FN01HML88
*** Script: Match found: A5C4011110994
*** Script: Match found: R6XVJR7740
*** Script: Match found: KPD46NG634
*** Script: Match found: XDDXP21721
*** Script: Match found: C02DG12TMD6R
*** Script: Match found: 20
*** Script: Match found: 632015000580
*** Script: Match found: XL6NHLH2RF
*** Script: Match found: TH92JJ9H2G
*** Script: Match found: WMHW9GWRXT
*** Script: Match found: JCWQFX6WL6
*** Script: Match found: TR4JR2N9RR
*** Script: Match found: C02TG07ZGY6N
*** Script: Match found: 70
*** Script: Match found: CNBCK8Z133
*** Script: Match found: 9FWTBY3
*** Script: Match found: 255H4E317P260729
*** Script: Match found: WGKXJGXNQM
*** Script: Match found: TNVTVKKWMY
*** Script: Match found: C02GJ0TJMD6R
*** Script: Match found: NX7JQMGKN1
*** Script: Match found: D25XV7U1J1GQ
*** Script: Match found: VWXWFCV7WV
*** Script: Match found: C02FN46RMD6R
*** Script: Match found: 85
*** Script: Match found: JJM4H62FDH
*** Script: Match found: PT9DXWXWXP
*** Script: Match found: 012076570857
*** Script: Match found: IUEC.769364.ATI
*** Script: Match found: C02QJ3PHG8WM
*** Script: Match found: K2M5F6HY9G
*** Script: Match found: QM407WGJGV
*** Script: Match found: MT991G6V6D
*** Script: Match found: W76HJMV43P
*** Script: Match found: Y5HYTXR5G9
*** Script: Match found: 1007P12
*** Script: Match found: C02FN5KCMD6R
*** Script: Match found: Y49TGR6VWY
*** Script: Match found: 31KKJ72
*** Script: Match found: QD3YPVF3V7
*** Script: Match found: C07S80KCG1J1
*** Script: Match found: X676T41KGF
*** Script: Match found: C07XKVHBJYVW
*** Script: Match found: C02FD6JDQ05N
*** Script: Match found: R4MD21V7FY
*** Script: Match found: VNB8H3416G
*** Script: Match found: C02G6133Q05R
*** Script: Match found: 000000000000000000000000000000000000000000047
*** Script: Match found: C02G711GMD6R
*** Script: Match found: FVFHJ0ZEQ05P
*** Script: Match found: 70
*** Script: Match found: BCPPSQ2
*** Script: Match found: LVVXJ5F6LX
*** Script: Match found: QX7MCYFKQH
*** Script: Match found: 54
*** Script: Match found: DMGMC671F1
*** Script: Match found: X3XX36G2YK
*** Script: Match found: T0WFYX9C7N
*** Script: Match found: NC2X921FGP
*** Script: Match found: W7PW6LC743
*** Script: Match found: C02KJ0MTFFT4
*** Script: Match found: 4RBWJ02
*** Script: Match found: C02G710KMD6R
*** Script: Match found: 95
*** Script: Match found: PJVHL0FR9N
*** Script: Match found: C02DG1LXMD6T
*** Script: Match found: C02G90A8MD6R
*** Script: Match found: H2WJH05CQ6P0
*** Script: Match found: C02FN471MD6R
*** Script: Match found: H2WJF0F7Q6P0
*** Script: Match found: C02FK1D2MD6R
*** Script: Match found: HFF996719T
*** Script: Match found: PYJY09Q43F
*** Script: Match found: AA2M011006164
*** Script: Match found: PVPJHGKJ23
*** Script: Match found: C02G37P2MD6R
*** Script: Match found: WCAV55658037
*** Script: Match found: JF5VBY3
*** Script: Match found: VNB3S06397
*** Script: Match found: 721828000008
*** Script: Match found: G17DP9P9DK
*** Script: Match found: FY6LM64076
*** Script: Match found: WJGW62HCVJ
*** Script: Match found: HHG73PJ47Y
*** Script: Match found: C02FN46CMD6R
*** Script: Match found: XRX27M073L
*** Script: Match found: D764M6C627
*** Script: Match found: C02XK19RJGH6
*** Script: Match found: H02MPWLFPF
*** Script: Match found: 10272DP
*** Script: Match found: C02DF2JFMD6R
*** Script: Match found: A5C2011107365
*** Script: Match found: V6954FMYKR
*** Script: Match found: XKRQX6LL6K
*** Script: Match found: C02GJ0TKMD6R
*** Script: Match found: WRW2N2XR6J
*** Script: Match found: H2WJF0CFQ6P0
*** Script: Match found: A7AK011001334
*** Script: Match found: 1VHT3M3
*** Script: Match found: YDY9P4NPJ1
*** Script: Match found: C1FJJRFNJG
*** Script: Match found: NY731YQPWH
*** Script: Match found: 2SS4PX2
*** Script: Match found: TTM271500AC
*** Script: Match found: Y6Q5CQ03PJ
*** Script: Match found: C02DG12MMD6R
*** Script: Match found: C02G37KPMD6R
*** Script: Match found: GWP0D42
*** Script: Match found: NYQR3GPL6W
*** Script: Match found: FV34GC2
*** Script: Match found: C02ZK3ZNLVDQ
*** Script: Match found: 81
*** Script: Match found: K4GQY007L5
*** Script: Match found: 9MQ5QN2
*** Script: Match found: XL4JY3DJRP
*** Script: Match found: T34T59VR4K
*** Script: Match found: C02G711FMD6R
*** Script: Match found: C02VL20PHTDF
*** Script: Match found: C02DT2V0ML7L
*** Script: Match found: C02G711HMD6R
*** Script: Match found: C02GJ0TQMD6R
*** Script: Match found: N0G9369P6K
*** Script: Match found: FVFGH5DMQ05P
*** Script: Match found: FOC1802Y7BG
*** Script: Match found: G0X9VHXJ07
*** Script: Match found: C02XV441JGH6
*** Script: Match found: FHY29GCQ5P
*** Script: Match found: FHPPSQ2
*** Script: Match found: C02F51SKML85
*** Script: Match found: 0
*** Script: Match found: C02G37M3MD6R
*** Script: Match found: H2WHV0TNQ6P0
*** Script: Match found: 3Y4S0G2
*** Script: Match found: 4QVCP72
*** Script: Match found: C02FN01TML88
*** Script: Match found: NY694GQXKD
*** Script: Match found: C02ZQ7VVMD6R
*** Script: Match found: B3DD7Y2
*** Script: Match found: 1007P12
*** Script: Match found: 6X9XFC2
*** Script: Match found: HLHYNK3
*** Script: Match found: C02G37NPMD6R
*** Script: Match found: Y6DXMFH63K
*** Script: Match found: QQDCPWVWGT
*** Script: Match found: 000000000000000000000000000000000000000000047
*** Script: Match found: C07DC00APJJ9
*** Script: Match found: C02G37NXMD6R
*** Script: Match found: C02FL4KMMD6R
*** Script: Match found: KQT4W4XQPK
*** Script: Match found: 4ZS7R53
*** Script: Match found: A4Y4011021594
*** Script: Match found: H2WHV0EFPJJ9
*** Script: Match found: RVQDT4GYYG
*** Script: Match found: C02G7110MD6R
*** Script: Match found: C02G37PCMD6R
*** Script: Match found: XDVHMFJ6RF
*** Script: Match found: C163HQJPGF
*** Script: Match found: C02DG12YMD6R
*** Script: Match found: 81
*** Script: Match found: C07S80L3G1J1
*** Script: Match found: C02FN2HHMD6T
*** Script: Match found: 4H5VBY3
*** Script: Match found: A61F011011875
*** Script: Match found: PGD9MJFCQV
*** Script: Match found: YVHWKG1HXG
*** Script: Match found: C02M60YFFD59
*** Script: Match found: C02DR9HWMD6R
*** Script: Match found: FB0MRL1
*** Script: Match found: CTGDWHFJ0L
*** Script: Match found: NMFWGC76H4
*** Script: Match found: C02GK0QJMD6T
*** Script: Match found: 69B0R72
*** Script: Match found: C02DQ27TMD6R
*** Script: Match found: HK7J33GMVQ
*** Script: Match found: C02XK10XJHD3
*** Script: Match found: M4N4D7X343
[0:00:00.002] Expanding large row block (file.read: alm_asset, 10000 rows, 160000 dataSize)
[0:00:00.014] Compacting large row block (file.write: alm_asset 10000 rows 160000 saveSize)
*** Script: Match found: HL9XQT2R03
*** Script: Match found: FK2CXYRWV4
*** Script: Match found: CPYR9Y2
*** Script: Match found: H2WJF048Q6P0
*** Script: Match found: GGX5M4XMPP
*** Script: Match found: QWTGY41WGM
*** Script: Match found: BZZTBY3
*** Script: Match found: C02FN47PMD6R
*** Script: Match found: C02DR9WEMD6R
*** Script: Match found: F0VQ0FHCYF
*** Script: Match found: D25NM00EF8J5
*** Script: Match found: C02DRAZ3MD6R
*** Script: Match found: D25WK06RJ1GQ
*** Script: Match found: C02TF7M7GTFM
*** Script: Match found: 82
*** Script: Match found: 80
*** Script: Match found: FOC1752X04X
*** Script: Match found: C02G703AML88
*** Script: Match found: GGK372W647
*** Script: Match found: G4YVW04QDT
*** Script: Match found: 29
*** Script: Match found: WD7V00X2NH
*** Script: Match found: XHLXYTR20X
*** Script: Match found: R77NTP9265
*** Script: Match found: KP4506QRHC
*** Script: Match found: 81
*** Script: Match found: C07FN1QQQ6P0
*** Script: Match found: D25RH01WGQ17
*** Script: Match found: WM6Y4L4V3F
*** Script: Match found: C02FN01QML88
*** Script: Match found: C02M60WPFD59
*** Script: Match found: QQT6KM7PFD
*** Script: Match found: H2WH30U0Q6P0
*** Script: Match found: KXQ37HR4YG
*** Script: Match found: C02F959EMD6R
*** Script: Match found: 20
*** Script: Match found: HD2NQPJ21M
*** Script: Match found: C02G37KRMD6R
*** Script: Match found: C02YH3EUJHD3
*** Script: Match found: C02NQ05HG3QD
*** Script: Match found: C02G710NMD6R
*** Script: Match found: GY75P67WH9
*** Script: Match found: C02MD325FD59
*** Script: Match found: 12YLR22
*** Script: Match found: H57MXH6374
*** Script: Match found: ESRIINC-1
*** Script: Match found: C02FN47RMD6R
*** Script: Match found: DH85VV3
*** Script: Match found: XVFKYCT4K3
*** Script: Match found: GTF6WW1
*** Script: Match found: H2WG30Y0Q6P0
*** Script: Match found: PMJPL2LK71
*** Script: Match found: CNRXJ84620
*** Script: Match found: 2L1WBY3
*** Script: Match found: CNDF112327
*** Script: Match found: C02FJ3T9MD6R
*** Script: Match found: C07YD0YEJYVY
*** Script: Match found: GX5YY4Y17H
*** Script: Match found: 96
*** Script: Match found: C02DG12LMD6R
*** Script: Match found: R3K0G9N2FY
*** Script: Match found: 41Q9LQ2
*** Script: Match found: W6YQ0NJ63P
*** Script: Match found: 84
*** Script: Match found: C02MD3CEFD59
*** Script: Match found: 4P041Q2
*** Script: Match found: Y9J5W3T5W0
*** Script: Match found: RPQCV4QNW4
*** Script: Match found: A5C4011117186
*** Script: Match found: C02F72UEML85
*** Script: Match found: WD9NNXXFQ2
*** Script: Match found: 8J1HK13
*** Script: Match found: H2WJF0LQQ6P0
*** Script: Match found: C02XJ4EBJGH6
*** Script: Match found: C02DRCN8MD6R
*** Script: Match found: A5C4011122489
*** Script: Match found: C02W52WQHTDF
*** Script: Match found: C02M60XGFD59
*** Script: Match found: C02FN5LUMD6R
*** Script: Match found: C07YH30BJYW0
*** Script: Match found: C02GJ0TUMD6R
*** Script: Match found: W63HPX79D2
*** Script: Match found: C239L33
*** Script: Match found: FOC1802U1E3
*** Script: Match found: XCR9HD6YV7
*** Script: Match found: F194C69FM9
*** Script: Match found: FVFGP4ZQQ05N
*** Script: Match found: C02RF1AGG8WM
*** Script: Match found: C02G37KSMD6R
*** Script: Match found: R27CYR9CYP
*** Script: Match found: XX7713KYQ5
*** Script: Match found: VNB3Y52070
*** Script: Match found: DL1WBY3
*** Script: Match found: W7H0FPDW2H
*** Script: Match found: 4P131Q2
*** Script: Match found: C02G711CMD6R
*** Script: Match found: P4K7YF3P34
*** Script: Match found: JD26M4N9N9
*** Script: Match found: PG94CFX2HP
*** Script: Match found: C02RV22CG8WM
*** Script: Match found: C02DG12MMD6R
*** Script: Match found: XFMG6QRYV6
*** Script: Match found: Y57RJ2V7X4
*** Script: Match found: W4TWKHK40W
*** Script: Match found: YDQ1GD9N4R
*** Script: Match found: 90
*** Script: Match found: C02FN46JMD6R
*** Script: Match found: JD7N0QJ2C7
*** Script: Match found: JPW2K2YWYL
*** Script: Match found: KVQ6GLF7G9
*** Script: Match found: JXRRVV3
*** Script: Match found: C07S80JFG1J1
*** Script: Match found: 1420P73
*** Script: Match found: BBYF.103372..ATI
*** Script: Match found: 82
*** Script: Match found: C02DG136MD6R
*** Script: Match found: XC2CW7T32M
*** Script: Match found: L5J3WRRW2H
*** Script: Match found: QNRY4359XM
*** Script: Match found: 3QZ5GH2
*** Script: Match found: 26
*** Script: Match found: VTQ0WGN4LD
*** Script: Match found: 90
*** Script: Match found: 564W8B3
*** Script: Match found: 1-80-119056
*** Script: Match found: FVFHJ0ZFQ05P
*** Script: Match found: DNBLYY2
*** Script: Match found: VNXV9WV0MX
*** Script: Match found: 20
*** Script: Match found: QXX7F023XH
*** Script: Match found: C02FG13XMD6R
*** Script: Match found: TKHYJPFJ2D
*** Script: Match found: VFJ7LN9264
*** Script: Match found: H2WH30M7Q6P0
*** Script: Match found: KX097DJFY3
*** Script: Match found: Y2N32CVM6J
*** Script: Match found: HNV34X5679
*** Script: Match found: H2WJF0LCQ6P0
*** Script: Match found: 4X1YBY3
*** Script: Match found: LL7DL2K4NT
*** Script: Match found: XRH4H2NQ0L
*** Script: Match found: FOC1802U1EJ
*** Script: Match found: P4G639VY94
*** Script: Match found: PKGW671JPG
*** Script: Match found: H2WJF0WKQ6P0
*** Script: Match found: TH95D1T16P
*** Script: Match found: V47L099XK4
*** Script: Match found: C02DQ04HML86
*** Script: Match found: H2WHJ20SQ6NV
*** Script: Match found: VN7W9DF6XM
*** Script: Match found: C02NQ01AG3QD
*** Script: Match found: C02G6131Q05R
*** Script: Match found: N9WY499521
*** Script: Match found: DKKKN32
*** Script: Match found: Y7HCQC4HT4
*** Script: Match found: CXJM60N006
*** Script: Match found: 442043635
*** Script: Match found: T2QQ4MH656
*** Script: Match found: FVFHJ2TSQ05P
*** Script: Match found: GXH94097XM
*** Script: Match found: 06F931G
*** Script: Match found: 48Y7T13
*** Script: Match found: W2MVF673M9
[0:00:00.003] Expanding large row block (file.read: alm_asset, 10000 rows, 160000 dataSize)
[0:00:00.015] Compacting large row block (file.write: alm_asset 10000 rows 160000 saveSize)
*** Script: Match found: KG6DG3J6YQ
*** Script: Match found: AUA343513
*** Script: Match found: X1HJKYF6LD
*** Script: Match found: R5HQ5642RN
*** Script: Match found: 5TF6WW1
*** Script: Match found: C02FN605MD6R
*** Script: Match found: C02CJ075LVDM
*** Script: Match found: D56W2HC4Q2
*** Script: Match found: CXDCQ423TH
*** Script: Match found: NC3W1746P9
*** Script: Match found: C02G7037ML88
*** Script: Match found: 94
*** Script: Match found: C02QW11NG8WM
*** Script: Match found: Y1VX5Y09RG
*** Script: Match found: J7C16RJKWX
*** Script: Match found: 55
*** Script: Match found: 10272DP
*** Script: Match found: C02FL9MQMD6R
*** Script: Match found: 82
*** Script: Match found: CPH7NQF12D
*** Script: Match found: C07FN1GPQ6P0
*** Script: Match found: 5CJD2Z3
*** Script: Match found: C02G711EMD6R
*** Script: Match found: C02FN472MD6R
*** Script: Match found: N1603P440N
*** Script: Match found: C02VL2YBHTDF
*** Script: Match found: C02KJ1QFFFT4
*** Script: Match found: C02FL2USMD6R
*** Script: Match found: HVY22H04RK
*** Script: Match found: RNJM62FHYH
*** Script: Match found: H3HN4X0MWN
*** Script: Match found: C02RG35XG8WM
*** Script: Match found: BBYF.102335..ATI
*** Script: Match found: A5C4011114438
*** Script: Match found: V060HYF2TM
*** Script: Match found: C02FN47TMD6R
*** Script: Match found: NKXQ7XHP3Q
*** Script: Match found: VM294WW4WH
*** Script: Match found: CNGCF8W0M3
*** Script: Match found: 000000000000000000000000000000000000000000047
*** Script: Match found: JL7TJ616XD
*** Script: Match found: A7PU011009096
*** Script: Match found: DJCJJM2
*** Script: Match found: 2UA7062FT3
*** Script: Match found: C02DG134MD6R
*** Script: Match found: V5623T5HJR
*** Script: Match found: C02GH3SHMD6R
*** Script: Match found: 4TF6WW1
*** Script: Match found: PH7G66GYQR
*** Script: Match found: FVFGP4YAQ05N
*** Script: Match found: C02JW0ZDDKQ5
*** Script: Match found: QTYYDJ9VXY
*** Script: Match found: FOC1802U1E0
*** Script: Match found: 7HCKXD3
*** Script: Match found: C02G7116MD6R
*** Script: Match found: N42724D69R
*** Script: Match found: C02YJ0W0JHD3
*** Script: Match found: C02G711MMD6R
*** Script: Match found: D659R4DY7H
*** Script: Match found: A7PU011005282
*** Script: Match found: 7CWXBY3
*** Script: Match found: FXXHGXJ67R
*** Script: Match found: NXWFPRH7F5
*** Script: Match found: G2M0XVFTVH
*** Script: Match found: CXH9V5L9JY
*** Script: Match found: C02YH3ETJHD3
*** Script: Match found: BKBDR73
*** Script: Match found: C02D11U3MD6R
*** Script: Match found: 81
*** Script: Match found: 82
*** Script: Match found: 64167FB9AE07
*** Script: Match found: 33PMQN2
*** Script: Match found: Y13790Q09H
*** Script: Match found: XLLQ4NQWL3
*** Script: Match found: NXPYYHT4JH
*** Script: Match found: AJ101802
*** Script: Match found: 97
*** Script: Match found: 20
*** Script: Match found: C02GJ3B8MD6R
*** Script: Match found: C02FN47CMD6R
*** Script: Match found: 5CZBC42
*** Script: Match found: C02G40JBMD6R
*** Script: Match found: H2WJH0CVQ6P0
*** Script: Match found: 49QYQQ2
*** Script: Match found: CND8F7QB1Z
*** Script: Match found: VWFYCQQJW6
*** Script: Match found: 97
*** Script: Match found: R12XJR3TDW
*** Script: Match found: D8PFHR2
*** Script: Match found: FVFGP4T6Q05N
*** Script: Match found: W4P6X53P3J
*** Script: Match found: GLWXBY3
*** Script: Match found: ACC2011020454
*** Script: Match found: CNBG203206
*** Script: Match found: 29
*** Script: Match found: MXCCF4K193
*** Script: Match found: D359YPKJQX
*** Script: Match found: YFG6N79K0G
*** Script: Match found: H2WJF0CEQ6P0
*** Script: Match found: RTH92662RL
*** Script: Match found: VCT138276
*** Script: Match found: X1KXDD2N9C
*** Script: Match found: 4LSLYY2
*** Script: Match found: BA100562
*** Script: Match found: FVFGP4ZJQ05N
*** Script: Match found: M630NJ1QHQ
*** Script: Match found: XJKXCL25FW
*** Script: Match found: 2JWXBY3
*** Script: Match found: D25XV7TYJ1GQ
*** Script: Match found: H3756MYG65
*** Script: Match found: 2UA75217H6
*** Script: Match found: USQC053754
*** Script: Match found: C02GJ3F3MD6R
*** Script: Match found: WQ699FY3Q3
*** Script: Match found: 000000000000000000000000000000000000000000047
*** Script: Match found: C02FD5UJMD6R
*** Script: Match found: HC546Q04X5
*** Script: Match found: 4T9WJ02
*** Script: Match found: C02DRAZ7MD6R
*** Script: Match found: XTXJJR9165
*** Script: Match found: G7QQMCQ6PN
*** Script: Match found: FOC1803U04J
*** Script: Match found: KG0X4Q5XHV
*** Script: Match found: K0G4VG9MVR
*** Script: Match found: A61H011010603
*** Script: Match found: GV254VLH3J
*** Script: Match found: G70R03X6R5
*** Script: Match found: 26
*** Script: Match found: C02C32EGLVDM
*** Script: Match found: LF7016WF45
*** Script: Match found: VMF7607PTQ
*** Script: Match found: YRW99396F1
*** Script: Match found: WRNYPYH6J9
*** Script: Match found: 792209000770
*** Script: Match found: C02CK051MD6R
*** Script: Match found: V43WP9RXHY
*** Script: Match found: C02DRCZ3MD6R
*** Script: Match found: 80
*** Script: Match found: NVGVXFDQGL
*** Script: Match found: W09WHTKHXD
*** Script: Match found: CCSXFC2
*** Script: Match found: C02QW121G8WM
*** Script: Match found: WQ1XY70RR9
*** Script: Match found: C02QG2AXG8WM
*** Script: Match found: 4Z8TRQ2
*** Script: Match found: 20
*** Script: Match found: 69B0R72
*** Script: Match found: JVK99Y3
*** Script: Match found: XP9M6MW5J9
*** Script: Match found: W9Q5K6D22C
*** Script: Match found: Q22G12P96R
*** Script: Match found: H1X8L13
*** Script: Match found: CBT5K13
*** Script: Match found: C02G710MMD6R
*** Script: Match found: FOC1802U19J
*** Script: Match found: R43J26V55X
*** Script: Match found: N9019R59C4
*** Script: Match found: C02ZK46YLVDQ
*** Script: Match found: HM9TF6JWMG
*** Script: Match found: FXH0J7T7JC
*** Script: Match found: X9572P7Q9R
*** Script: Match found: C02G88PPMD6R
*** Script: Match found: C02DG137MD6R
*** Script: Match found: C02ZK46YLVDQ
*** Script: Match found: 70
*** Script: Match found: C6W9PY2
*** Script: Match found: 10272CP
*** Script: Match found: 36
*** Script: Match found: C1F739R1XP
*** Script: Match found: JHLFCGJWL3
*** Script: Match found: C02DRAZBMD6R
*** Script: Match found: N6NXHFVY41
*** Script: Match found: VWY0X7K4HD
*** Script: Match found: C02FN462MD6R
*** Script: Match found: C02NQ00JG3QD
*** Script: Match found: N40J0X44DP
*** Script: Match found: 3X74QN2
*** Script: Match found: PQ3PMGKQXL
*** Script: Match found: C07DC00BPJJ9
*** Script: Match found: A7PU011008244
*** Script: Match found: C02D8620MD6R
*** Script: Match found: RYW09CH00D
*** Script: Match found: 46TMFB2
*** Script: Match found: BG6NDY3
*** Script: Match found: C02FN47FMD6R
*** Script: Match found: C02G37P4MD6R
*** Script: Match found: C02CJ0K3LVDM
*** Script: Match found: HJLFK63
*** Script: Match found: M6GD9D52TV
*** Script: Match found: VQ05Q79DCR
*** Script: Match found: H244GC2
*** Script: Match found: C02FP1HKMD6R
*** Script: Match found: 82
*** Script: Match found: G4QT956KXF
*** Script: Match found: C02DQ17BMD6R
*** Script: Match found: PQ7KVXX6HW
*** Script: Match found: M7744X42GP
*** Script: Match found: CJWWV4G1V9
*** Script: Match found: F222106930
*** Script: Match found: FLMC3G2
*** Script: Match found: H2WJF0MRQ6P0
*** Script: Match found: 7CMW373
*** Script: Match found: W1K3G6MGJ2
[0:00:00.002] Expanding large row block (file.read: alm_asset, 10000 rows, 160000 dataSize)
[0:00:00.015] Compacting large row block (file.write: alm_asset 10000 rows 160000 saveSize)
*** Script: Match found: C02WL0C6HTDF
*** Script: Match found: A5C4011117165
*** Script: Match found: HP26XQC29X
*** Script: Match found: C07SN0TWG1J2
*** Script: Match found: 1NBLYY2
*** Script: Match found: CZC14822SF
*** Script: Match found: YRH647FF6N
*** Script: Match found: 2GHKN7ZQ
*** Script: Match found: MXBPMBC216
*** Script: Match found: A7PU011008933
*** Script: Match found: Q2H76P9RNY
*** Script: Match found: XR2R6DP9M3
*** Script: Match found: YKG21H00WW
*** Script: Match found: S227686X6B35081
*** Script: Match found: C2CVBY3
*** Script: Match found: VLWTJVV6KJ
*** Script: Match found: N335020GQM
*** Script: Match found: A7PY011001404
*** Script: Match found: C6V8PY2
*** Script: Match found: N9KQ0H6XD3
*** Script: Match found: C02GJ0TWMD6R
*** Script: Match found: CGF3FN2P6Q
*** Script: Match found: FY4LMV2
*** Script: Match found: C02FN019ML88
*** Script: Match found: 000000000000000000000000000000000000000000047
*** Script: Match found: C02FN47GMD6R
*** Script: Match found: C02DG135MD6R
*** Script: Match found: XC74Y1J9WJ
*** Script: Match found: 71
*** Script: Match found: 80
*** Script: Match found: FVFHJ0Z9Q05P
*** Script: Match found: 55
*** Script: Match found: C02DV359Q05N
*** Script: Match found: C02DK5GRMD6R
*** Script: Match found: R2FQ9F21N2
*** Script: Match found: GM434WCX9C
*** Script: Match found: XJ2YQ4NQ25
*** Script: Match found: M4T6NP27P0
*** Script: Match found: C02D120BMD6R
*** Script: Match found: G44M79PYTV
*** Script: Match found: C02G3219MD6R
*** Script: Match found: JQD3WV3
*** Script: Match found: XQCQ99P9HP
*** Script: Match found: FVG49R76CR
*** Script: Match found: 000000000000000000000000000000000000000000047
*** Script: Match found: FVFHK09SQ05P
*** Script: Match found: WVFNKH95F4
*** Script: Match found: 6VF6WW1
*** Script: Match found: C02G950DMD6R
*** Script: Match found: NR32LKV22M
*** Script: Match found: C02G7791MD6R
*** Script: Match found: H2WJF0KUQ6P0
*** Script: Match found: CX5PYY1
*** Script: Match found: VWNVF1QJH7
*** Script: Match found: JYR3XWYJ3M
*** Script: Match found: YW06X5XVTY
*** Script: Match found: J48D2J3
*** Script: Match found: Q6Q74F4LLF
*** Script: Match found: NDCWV3CXM7
*** Script: Match found: C02D117CMD6R
*** Script: Match found: H2WJF0B8Q6P0
*** Script: Match found: CND1G31191
*** Script: Match found: Y2V5L93G5W
*** Script: Match found: C02PJ100G3QP
*** Script: Match found: HX95K13
*** Script: Match found: 15PDLQ2
*** Script: Match found: C02QW1D4G8WM
*** Script: Match found: C71DPY2
*** Script: Match found: JPBCC1D22G
*** Script: Match found: 9ZFBG72
*** Script: Match found: FOC1802X1HW
*** Script: Match found: C02DRAYYMD6R
*** Script: Match found: C02FN47JMD6R
*** Script: Match found: HKDFN32
*** Script: Match found: DD136120225010
*** Script: Match found: FD9V6WRXGJ
*** Script: Match found: 7HDKJM2
*** Script: Match found: 5T85GC2
*** Script: Match found: C02C98MDMD6R
*** Script: Match found: 1TF6WW1
*** Script: Match found: A5C4011117775
*** Script: Match found: MJ09A6MA
*** Script: Match found: YKXXVXGWP1
*** Script: Match found: FVFHJ0ZLQ05P
*** Script: Match found: H2WH60C6PJJ9
*** Script: Match found: HYVJKXQW3H
*** Script: Match found: PV623PYTR6
*** Script: Match found: D0Q19D6MPY
*** Script: Match found: 29
*** Script: Match found: C02G7112MD6R
*** Script: Match found: FXXQ421XYW
*** Script: Match found: XLN642N4QJ
*** Script: Match found: 49QYQQ2
*** Script: Match found: C02DG12JMD6R
*** Script: Match found: JTF6WW1
*** Script: Match found: F4JX8Y3
*** Script: Match found: VWR0X99VP9
*** Script: Match found: Y5F97957VY
*** Script: Match found: C02G37P8MD6R
*** Script: Match found: J4XYQ5J3VX
*** Script: Match found: A7PU011004433
*** Script: Match found: D70GXK2
*** Script: Match found: 70
*** Script: Match found: XLPGH6YC7F
*** Script: Match found: CQ9GKW7GY7
*** Script: Match found: HGGF6GWQGJ
*** Script: Match found: YD6R7QXLXM
*** Script: Match found: K596RQLGDM
*** Script: Match found: C02FN01RML88
*** Script: Match found: FOC1803Y0X3
*** Script: Match found: JC4S9Y2
*** Script: Match found: C02ZK40NLVDQ
*** Script: Match found: A7PU011006133
*** Script: Match found: C02Z70D4LVDM
*** Script: Match found: C02G711NMD6R
*** Script: Match found: TYQDKGMGJ0
*** Script: Match found: 81
*** Script: Match found: C02F73UWMD6R
*** Script: Match found: 87
*** Script: Match found: C02DR858MD6R
*** Script: Match found: DNBLYY2
*** Script: Match found: C02QH2PLG8WM
*** Script: Match found: RD2YDWYD72
*** Script: Match found: NXQ70QJD91
*** Script: Match found: C1FJJRFNJG
*** Script: Match found: H2WJF0B3Q6P0
*** Script: Match found: CCZRRF2
*** Script: Match found: FVFGV1YDQ05Q
*** Script: Match found: C02DG131MD6R
*** Script: Match found: W4FQD4L7W7
*** Script: Match found: C02FN01KML88
*** Script: Match found: 51
*** Script: Match found: CNBH111369
*** Script: Match found: C02G711PMD6R
*** Script: Match found: JRLKMV2
*** Script: Match found: H27F3Y4NX3
*** Script: Match found: C1MPJ6MCG944
*** Script: Match found: JAE214104V4
*** Script: Match found: JPRC98Z07Q
*** Script: Match found: 9VF6WW1
*** Script: Match found: T749VW149Y
*** Script: Match found: C02G703HML88
*** Script: Match found: H2WFM16NPJJ9
*** Script: Match found: V0M4D2KXXV
*** Script: Match found: RTHHGX6JH1
*** Script: Match found: 1
*** Script: Match found: YVXJL7V1Q3
*** Script: Match found: LD79VTYYV0
*** Script: Match found: 5QKFZV1
*** Script: Match found: FSF6WW1
*** Script: Match found: GJ6T46W4VM
*** Script: Match found: C02DQ201MD6R
*** Script: Match found: CDWXBY3
*** Script: Match found: C02FN5KFMD6R
*** Script: Match found: C02FN01DML88
*** Script: Match found: WV56YXP0GG
*** Script: Match found: H2WH30MEQ6P0
*** Script: Match found: PC7R1PXJ2N
*** Script: Match found: 346SHM2
*** Script: Match found: C02QG2AXG8WM
*** Script: Match found: C02DRAYXMD6R
*** Script: Match found: P047LKXLG4
*** Script: Match found: NX4V0QWFM2
*** Script: Match found: PC4CQDHJ06
*** Script: Match found: 4RLQJ02
*** Script: Match found: C02G710ZMD6R
*** Script: Match found: T9WC6LGXFJ
*** Script: Match found: C02NPB98G3QD
*** Script: Match found: A7AK011002770
*** Script: Match found: YYXFXG779T
*** Script: Match found: FOC1803U05H
*** Script: Match found: H2WJF0CDQ6P0
*** Script: Match found: C02DQ27SMD6R
*** Script: Match found: H12DHJYZPN7C
*** Script: Match found: 2GFZBY3
*** Script: Match found: JK216FFHL2
*** Script: Match found: B9Q5K13
[0:00:00.003] Expanding large row block (file.read: alm_asset, 10000 rows, 160000 dataSize)
[0:00:00.015] Compacting large row block (file.write: alm_asset 10000 rows 160000 saveSize)
*** Script: Match found: FOC1749Y1E5
*** Script: Match found: R9FR4NMW9L
*** Script: Match found: 85
*** Script: Match found: R6YPF0JWY9
*** Script: Match found: C02G710XMD6R
*** Script: Match found: 1
*** Script: Match found: HY55264KHY
*** Script: Match found: J9D4YXM36F
*** Script: Match found: 4QN6WW1
*** Script: Match found: GK7H9R3
*** Script: Match found: A7PU011009169
*** Script: Match found: HP1VYVYW24
*** Script: Match found: N96J2X9N9X
*** Script: Match found: 7HCKXD3
*** Script: Match found: C02XV42XJGH6
*** Script: Match found: V2HXV09914
*** Script: Match found: C02FN477MD6R
*** Script: Match found: 5V4PL33
*** Script: Match found: 29
*** Script: Match found: C02ZX4WWMD6T
*** Script: Match found: JPBCC520QB
*** Script: Match found: A5C4011121722
*** Script: Match found: C02NQ0DLG3QD
*** Script: Match found: C02KJ1R2FFT4
*** Script: Match found: H2WHP0K8Q6NW
*** Script: Match found: C02XT3ZNJGH5
*** Script: Match found: C02XK11WJHD3
*** Script: Match found: L023TDQ6QF
*** Script: Match found: JM6G9R7MLV
*** Script: Match found: X2C4C02NJK
*** Script: Match found: YJXRL2YGQM
*** Script: Match found: 20
*** Script: Match found: C02G711QMD6R
*** Script: Match found: GQD616HXGK
*** Script: Match found: H2WJF0LXQ6P0
*** Script: Match found: PTPCGGWG62
*** Script: Match found: CND0353DFM
*** Script: Match found: JLC72TJ25D
*** Script: Match found: C02YJ2KZJGH6
*** Script: Match found: P2JWT700DK
*** Script: Match found: 10JN6Y2
*** Script: Match found: C02GD0DUML7M
*** Script: Match found: 5CG0286P3M
*** Script: Match found: YQJLY494RT
*** Script: Match found: VLW6JG6CQQ
*** Script: Match found: H2WJF0LDQ6P0
*** Script: Match found: H2WJF0MZQ6P0
*** Script: Match found: V3W2NX7W5G
*** Script: Match found: C02DT1FTMD6R
*** Script: Match found: 49.HMXX.000863.COXC
*** Script: Match found: FWPVHW532P
*** Script: Match found: GRWSFC2
*** Script: Match found: PMHFW0JR9J
*** Script: Match found: H2WG72SBQ6NY
*** Script: Match found: GW4TV3W494
*** Script: Match found: QTLCFH7WML
*** Script: Match found: C02FN01NML88
*** Script: Match found: C02FN47LMD6R
*** Script: Match found: 64167FB892D8
*** Script: Match found: HXYH4756DN
*** Script: Match found: T5W5C29D4Q
*** Script: Match found: WGLC9CR32W
*** Script: Match found: C02DG133MD6R
*** Script: Match found: CND8F1Q628
*** Script: Match found: FW5C7VC2YF
*** Script: Match found: 5VF6WW1
*** Script: Match found: WWY3Y2KWRL
*** Script: Match found: 3VY03W2
*** Script: Match found: RD6C49F7KF
*** Script: Match found: CNDCGB80TT
*** Script: Match found: P56YM07T6X
*** Script: Match found: 80
*** Script: Match found: QTFCU30210014
*** Script: Match found: XCRHH67XFH
*** Script: Match found: C07J106DPJJ9
*** Script: Match found: 82
*** Script: Match found: FVFHJ0ZMQ05P
*** Script: Match found: XH02X56VD2
*** Script: Match found: C4Q713567
*** Script: Match found: GW2VWWR7J0
*** Script: Match found: C02FC3XPMD6R
*** Script: Match found: 77GCY33
*** Script: Match found: 6KQ2GC2
*** Script: Match found: GK9721N7JW
*** Script: Match found: C02YJ2HPJGH6
*** Script: Match found: 48Y9T13
*** Script: Match found: P9T0H2WQN6
*** Script: Match found: JGGRZD3
*** Script: Match found: FTF6WW1
*** Script: Match found: YHX7F6K7Q0
*** Script: Match found: FOC1803U001
*** Script: Match found: D5737JT72L
*** Script: Match found: K640YX516L
*** Script: Match found: NLFYFVF091
*** Script: Match found: HPN6WW1
*** Script: Match found: C02FN474MD6R
*** Script: Match found: VL99NG0G63
*** Script: Match found: VGPHWQXGTC
*** Script: Match found: C02FN46UMD6R
*** Script: Match found: F141M63
*** Script: Match found: C07D92FPPJJ9
*** Script: Match found: R40KN7M70K
*** Script: Match found: TXF7NKW7QG
*** Script: Match found: X6QNQG6LM9
*** Script: Match found: C02G37NSMD6R
*** Script: Match found: V4H3HJC6QC
*** Script: Match found: FOC1802Y2AE
*** Script: Match found: C02S33EMG8WM
*** Script: Match found: PN2M2CH6XD
*** Script: Match found: WX7R466T2H
*** Script: Match found: H2CG6T07Q2
*** Script: Match found: 5X8DR73
*** Script: Match found: 9BJD2Z3
*** Script: Match found: VT4GK66DQL
*** Script: Match found: C02FN5KVMD6R
*** Script: Match found: C02FN604MD6R
*** Script: Match found: H2WJQ054Q6P0
*** Script: Match found: 000000000000000000000000000000000000000000047
*** Script: Match found: T63044Y1VX
*** Script: Match found: VVVQN4DX4N
*** Script: Match found: FM2M934YX3
*** Script: Match found: Y62CV2KE
*** Script: Match found: C07DC0EMPJJ9
*** Script: Match found: A61H011006926
*** Script: Match found: C02FN5KDMD6R
*** Script: Match found: FOC1748Z56F
*** Script: Match found: BKKBRQ3
*** Script: Match found: XQNWQXD46J
*** Script: Match found: C07YD0YDJYVY
*** Script: Match found: JN6349GCFD
*** Script: Match found: P7X36VYY24
*** Script: Match found: 2GHLZQ3M
*** Script: Match found: C02FN47NMD6R
*** Script: Match found: DD136120226002
*** Script: Match found: H2WFK02APJJ9
*** Script: Match found: QTFCU3021003F
*** Script: Match found: A7R0017013089
*** Script: Match found: 720VBY3
*** Script: Match found: C02G7114MD6R
*** Script: Match found: J363YY3YXM
*** Script: Match found: H2WJH06TQ6P0
*** Script: Match found: JPBFR11456
*** Script: Match found: C02DRCN9MD6R
*** Script: Match found: XRQY29QT54
*** Script: Match found: Y6QQCH4QRX
*** Script: Match found: A61H011011320
*** Script: Match found: 442593696
*** Script: Match found: C02GJ0TSMD6R
*** Script: Match found: C02FN467MD6R
*** Script: Match found: 70
*** Script: Match found: C02DRAZXMD6R
*** Script: Match found: C02JJHKJ77
*** Script: Match found: XGWMHYHGD2
*** Script: Match found: CFVP37GWCJ
*** Script: Match found: P211FQCLY6
*** Script: Match found: K6L61LC6TQ
*** Script: Match found: 0643F4A
*** Script: Match found: HT6D9RLVJV
*** Script: Match found: VX910JC2FR
*** Script: Match found: C02G710TMD6R
*** Script: Match found: 4Z8TRQ2
*** Script: Match found: C02G37PBMD6R
*** Script: Match found: 950A9157
[0:00:00.002] Expanding large row block (file.read: alm_asset, 10000 rows, 160000 dataSize)
[0:00:00.016] Compacting large row block (file.write: alm_asset 10000 rows 160000 saveSize)
*** Script: Match found: CNDF112387
*** Script: Match found: H6YV0F927G
*** Script: Match found: HCV2X65GXT
*** Script: Match found: H2WH313QQ6P0
*** Script: Match found: DGVJHJN7FX
*** Script: Match found: 81
*** Script: Match found: V7LYVX1WGM
*** Script: Match found: D43CHQQ3YN
*** Script: Match found: LMHG1HWHX5
*** Script: Match found: 440819944
*** Script: Match found: KMQKN93993
*** Script: Match found: 6BLVZH3
*** Script: Match found: G6MC4J7GFT
*** Script: Match found: 70
*** Script: Match found: C02XN4EGJGH6
*** Script: Match found: 4KKQ0Z2
*** Script: Match found: XYW57CJPX7
*** Script: Match found: H2WJH0EGQ6P0
*** Script: Match found: C02GD0DNML7M
*** Script: Match found: C6TCPY2
*** Script: Match found: FRXYQTJ3J0
*** Script: Match found: 27
*** Script: Match found: H2WJF0M6Q6P0
*** Script: Match found: 4P041Q2
*** Script: Match found: H2WHV0U5Q6P0
*** Script: Match found: 87
*** Script: Match found: H7Y02H75H9
*** Script: Match found: C07D92ZBPJJ9
*** Script: Match found: JZM1NV2
*** Script: Match found: XDL7LL7C30
*** Script: Match found: A4Y4011003708
*** Script: Match found: FW0QLX2
*** Script: Match found: A61H011010566
*** Script: Match found: HD65F0WQMT
*** Script: Match found: G16XXYL77H
*** Script: Match found: J6LPY9775Y
*** Script: Match found: C07QM0A2G1J1
*** Script: Match found: HXTJQ6667K
*** Script: Match found: FOC1803X04N
*** Script: Match found: T9G4YDQDX4
*** Script: Match found: 4KKQ0Z2
*** Script: Match found: H2WH30TFQ6P0
*** Script: Match found: QNH3YD06TM
*** Script: Match found: BCWN3132
*** Script: Match found: C02FN464MD6R
*** Script: Match found: 7HDKJM2
*** Script: Match found: C02DC0YPML86
*** Script: Match found: GN5VBY3
*** Script: Match found: 4SF6WW1
*** Script: Match found: FOC1802X1GY
*** Script: Match found: FVFHJ0Z2Q05P
*** Script: Match found: 35TJMV2
*** Script: Match found: R2QKPWY91J
*** Script: Match found: GMXQPVVQTT
*** Script: Match found: C02G703BML88
*** Script: Match found: 99X1L33
*** Script: Match found: FOC1802U1CZ
*** Script: Match found: R37CR46HJ7
*** Script: Match found: C02GJ0TRMD6R
*** Script: Match found: C02C9AHTMD6R
*** Script: Match found: 20
*** Script: Match found: 80511200121
*** Script: Match found: 2MFR4X3
*** Script: Match found: C02FN01AML88
*** Script: Match found: C02C40NTMD6R
*** Script: Match found: C02NQ0DPG3QD
*** Script: Match found: BSF6WW1
*** Script: Match found: JTFJ7MM93Y
*** Script: Match found: P2Q1H72619
*** Script: Match found: A7PU011006104
*** Script: Match found: PV75FHL2DF
*** Script: Match found: NTQPY4M17J
*** Script: Match found: 81
*** Script: Match found: FOC1802Y79N
*** Script: Match found: JPDCDCQ16W
*** Script: Match found: J17YH16L4H
*** Script: Match found: V9T69KQ3CP
*** Script: Match found: 80
*** Script: Match found: C02F959BMD6R
*** Script: Match found: C02CCDNXMD6M
*** Script: Match found: T7RQP9PVDQ
*** Script: Match found: C02FN01BML88
*** Script: Match found: H2WGN1ZRQ6P0
*** Script: Match found: C07SN0TTG1J2
*** Script: Match found: C02FL4UAMD6R
*** Script: Match found: PDY71F02L0
*** Script: Match found: C02FN473MD6R
*** Script: Match found: 1
*** Script: Match found: GSF6WW1
*** Script: Match found: C02DRAZTMD6R
*** Script: Match found: PP2FV5V6FT
*** Script: Match found: KVKXMT99HK
*** Script: Match found: C02FJ3DUMD6R
*** Script: Match found: VQX626XQ2J
*** Script: Match found: C02G37PDMD6R
*** Script: Match found: V4NVG2RCP7
*** Script: Match found: WFX9921JP4
*** Script: Match found: A5C4011115513
*** Script: Match found: D6K7M72
*** Script: Match found: FOC1802U1DT
*** Script: Match found: MJ05VG98
*** Script: Match found: RQ60PJH6JF
*** Script: Match found: 5WN6H62
*** Script: Match found: C07S80L4G1J1
*** Script: Match found: C02GK0QSMD6T
*** Script: Match found: TQ9VFH93D7
*** Script: Match found: THYF7PVWJ9
*** Script: Match found: C02C9AGAMD6R
*** Script: Match found: 6SJFQ53
*** Script: Match found: C02TF3UFGTFM
*** Script: Match found: C02GG2PTMD6R
*** Script: Match found: Q0V7TKX0WJ
*** Script: Match found: 2WVS9Y2
*** Script: Match found: 10272CP
*** Script: Match found: W3WTGV21N9
*** Script: Match found: C02DG12SMD6R
*** Script: Match found: C02DT1FUMD6R
*** Script: Match found: VDGQ0HFWTY
*** Script: Match found: C02GJ1CJML85
*** Script: Match found: C02FF38JMD6T
*** Script: Match found: VT2D7MGK2J
*** Script: Match found: MQHR9G721V
*** Script: Match found: D67D269T7L
*** Script: Match found: FOC1915R28T
*** Script: Match found: C02GC5GGQ05N
*** Script: Match found: C02FN47AMD6R
*** Script: Match found: A7AK011002096
*** Script: Match found: WL7XKF7L44
*** Script: Match found: 44CJ3F3
*** Script: Match found: 7823D0P
*** Script: Match found: C02GJ0TNMD6R
*** Script: Match found: LQHXHP6D91
*** Script: Match found: C02DG12XMD6R
*** Script: Match found: QRYWKPFCYF
*** Script: Match found: PCWCW9F2VQ
*** Script: Match found: H2WH30TBQ6P0
*** Script: Match found: C02DR8HTMD6T
*** Script: Match found: JQ6CQQHR7Q
*** Script: Match found: A5C4011118439
*** Script: Match found: WGJPLQ6YH1
*** Script: Match found: LDW4Q043F1
*** Script: Match found: 81
*** Script: Match found: CNCCDB30HQ
*** Script: Match found: C02GD1Q3Q05N
*** Script: Match found: C02FN47HMD6R
*** Script: Match found: H4492Y332T
*** Script: Match found: C02CK0DFMD6R
*** Script: Match found: C02FC0UJMD6T
*** Script: Match found: LNQ6DK4QP4
*** Script: Match found: YYH2R14V2Q
*** Script: Match found: H2WHR0TMQ6P0
*** Script: Match found: KN2J4GPWGP
*** Script: Match found: QQN4LFHWKP
*** Script: Match found: WV09TP7P7R
*** Script: Match found: JSF6WW1
*** Script: Match found: MLYF.115768..ATI
*** Script: Match found: FVFHJ0YSQ05P
*** Script: Match found: 5CG8125XTL
*** Script: Match found: H2WJF0K6Q6P0
*** Script: Match found: C02DQ1RRMD6R
*** Script: Match found: GW3N2C2XJJ
*** Script: Match found: C02D90W5MD6R
*** Script: Match found: C02F55REMD6R
*** Script: Match found: C02DT1FFMD6R
*** Script: Match found: GG3L1M2
*** Script: Match found: G17CM619TK
*** Script: Match found: C02DH1DMMD6R
*** Script: Match found: C02DC0YNML86
*** Script: Match found: 8CG83335KL
*** Script: Match found: DNQVD9H44P
*** Script: Match found: C02KJ1Q7FFT4
*** Script: Match found: C02FN466MD6R
[0:00:00.002] Expanding large row block (file.read: alm_asset, 7492 rows, 119872 dataSize)
[0:00:00.015] Compacting large row block (file.write: alm_asset 10000 rows 160000 saveSize)
*** Script: Match found: CN0CS02637
*** Script: Match found: BTF6WW1
*** Script: Match found: C02G711KMD6R
*** Script: Match found: KT25FPPVQ0
*** Script: Match found: VTR2410F23
*** Script: Match found: H1959JYT23
*** Script: Match found: 7MN9KD3
*** Script: Match found: 70
*** Script: Match found: W4PJLF95RY
*** Script: Match found: QQ01QJXY0J
*** Script: Match found: C02FN479MD6R
*** Script: Match found: 87KWMR2
*** Script: Match found: FVFHJ2U6Q05P
*** Script: Match found: C02DRCZ8MD6R
*** Script: Match found: C02CK0FJMD6T
*** Script: Match found: N9CJGDH9NQ
*** Script: Match found: KY9QP5P6P0
*** Script: Match found: C02FN5LSMD6R
*** Script: Match found: MG7329P0RT
*** Script: Match found: CNDF245911
*** Script: Match found: N6XWKLGKVF
*** Script: Match found: 3VPR4X3
*** Script: Match found: 86
*** Script: Match found: C2FD3J3
*** Script: Match found: VJ9KMXXWHK
*** Script: Match found: PWFK72FHYR
*** Script: Match found: J69JFVWXHP
*** Script: Match found: CM86CP2
*** Script: Match found: H4C0D3W7F1
*** Script: Match found: N4CYYP4F33
*** Script: Match found: J36WHWYXJ2
*** Script: Match found: 2GQRYD3
*** Script: Match found: 5GZC0N2
*** Script: Match found: A5C4011118473
*** Script: Match found: H2WJF0MYQ6P0
*** Script: Match found: C02YW35RLVDQ
*** Script: Match found: WTWWXL4W5P
*** Script: Match found: C02G703KML88
*** Script: Match found: C02G37P1MD6R
*** Script: Match found: T9GJD2LTWY
*** Script: Match found: GV206WMYY9
*** Script: Match found: QVV6KP2R63
*** Script: Match found: T0YXR59FJD
*** Script: Match found: L9YVWJ5G6C
*** Script: Match found: 3TF6WW1
*** Script: Match found: C02CH2R6JV40
*** Script: Match found: HJQVQMM61W
*** Script: Match found: 81
*** Script: Match found: C02FN460MD6R
*** Script: Match found: FOC1915R23Z
*** Script: Match found: V2QCTP4X15
*** Script: Match found: RQ2T297GXD
*** Script: Match found: QV9W63XL2R
*** Script: Match found: C02YH3EUJHD3
*** Script: Match found: 792209000878
*** Script: Match found: 627WXY2
*** Script: Match found: FOC1803X057
*** Script: Match found: C02DG138MD6R
*** Script: Match found: C02CJ0JZLVDM
*** Script: Match found: A7PU011007166
*** Script: Match found: C02QN21MG8WL
*** Script: Match found: P03T24L2YM
*** Script: Match found: H4TGV1PGPN7C
*** Script: Match found: XRVQWQVV6N
*** Script: Match found: C02FN46GMD6R
*** Script: Match found: Q7XLFJ9TLX
*** Script: Match found: C02C9AP6MD6R
*** Script: Match found: B14650355
*** Script: Match found: 97
*** Script: Match found: 27
*** Script: Match found: YN3LY72LR6
*** Script: Match found: 55
*** Script: Match found: Y5XK9J5F9C
*** Script: Match found: FOC1802X1GK
*** Script: Match found: C02DG12PMD6R
*** Script: Match found: CQ1FTP6KF4
*** Script: Match found: 18
*** Script: Match found: NIT206949
*** Script: Match found: C02G710SMD6R
*** Script: Match found: C02FN018ML88
*** Script: Match found: A90H041002771
*** Script: Match found: A4Y4011006641
*** Script: Match found: C1MRT459H3QK
*** Script: Match found: H2WFL0W3PJJ9
*** Script: Match found: FOC1803U003
*** Script: Match found: WPX47RM61X
*** Script: Match found: C02FN46VMD6R
*** Script: Match found: J0N9QYMXY7
*** Script: Match found: C02G710PMD6R
*** Script: Match found: 4Q56L33
*** Script: Match found: VD907HJP2G
*** Script: Match found: 6TF6WW1
*** Script: Match found: DD136120224014
*** Script: Match found: C02FN469MD6R
*** Script: Match found: C02G83QKMD6R
*** Script: Match found: H2WF10K7Q6P0
*** Script: Match found: BKPZ6S2
*** Script: Match found: C02K80H0FFT4
*** Script: Match found: 6BJD2Z3
*** Script: Match found: AA2J041009708
*** Script: Match found: FOC1802Y30D
*** Script: Match found: CNDG154057
*** Script: Match found: JAE21400372
*** Script: Match found: HCG6VDJKFF
*** Script: Match found: VQK7QH63JQ
*** Script: Match found: XDQ6902RYM
*** Script: Match found: C34NXV3PQW
*** Script: Match found: C07SN0TWG1J2
*** Script: Match found: XL1F3FQXTR
*** Script: Match found: Y14F96YKFG
*** Script: Match found: 2M5VBY3
*** Script: Match found: C07DC06VPJJ9
*** Script: Match found: C02DR9VUMD6R
*** Script: Match found: A5C4011118462
*** Script: Match found: WJKCFYXG32
*** Script: Match found: 2VF6WW1
*** Script: Match found: PKW49PVT7R
*** Script: Match found: CR3HT9MCF6
*** Script: Match found: FT5N1T3
*** Script: Match found: CZC5062QCZ
*** Script: Match found: 5XLF7Y2
*** Script: Match found: XJ7V4VHFFP
*** Script: Match found: A61H011007824
*** Script: Match found: XYVYM92QXT
*** Script: Match found: C02FN46EMD6R
*** Script: Match found: 55
*** Script: Match found: 37SBCP2
*** Script: Match found: HYY2YTVFQQ
*** Script: Match found: C02FP160Q05N
*** Script: Match found: 29
*** Script: Match found: FOC1803U056
*** Script: Match found: 73
*** Script: Match found: GWPWC42
*** Script: Match found: FXNQ4X3
*** Script: Match found: C07SN0U6G1J2
*** Script: Match found: W2X9HCF477
*** Script: Match found: Y4PJ4M2VFY
*** Script: Match found: A5C4011122198
*** Script: Match found: VTJVXFVXYN
*** Script: Match found: C69V76YQR2
*** Script: Match found: KJF9Q0TW9V
// Create a GlideRecord for the 'cmdb_ci' table
var cmdbCiGr = new GlideRecord('cmdb_ci');
cmdbCiGr.addEncodedQuery('sys_class_name=cmdb_ci_computer^serial_numberISNOTEMPTY^assetISEMPTY');
cmdbCiGr.query();

// Create a GlideRecord for the 'alm_asset' table
var almAssetGr = new GlideRecord('alm_asset');
almAssetGr.addEncodedQuery('ci=NULL^serial_numberISNOTEMPTY');
almAssetGr.query();

// Loop through 'alm_asset' records and check for matching serial numbers in 'cmdb_ci'
while (almAssetGr.next()) {
    var serialNumber = almAssetGr.serial_number;

    // Create a new GlideRecord for 'cmdb_ci' and query based on serial number
    var cmdbCiGrBySerial = new GlideRecord('cmdb_ci');
    cmdbCiGrBySerial.addQuery('serial_number', serialNumber);
    cmdbCiGrBySerial.query();

    if (cmdbCiGrBySerial.next()) {
        // Do something with the matching records
        gs.log('Match found: ' + serialNumber);
    }
}
const express = require("express");
const { z } = require("zod");

const app = express();

app.use(express.json());

const LoginSchema = z.object({
  // In this example we will only validate the request body.
  body: z.object({
    // email should be valid and non-empty
    email: z.string().email(),
    // password should be at least 6 characters
    password: z.string().min(6),
  }),
});

const validate = (schema) => (req, res, next) => {
  try {
    schema.parse({
      body: req.body,
      query: req.query,
      params: req.params,
    });

    next();
  } catch (err) {
    return res.status(400).send(err.errors);
  }
};

app.post("/login", validate(LoginSchema), (req, res) => {
  return res.json({ ...req.body });
});

app.listen(1337, () => console.log(`> Ready on http://localhost:${1337}`));
size_x = transform.position[0]*2;
size_y = transform.position[1];

x_offset = effect("Offset")("Shift Center To")[0]+(time*(size_x/thisComp.duration));

if(time < (thisComp.duration/2)){
	y_offset = ease(time, 0, thisComp.duration/2, size_y, size_y*2);
} else {
	y_offset = ease(time, thisComp.duration/2, thisComp.duration, size_y*2, size_y);
}

[x_offset, y_offset];
 
import React from 'react';
const knex = require('knex');

// we require this pakages to use this - knex , oracledb , pg , pg-query-stream
// we tried with prisma but got stucked in fetching data


function page() {
  const db = async () => {
    const database = knex({
      client: 'pg',
      connection: {
        host: '1.2.3.4',
        port: 5432,
        user: 'username',
        password: 'password',
        database: 'databasename'
      }
    });

    const a = await database.from('analytics.u_kpi_essentialdata').select();
    console.log('test---', a);
  };
  db();

  return (
    <div>
      <div>page</div>
      <div> naks</div>
    </div>
  );
}

export default page;
/**
 * Calculates the sale price of a value at a given discount.
 * The sale price is formatted as US dollars.
 *
 * @param {number} input The value to discount.
 * @param {number} discount The discount to apply, such as .5 or 50%.
 * @return The sale price formatted as USD.
 * @customfunction
 */
function salePrice(input, discount) {
  let price = input - (input * discount);
  let dollarUS = Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
});
  return dollarUS.format(price);
}
<x:Envelope
    xmlns:x="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:ws="http://www.nfevargem.com.br/ws.vargem/">
    <x:Header/>
    <x:Body>
        <ws:setInvoice>
            <ws:strJsonInvoice>[
   {
      "im":"002269",
      "NumeroNota":"004009",
      "DataEmissao":"2023-10-30",
      "NomeTomador":"INSTITUTO BRASILEIRO DE CIENCIA E TECNOLOGIA MAHARISHI IBCTM",
      "tipoDocTomador":"J",
      "documentoTomador":"31533629000120",
      "InscricaoEstadualTomador":"",
      "logradouroTomador":"Avenida Nove de Julho",
      "numeroTomador":"5955",
      "complementoTomador":"Loja A1 A15",
      "bairroTomador":"Jardim Paulista",
      "CEPTomador":"01407200",
      "cidadeTomador":"Sao Paulo",
      "ufTomador":"SP",
      "PAISTomador":"BRASIL",
      "emailTomador":"flavia.baptista@yahoo.com.br",
      "logradouroServico":"Estrada das Furnas",
      "numeroServico":"SN",
      "complementoServico":"",
      "bairroServico":"Bairro das Furnas",
      "CEPServico":"37640000",
      "cidadeServico":"Extrema",
      "ufServico":"MG",
      "issRetido":"1",
      "devidoNoLocal":"1",
      "observacao":"-",
      "INSS":"0.00",
      "IRPJ":"0.00",
      "CSLL":"0.00",
      "COFINS":"0.00",
      "PISPASEP":"0.00",
      "PAISServico":"BRASIL",
      "descricao":"FCK 25,0 MPA  BRITA 0\/1 ABAT. 10+-2 = 42,00 m3 x 440,00 = R$ 18.480,00 REM 11631-11632-11634-11635-11638-11640-11643-Estrada das Furnas, S\/N  Bairro das Furnas - Extrema\r\nTAXA DE BOMBA = 1,00 m3 x 2.400,00 = R$ 2.400,00 REM 11631-11632-11634-11635-11638-11640-11643-742 (DIA 20\/10 - 48,00 m3 - BOMBA ESTACIONARIA)\r\nTAXA DE BOMBA = 1,00 tx x 300,00 = R$ 300,00 DIFERENCA DE TAXA REF REMESSA 620 DE 20\/09\/2023\r\nREMESSA  DE MATERIAL R$ 10.590,00\r\nEXECUCAO DE SERVICOS R$ 10.590,00\r\nRETENCAO ISS R$ 211,80 (2.00%)\r\nVENCIMENTOS:\r\n004009 - R$ 20.968,20 - 26\/10\/2023 - CARTEIRA\r\nPredio 2\r\nVENDEDOR: Eliano Alves Martins",
      "atividade":"00702",
      "valor":"21180.00",
      "aliquota":"2.00",
      "deducaoMaterial":"10590.00",
      "descontoCondicional":"0.00",
      "descontoIncondicional":"0.00",
      "valorDeducao":"10590.00",
      "baseCalculo":"10590.00",
      "valorIss":"211.80",
      "valorTotalNota":"21180.00",
      "tipoEnquadramento":"",
      "tipoIss":"M",
      "hashMd5":""
   }
]</ws:strJsonInvoice>
            <ws:strToken>d439eb5be97874d72569582b84ebc8ba</ws:strToken>
        </ws:setInvoice>
    </x:Body>
</x:Envelope>
import express from "express";
const router = express.Router();
import multer from "multer";
import productModel from "../model/productModel.js";

const Storage = multer.diskStorage({
  destination: "upload",
  filename: (req, file, cb) => {
    cb(null, file.originalname);
  },
});

const upload = multer({
  storage: Storage,
}).single("image");

router.post("/product", (req, res) => {
  upload(req, res, (err) => {
    if (err) {
      console.log(err);
    } else {
      const product = new productModel({
        name: req.body.name,
        image: {
          data: req.file.filename,
          contentType: "image/png",
        },
      });
      product
        .save()
        .then(() => res.send("successfully created"))
        .catch((err) => res.send("error in creating product"));
    }
  });
});

export default router;
const text3 = document.querySelector('.text3');
const img3 = document.querySelector('.img3');

function animateElement(element, offset) {
    const elementPosition = element.getBoundingClientRect().top;
    const screenPosition = window.innerHeight / offset;

    if (elementPosition < screenPosition) {
        element.classList.add('animate');
    } else {
        element.classList.remove('animate');
    }
}

function animate() {
    animateElement(text3, 1.3);
    animateElement(img3, 1.3);
}

window.addEventListener('scroll', animate);
class Func {
  constructor(a, b) {
    this.a = a
    this.b = b
  }

  getSum() {
    return this.a + this.b
  }
}

let x = new Func(3, 4)
let arr1 = [1, 2, 3]
let arr2 = ['a', 'b', 'c']
let arr3 = [...arr1, ...arr2]

console.log(arr3) // [1, 2, 3, "a", "b", "c"]
<link rel="stylesheet" type="text/css" href="plugin/codemirror/lib/codemirror.css"> <body>	<textarea class="codemirror-textarea"></textarea></body> <script> $(document).ready(function(){    var codeText = $(".codemirror-textarea")[0];    var editor = CodeMirror.fromTextArea(codeText, {        lineNumbers : true    });}); </script> <script type="text/javascript" src="plugin/codemirror/lib/codemirror.js"></script>
async function fun() {  return fetch('https://jsonplaceholder.typicode.com/todos/1').then(res => res.json());} const data  = await fun();
[Unit]
Description=My app

[Service]
ExecStart=/var/www/myapp/app.js
Restart=always
User=nobody
# Note Debian/Ubuntu uses 'nogroup', RHEL/Fedora uses 'nobody'
Group=nogroup
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=/var/www/myapp

[Install]
WantedBy=multi-user.target
function el(arr) {
  let i = 0;
  return function gen() {
    if (i < arr.length) {
      let val = arr[i];
      i += 1;
      return val;
    }
  }
}
const myArray = [1, 2, 3];
const myGenerator = el(myArray);

console.log(myGenerator()); // 1
console.log(myGenerator()); // 2
console.log(myGenerator()); // 3
console.log(myGenerator()); // undefined
function el(arr) {
  let i = 0;
  return function gen() {
    if (i < arr.length) {
      let val = arr[i];
      i += 1;
      return val;
    }
  }
}
const myArray = [1, 2, 3];
const myGenerator = el(myArray);

console.log(myGenerator()); // 1
console.log(myGenerator()); // 2
console.log(myGenerator()); // 3
console.log(myGenerator()); // undefined
function el(arr) {
  let i = 0;
  return function gen() {
    if (i < arr.length) {
      let val = arr[i];
      i += 1;
      return val;
    }
  }
}
const myArray = [1, 2, 3];
const myGenerator = el(myArray);

console.log(myGenerator()); // 1
console.log(myGenerator()); // 2
console.log(myGenerator()); // 3
console.log(myGenerator()); // undefined
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WEB TITLE</title>
    <!-- CSS -->
    <link rel="stylesheet" href="style.css">
    <!-- FONT AWESOME -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" integrity="sha512-z3gLpd7yknf1YoNbCzqRKc4qyor8gaKU1qmn+CShxbuBusANI9QpRohGBreCFkKxLhei6S9CQXFEbbKuqLg0DA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <!-- MATERIAL ICON -->
    <link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined" rel="stylesheet">
    <!-- AOS LINK -->
    <link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
</head>
<body>


    <!-- WEB CONTENTS GOES HERE -->
    
    

    <!-- JAVASCRIPT -->
    <script src="script.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
    <script>
        AOS.init();
      </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Code Snippet</title>
    <!-- CSS -->
    <link rel="stylesheet" href="style.css">
    <!-- MATERIAL ICON -->
    <link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined" rel="stylesheet">
    <!-- AOS LINK -->
    <link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
</head>
<body>
    

    <!-- JAVASCRIPT -->
    <script src="script.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
    <script>
        AOS.init();
      </script>
</body>
</html>
(function (root, factory) {
	if (typeof define === "function" && define.amd) {
		define("onDomReady", factory(root));
	} else if (typeof exports === "object") {
		module.onDomReady = factory(root);
	} else {
		root.onDomReady = factory(root);
	}
})(this, function (root) {
    "use strict";
    
    var win = window,
        doc = win.document,
        docElem = doc.documentElement,
        
        LOAD = "load",
        FALSE = false,
        ONLOAD = "on"+LOAD,
        COMPLETE = "complete",
        READYSTATE = "readyState",
        ATTACHEVENT = "attachEvent",
        DETACHEVENT = "detachEvent",
        ADDEVENTLISTENER = "addEventListener",
        DOMCONTENTLOADED = "DOMContentLoaded",
        ONREADYSTATECHANGE = "onreadystatechange",
        REMOVEEVENTLISTENER = "removeEventListener",
        
        isEventListener = ADDEVENTLISTENER in doc,
        isDomReady = FALSE,
        domReadyCallBacks = [];
        
    var exports = function (func) {
        function defer (func, wait) {
            setTimeout(func, +wait >= 0 ? wait : 1);
        }
        
        function ready (func) {
            if (!isDomReady) {
                if (!doc.body) {
                    return defer(ready);
                }
                
                isDomReady = true;

                while (func = domReadyCallBacks.shift()) {
                    defer(func);
                }
            }
        }
        
        function detach() {
            if (isEventListener) {
                doc[REMOVEEVENTLISTENER](DOMCONTENTLOADED, completed, FALSE);
                win[REMOVEEVENTLISTENER](LOAD, completed, FALSE);
            } else {
                doc[DETACHEVENT](ONREADYSTATECHANGE, completed);
                win[DETACHEVENT](ONLOAD, completed);
            }
        }
        
        function completed (event) {
            if (isEventListener || event.type === LOAD || doc[READYSTATE] === COMPLETE) {
                detach();
                ready();
            }
        }
        
        if (doc[READYSTATE] === COMPLETE) {
            defer(ready);
        } else if (isEventListener) {
            doc[ADDEVENTLISTENER](DOMCONTENTLOADED, completed, FALSE);
            win[ADDEVENTLISTENER](LOAD, completed, FALSE);
        } else {
            doc[ATTACHEVENT](ONREADYSTATECHANGE, completed);
            win[ATTACHEVENT](ONLOAD, completed );
        }
        
        isDomReady ? defer(func) : domReadyCallBacks.push(func);
    };
    
    return exports;
});

// An example of the use of function onDomReady.
onDomReady(function(){
    console.log("DOM IS READY");
});
/**
 *    @module
 *    @author daemon.devin <daemon.devin@gmail.com>
 *
 *    @param {String}   file - The path of the file you want to load.
 *    @param {Function} callback (optional) - Called after script load.
 */
var loader = loader || (Function() {
    return {
    	
    	load: function(file, callback) {

            var script = document.createElement('script');
            script.src = file, script.async = true;
            
  			// If defined, execute the callback after checking 
  			// if the script has been successfully loaded.
            if (callback !== undefined) {
            	
            	// IE calls `script.onreadystatechange()` continuously
            	// as the script loads. Use `script.onreadystatechange()`
            	// to check if the script has finished loading.
	        script.onreadystatechange = function() {
	                
	            // When the script finishes loading, IE sets 
	            // `script.readyState` to either 'loaded' or 'complete'.
	            if (script.readyState === 'loaded' ||
	                script.readyState === 'complete') {
	                    
                  	// Set `onreadystatechange()` to null to prevent 
                  	// it from firing again.
	                script.onreadystatechange = null;
	                    
	                // Execute the callback.
	                callback (file );
	            }
	        };
	            
	        // The following is one of the reasons IE is infereor
            // to all modern browsers.
	        script.onload = function () {
	            callback ( file );
	        };
            }
            
  			// Add the loaded script to the end of the document 
  			// so it won't hinder the rest of the page from loading.
            document.body.appendChild(script);
        } 
    };
}());
// Define your class
class MyModule {
  constructor($) {
    this.$ = $;
  }
  
  // Add methods and properties here
}

// Environment detection and initialization
(function() {
  if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
    // CommonJS
    module.exports = MyModule;
  } else if (typeof define === 'function' && define.amd) {
    // AMD
    define(['jquery'], function($) {
      return new MyModule($);
    });
  } else {
    // Global
    if (typeof window.jQuery !== 'undefined') {
      window.MyModule = MyModule;
    }
  }
})();
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException, TimeoutException
import csv

URL = "https://www.theinfatuation.com/new-york/guides"

chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("detach", True)

print("Starting the browser...")
driver = webdriver.Chrome(options=chrome_options)
driver.get(URL)

# Close the modal if it appears
try:
    wait = WebDriverWait(driver, 10)
    no_thanks_button = wait.until(
        EC.element_to_be_clickable(
            (By.CSS_SELECTOR, "button[data-click='close'][aria-label='No thanks; close the dialog']"))
    )
    no_thanks_button.click()
    print("Closed the modal!")
except TimeoutException:
    print("No modal to close!")

# close the bottom overlay
try:
    overlay_close_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.ID, "bx-close-inside-2272826"))
    )
    driver.execute_script("arguments[0].click();", overlay_close_button)
    print("Closed the overlay!")
except TimeoutException:
    print("Overlay not found or already closed.")


# Click load more 10 times
for _ in range(10):
    try:
        load_more_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, "div.css-xi606m"))
        )
        load_more_button.click()
        print(f"Clicked load more {_+1} times.")

        # Adding a sleep duration to allow data to be rendered
        time.sleep(5)
    except TimeoutException:
        print(
            f"Couldn't click 'load more' the {_+1}-th time. Continuing with the available data.")
        break

# Extract data
guide_elements = driver.find_elements(
    By.CSS_SELECTOR, "a[data-testid='detailedStory-link']")
guide_data = [guide.get_attribute('href') for guide in guide_elements]

# CSV output setup
with open("output.csv", "w", newline="") as csvfile:
    fieldnames = ["Article Title", "URL", "Restaurants", "Date"]
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()

    for link in guide_data:
        driver.get(link)
        try:
            # CSS selector to get the article title
            title = driver.find_element(
                By.CSS_SELECTOR, "h1 > .styles_title__QfDF5").text
            # Extracting the date
            date_element = driver.find_element(
                By.CSS_SELECTOR, "div.styles_contributorsList__EKq26 time")
            date = date_element.get_attribute("datetime")
            # CSS selector to get restaurant names
            restaurants = [restaurant.text for restaurant in driver.find_elements(
                By.CSS_SELECTOR, "h2.chakra-heading.styles_mainHeading__e4VAy.flatplan_venue-heading.css-67umdg")]

            # Print data
            print("Article Title:", title)
            print("URL:", link)
            print("Restaurants:", ", ".join(restaurants))
            print("Date:", date)
            print("------")

            writer.writerow({"Article Title": title, "URL": link,
                            "Restaurants": ", ".join(restaurants), "Date": date})
        except NoSuchElementException:
            print(
                f"Couldn't retrieve complete data for article at URL: {link}")

driver.quit()
const kue = require('kue');
const queue = kue.createQueue();

const addEmailJob = (email, subject, html) => {
  const job = queue.create('email', {
    email,
    subject,
    html
  })
    .save((error) => {
      if (error) {
        console.error(error);
      } else {
        console.log(`Email job added to queue: ${email}`);
}
});
};

// Add 50,000 email jobs to the queue
const emailList = [
{ email: 'recipient1@example.com', subject: 'Test email 1', html: '<p>This is a test email 1</p>' },
{ email: 'recipient2@example.com', subject: 'Test email 2', html: '<p>This is a test email 2</p>' },
// ...
{ email: 'recipient50000@example.com', subject: 'Test email 50000', html: '<p>This is a test email 50000</p>' }
];

emailList.forEach((emailData) => {
addEmailJob(emailData.email, emailData.subject, emailData.html);
});
const kue = require('kue');
const queue = kue.createQueue();
const sendEmail = require('./send-email'); // The script from step 3

queue.process('email', (job, done) => {
sendEmail(job.data.email, job.data.subject, job.data.html);
done();
});
for (int index = 0; index < array.length; index++){
  
}
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
} from 'chart.js';
import { Line } from 'react-chartjs-2';       


function HraHero() {
  return (
    <Line
      className='bg-white h-3/4 w-full'
      options={{
        responsive: true,
        plugins: {
          legend: false
        },
        scales: {
          x: {
            ticks: {
              color: 'orange'
            },
            title: {
              display: true,
              text: 'Years of Growth',
              color: '#00aeef',
              font: {
                size: 14
              }
            }
          },
          y: {
            ticks: {
              callback: function (value, i) {
                if (i == 0) {
                  return value + ' k';
                }

                return value + ' Lakhs';
              }
            },
            title: {
              display: true,
              text: 'Amount Invested',
              color: '#154d83',
              font: {
                size: 14
              }
            },
            border: {
              dash: [6, 4]
            }
          }
        }
      }}
      data={{
        labels: [
          2022, 2024, 2026, 2028, 2030, 2032, 2034, 2036, 2038, 2040, 2042
        ],
        datasets: [
          {
            data: [0, 2, 3, 5, 10, 15, 20, 25, 30, 35],
            borderColor: '#f47920',
            tension: 0.1,
            pointRadius: '6',
            pointHoverRadius: '6',
            pointBackgroundColor: '#00aeef',
            pointHoverBackgroundColor: '#f47920'
          }
        ]
      }}
    />
  );
}

export default HraHero
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
} from 'chart.js';
import { Line } from 'react-chartjs-2';       


function HraHero() {
   ChartJS.register(
    CategoryScale,
    LinearScale,
    PointElement,
    LineElement,
    Title,
    Tooltip,
    Legend
  );
  
  return (
    <Line
      className='bg-white h-3/4 w-full'
      options={{
        responsive: true,
        plugins: {
          legend: false
        },
        scales: {
          x: {
            ticks: {
              color: 'orange'
            },
            title: {
              display: true,
              text: 'Years of Growth',
              color: '#00aeef',
              font: {
                size: 14
              }
            }
          },
          y: {
            ticks: {
              callback: function (value, i) {
                if (i == 0) {
                  return value + ' k';
                }

                return value + ' Lakhs';
              }
            },
            title: {
              display: true,
              text: 'Amount Invested',
              color: '#154d83',
              font: {
                size: 14
              }
            },
            border: {
              dash: [6, 4]
            }
          }
        }
      }}
      data={{
        labels: [
          2022, 2024, 2026, 2028, 2030, 2032, 2034, 2036, 2038, 2040, 2042
        ],
        datasets: [
          {
            data: [0, 2, 3, 5, 10, 15, 20, 25, 30, 35],
            borderColor: '#f47920',
            tension: 0.1,
            pointRadius: '6',
            pointHoverRadius: '6',
            pointBackgroundColor: '#00aeef',
            pointHoverBackgroundColor: '#f47920'
          }
        ]
      }}
    />
  );
}

export default HraHero
 const numbersArray = Array.from({length: 20}, ((_, index) => index + 1));
1.To check which Git credentials are configured in your system, you can use the following command in the terminal:

```bash
git config --list
```

2. To permanently remove the user.email and user.name settings from your Git configuration, you can use the following commands in the terminal:

```bash
git config --global --unset user.email
git config --global --unset user.name
```

3. Then run the git config --list command to check your Git configuration, the output will not include the user.email and user.name settings.

var delayInMilliseconds = 1000; //1 second

setTimeout(function() {
  //your code to be executed after 1 second
}, delayInMilliseconds);
//var is not required. ,1000 is OK
async function gptFunctions(prompts, model, functions){
    const plan = readFile("public/generated/shared_deps.md")
    await openai.chat.completions.create({
        messages: [{ role: "system", content: s.appSystemPrompt+"Given the prompt and the plan, return a list of strings corresponding to the new files that will be generated."}
        ,
            {
                "role": "user",
                "content": " I want a:" +s.prompt,
            },
            {
                "role": "user",
                "content": " The plan we have agreed on is:"+s.plan,
            },
        ],
        model: model,
        functions: [{'name': 'file_paths', 'description': 'Construct a list of file names.', 'parameters': {'type': 'object', 'properties': {'files_to_edit': {'type': 'array', 'items': {'type': 'string'}}}, 'required': ['files_to_edit']}}],
        function_call:{"name":"file_paths"}
      }).then((response) => {       
        let temp = JSON.parse(response.choices[0].message.function_call.arguments).files_to_edit;
        
        console.log(temp);
        
        
      }).catch((error) => {
        console.log(error);
      });
}
var audio = new Audio('audio_file.mp3');
audio.play();
/*!
 *  replaceme.js - text rotating component in vanilla JavaScript
 *  @version 1.1.0
 *  @author Adrian Klimek
 *  @link https://adrianklimek.github.io/replaceme/
 *  @copyright Addrian Klimek 2016
 *  @license MIT
 */
!function(a,b){"use strict";function c(a,b){for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}function d(){"function"==typeof b&&b.fn.extend({ReplaceMe:function(a){return this.each(function(){new e(this,a)})}})}function e(a,b){var d={animation:"animated fadeIn",speed:2e3,separator:",",hoverStop:!1,clickChange:!1,loopCount:"infinite",autoRun:!0,onInit:!1,onChange:!1,onComplete:!1};if("object"==typeof b?this.options=c(d,b):this.options=d,"undefined"==typeof a)throw new Error('ReplaceMe [constructor]: "element" parameter is required');if("object"==typeof a)this.element=a;else{if("string"!=typeof a)throw new Error('ReplaceMe [constructor]: wrong "element" parameter');this.element=document.querySelector(a)}this.init()}e.prototype.init=function(){"function"==typeof this.options.onInit&&this.options.onInit(),this.words=this.escapeHTML(this.element.innerHTML).split(this.options.separator),this.count=this.words.length,this.position=this.loopCount=0,this.running=!1,this.bindAll(),this.options.autoRun===!0&&this.start()},e.prototype.bindAll=function(){this.options.hoverStop===!0&&(this.element.addEventListener("mouseover",this.pause.bind(this)),this.element.addEventListener("mouseout",this.start.bind(this))),this.options.clickChange===!0&&this.element.addEventListener("click",this.change.bind(this))},e.prototype.changeAnimation=function(){this.change(),this.loop=setTimeout(this.changeAnimation.bind(this),this.options.speed)},e.prototype.start=function(){this.running!==!0&&(this.running=!0,this.changeWord(this.words[this.position]),this.position++),this.loop=setTimeout(this.changeAnimation.bind(this),this.options.speed)},e.prototype.change=function(){return this.position>this.count-1&&(this.position=0,this.loopCount++,this.loopCount>=this.options.loopCount)?void this.stop():(this.changeWord(this.words[this.position]),this.position++,void("function"==typeof this.options.onChange&&this.options.onChange()))},e.prototype.stop=function(){this.running=!1,this.position=this.loopCount=0,this.pause(),"function"==typeof this.options.onComplete&&this.options.onComplete()},e.prototype.pause=function(){clearTimeout(this.loop)},e.prototype.changeWord=function(a){this.element.innerHTML='<span class="'+this.options.animation+'" style="display:inline-block;">'+a+"</span>"},e.prototype.escapeHTML=function(a){var b=/<\/?\w+\s*[^>]*>/g;return b.test(a)===!0?a.replace(b,""):a},a.ReplaceMe=e,d()}(window,window.jQuery);
   const sibling = el.previousElementSibling; // parent wrapper
    
      if (sibling) {
        const classList = sibling.getAttribute('class');
        if (classList !== null && classList !== undefined && classList !== '') {
          if (sibling.classList.contains(navLinkClass)) {
           	// do something
          }
        }
      }
SELECT C.CON_IN_CODIGO,     
       (SELECT MAX(FA.PFA_DT_INICIAL)
          FROM GLO_PROCESSO_FLUXO_ANDA FA
         INNER JOIN GLO_PROCESSO_FLUXO FL
            ON FA.PFLU_IN_CODIGO = FL.PFLU_IN_CODIGO
           AND FL.PFLU_CHAVE_PK = C.CON_IN_CODIGO
           AND FL.PFLU_NOMETABELA = 'RH_FORM_CONTRATACAO') DATA_MOV
  FROM RH_FORM_CONTRATACAO C  
 WHERE UPPER(c.CON_ST_STATUS) NOT IN('FINALIZADO','CANCELADO')
 and (SELECT MAX(FA.PFA_DT_INICIAL)
          FROM GLO_PROCESSO_FLUXO_ANDA FA
         INNER JOIN GLO_PROCESSO_FLUXO FL
            ON FA.PFLU_IN_CODIGO = FL.PFLU_IN_CODIGO
           AND FL.PFLU_CHAVE_PK = C.CON_IN_CODIGO
           AND FL.PFLU_NOMETABELA = 'RH_FORM_CONTRATACAO') < ADD_MONTHS(SYSDATE,-2);
           
function incrementStats() {
    const counters = document.querySelectorAll('.counter');

    counters.forEach((counter) => {
        counter.innerText = 0;

        const updateCounter = () => {
            const target = +counter.getAttribute('data-target'); // the "+" here casts the returned text to a number
            const c = +counter.innerText;
            const increment = target / 200;

            if (c < target) {
                counter.innerText = Math.ceil(c + increment);
                setTimeout(updateCounter, 1);
                // here the function is calling itself until "c"
                // reaches the "data-target", making it recursive
            } else {
                counter.innerText = target;
            }
        };

        updateCounter();
    });
}

document.addEventListener('DOMContentLoaded', incrementStats);
  '<a href="' ||
          APEX_UTIL.PREPARE_URL(p_url           => 'f?p=' || :APP_ID ||
                                                   ':836:' || :APP_SESSION ||
                                                   '::NO:836:P836_ID:' ||
                                                   (SELECT ID
                                                      FROM SGQ_VISITA_OBRA_ITENS_CHECK
                                                     WHERE ID_SGQ_VISITA_OBRA_ITENS = I.ID),
                                p_checksum_type => 'SESSION') ||
          '"><span aria-hidden="true" class="fa fa-check-square-o"></span></i></i></a>'
// #1 Main Composition

// Offset > Shift Center To
x_offset = effect("Offset")("Shift Center To")[0];
y_offset = effect("Offset")("Shift Center To")[1];
posterizeTime(thisComp.layer("Null 7").effect("posterize adjusment 2, 15")("Slider"));
x = Math.round(random(-10,10));
y = x*240;
[x_offset, y_offset+y];

// Adjustment Layer Position
temp = transform.position[0];
[temp + (240*index)-240, transform.position[1]]

// #2 Inside Each Pre-Composed Row of Squares with Random Opacity

// Each Square Position
offset = 240;
[position[0]+offset*index-120,position[1]];

// Each Square Opacity
posterizeTime(thisComp.layer("Null 5").effect("posterize")("Slider"));
seedRandom(index+thisComp.layer("Null 5").effect("seed")("Slider"));
random(0,100);

// #3 Inside Pre-Composition of Rows

// Each Row Position
offset = 240;
[position[0],position[1]+offset*index-240];
/* log all background images on a page to the console */
let bgimg = performance.getEntriesByType('resource')
  .filter(rs => rs.initiatorType == 'css')
  .map(rs => {
  return {
    name: rs.name,
    initiator: rs.initiatorType
  }
}) || [];

(bgimg.length > 0)?
    console.table(bgimg):
    console.log('No background images on this page!');
x = 0;
modulo = thisComp.layer("Null 3").effect("modulo (recomienzo)")("Slider"); // segundos en la timeline

for (x; x <= time; x += 0.5) {
	if ((x - inPoint) % modulo == 0){
		if(time >= x + 0.5){
			transform.opacity = 0;
		} else {
			transform.opacity = 100;
		}
	}
}
function runTypingEffect() {
    const text = 'I am Chuck Winters.';
    const typingElement = document.getElementById('typing-text');
    const typingDelay = 100;

    typeText(text, typingElement, typingDelay);
}

function typeText(text, typingElement, typingDelay) {
  for (let i = 0; i < text.length; i++) {
    setTimeout(() => {
      typingElement.textContent += text.charAt(i);
    }, typingDelay * i);
  }
}

document.addEventListener('DOMContentLoaded', runTypingEffect)
const [formErrors, setFormErrors] = useState<Partial<UserRegistrationFormAddressInfoDetails>>({
  address: '',
  countryName: '',
  nationalityName: '',
  cityName: '',
  passportNo: '',
  passportExpiryDate: '',
  // nationality: '',
  resident: '',
  companyAdd: '',
});


handleEmptyField('passportNo', userData.passportNumber || passportNo, 'Passport No is required');


useEffect(() => {
  if (passportNo) {
    setFormErrors((prevErrors) => ({ ...prevErrors, passportNo: '' }));
  }
}, [passportNo]);

<input
      type="text"
      className={`form-control passport-number-input ${formErrors.passportNo ? 'input-error' : ''}`}
      id="passportNumber"
      placeholder="Enter Your Passport Number"
      defaultValue={userData.passportNumber}
      maxLength={12}
      onChange={(e) => {
        setPassportNo(e.target.value);
        if (e.target.value) {
        setFormErrors((prevErrors) => ({ ...prevErrors, passportNo: '' }));
        }
        }}
      onInput={(e) => {
        const input = e.target as HTMLInputElement;
        input.value = input.value.replace(/[^a-zA-Z0-9 ]/g, '');
        setPassportNo(input.value);
        }}
      {...register('passportNo', {
      required: true,
      })}
/>





public static List<Account> parentWithChildren() {
    List<Account> accounts = [SELECT Name, AccountSource, (SELECT Name FROM Contacts) FROM Account];

    for(Account nextAcct :accounts) {
        for(Contact nextContact :nextAcct.Contacts) {
            System.Debug(nextContact);
        }
    }

  return accounts;
}

// To access value from a lookup inside the inner query
List<Case> cases = [SELECT Id, CaseNumber, Subclassificacao__c, Status, (SELECT Id, Produto__r.Name FROM ProdutosDoCaso__r) FROM 
                    Case WHERE NTrackwise__c = '' and CreatedDate >= 2023-11-01T00:00:00.000+0000 and Status = 'MTO'];

for (Case c : cases) {
    System.debug('Case Number: ' + c.CaseNumber);
    System.debug('Subclassificacao: ' + c.Subclassificacao__c);
    System.debug('Status: ' + c.Status);

    // Iterate over related Produto__r records
    for (ProdutoDoCaso__c produto : c.ProdutosDoCaso__r) {
        System.debug('Produto Name: ' + produto.Produto__r.Name);
    }
}
function userScroll() {
  const navbar = document.querySelector('.navbar');

  window.addEventListener('scroll', () => {
    if (window.scrollY > 50) {
      navbar.classList.add('bg-dark');
    } else {
      navbar.classList.remove('bg-dark');
    }
  });
}

document.addEventListener('DOMContentLoaded', userScroll);
var grSysEmail = new GlideRecord('sys_email');
grSysEmail.addEncodedQuery("type=send-ready");
grSysEmail.query();
while (grSysEmail.next()) {
grSysEmail.state = 'processed';
grSysEmail.type= 'sent';
grSysEmail.update();
}
var whiteList = {
    "http://localhost:5000": true,
    "https://example-url.herokuapp.com": true
};
var allowCrossDomain = function(req, res, next) {    
        if(whiteList[req.headers.origin]){            
            res.header('Access-Control-Allow-Credentials', true);
            res.header('Access-Control-Allow-Origin', req.headers.origin);
            res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
            res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, Origin, Accept');        
            next();
        } 
};
app.use(allowCrossDomain);
posterizeTime(thisComp.layer("Null 3").effect("posterize")("Slider"));
seedRandom(index+thisComp.layer("Null 3").effect("seed")("Slider"));
random(0,100);
function logINPDebugInfo(inpEntry) {
  console.log('INP target element:', inpEntry.target);
  console.log('INP interaction type:', inpEntry.name);

  const navEntry = performance.getEntriesByType('navigation')[0];
  const wasINPBeforeDCL =
    inpEntry.startTime < navEntry.domContentLoadedEventStart;

  console.log('INP occurred before DCL:', wasINPBeforeDCL);
}
new PerformanceObserver((list) => {
  for (const {value, startTime, sources} of list.getEntries()) {
    // Log the shift amount and other entry info.
    console.log('Layout shift:', {value, startTime});
    if (sources) {
      for (const {node, curRect, prevRect} of sources) {
        // Log the elements that shifted.
        console.log('  Shift source:', node, {curRect, prevRect});
      }
    }
  }
}).observe({type: 'layout-shift', buffered: true});
x = 0;
menu = thisComp.layer("Null 3").effect("Dropdown Menu Control")("Menu").value;

for (x; x <= time; x += 0.5) {
	if ((x - inPoint) % 2 == 0){
		switch(menu){
		case 1:
		transform.opacity = linear(time, x, x + 0.5, 100, 0);
		break;
		case 2:
		transform.opacity = easeOut(time, x, x + 0.5, 100, 0);
		break;
		case 3:
		transform.opacity = easeIn(time, x, x + 0.5, 100, 0);
		break;
		case 4:
		transform.opacity = ease(time, x, x + 0.5, 100, 0);
		break;
		};
	};
};
import { v4 as uuidv4 } from 'uuid';

const randomString1 = uuidv4();
const randomString2 = uuidv4();

console.log(randomString1);
console.log(randomString2);
  props,
  ref,
) => <MuiAlert elevation={6} ref={ref} variant="filled" {...props} />);

export default function PhoneOTPVerification() {
  const [inputValue, setInputValue] = useState(['', '', '', '', '', '']);
  const [isVerified, setIsVerified] = useState(false);
  const [showInvalidOTPModal, setShowInvalidOTPModal] = useState(false);
  const [open, setOpen] = React.useState(false);
  const [errorMessage, setErrorMessage] = React.useState('');
  const [phoneNumber, setPhoneNumber] = useState('');
  const [snackbarSeverity, setSnackbarSeverity] = React.useState('success');
  const [snackbarOpen, setSnackbarOpen] = React.useState(false);
  const [snackbarMessage, setSnackbarMessage] = React.useState('');

  const navigate = useNavigate();

  const handleClose = (event?: React.SyntheticEvent | Event, reason?: string) => {
    if (reason === 'clickaway') {
      return;
    }

    setOpen(false);
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>, index: number) => {
    // Only allow digit characters
    const value = e.target.value.replace(/\D/g, '');
    // Create a new array with the updated value
    const newValue = [...inputValue];
    newValue[index] = value;
    setInputValue(newValue);
  };

  const handleKeyDown = (e: { key: string; }) => {
    if (e.key === 'Backspace') {
      setInputValue(inputValue.slice(0, -1)); // Remove the last character from the input value
    }
  };
  const { userGuid } = useParams();
  const verifyPhoneNumber = async () => {
    // Join the inputValue array into a single string
    const userOtp = inputValue.join('');
    // Check if the length is 6 (since we have 6 input fields)
    if (userOtp.length === 6) {
      const response = await trackPromise(api.verifyOtp(userOtp, userGuid));
      if (response?.data?.Output?.phoneVerified) {
        setIsVerified(true);
        navigate(`/accounts/signup/identity-verification/${userGuid}`);
      } else {
        setOpen(true);
        setErrorMessage('Invalid OTP');
      }
    } else {
      setIsVerified(false);
    }
  };

  const resentOtp = async () => {
    const response = await trackPromise(api.resendOtp(userGuid));
    console.log('otp resend response:', response);
    // show success sbackbart nessga if otp resend successfully
    if (response?.data?.Output?.phoneNumber) {
      setPhoneNumber(response?.data?.Output?.phoneNumber);
      setSnackbarSeverity('success');
      setSnackbarMessage('OTP resend successfully');
      setSnackbarOpen(true);
    } else {
      setSnackbarSeverity('error');
      setSnackbarMessage('OTP resend failed. Try again.');
      setSnackbarOpen(true);
    }
  };

  // useEffect(() => {
  //   resentOtp();
  // }, []);

  return (
    <>
      <main className="otp-verify-container">
        <header className="header">
          <img src={Headericon} alt="Header Image" />
        </header>
        <section className="verification-section">
          <h1 className="verification-title">Phone Number Verification</h1>
          <article className="verification-content">
            <div className="verification-icon">
              <img src={SMSIcon} alt="SMS Icon" />
            </div>
            <div className="verification-subtitle">Enter 6 Digit OTP</div>
            <div className="verification-message">
              <span className="verification-message-text">
                We have sent an OTP on
                {' '}
                <span className="verification-message-phone">{phoneNumber}</span>
              </span>
              <button
                onClick={resentOtp}
                className="resend-link"
              >
                Resend OTP
              </button>
            </div>
            <div className="verification-input mb-5">
              {[...Array(6)].map((_, index) => (
                <input
                  key={index}
                  type="text"
                  maxLength={1}
                  className="otp-input"
                  value={inputValue[index] || ''}
                  onChange={(e) => handleChange(e, index)}
                />
              ))}
              <button type="button" onClick={verifyPhoneNumber}>
                Verify
              </button>
            </div>
          </article>
        </section>
        <InvalidOTPModal
          show={showInvalidOTPModal}
          handleClose={() => setShowInvalidOTPModal(false)}
        />

      </main>
      <Snackbar
        open={open}
        autoHideDuration={3000}
        onClose={handleClose}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
      >
        <Alert onClose={handleClose} severity="error" sx={{ width: '100%', backgroundColor: '#C13254' }}>
          {/* Oops! Something went wrong. Please try again later. */}
          {errorMessage}
        </Alert>
      </Snackbar>

      {/* snacbar for otp resend */}
      <Snackbar
        open={snackbarOpen}
        autoHideDuration={3000}
        onClose={() => setSnackbarOpen(false)}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
      >
        <MuiAlert
          onClose={() => setSnackbarOpen(false)}
          variant="filled"
          elevation={6}
          severity={snackbarSeverity as MuiAlertProps['severity']}
          sx={{ width: '100%' }}
        >
          {snackbarMessage}
        </MuiAlert>
      </Snackbar>

    </>
  );
}
const formatPrice = (price) => {
  let formattedPrice = new Intl.NumberFormat('en-AU', { // comes from the Numberforamatted API JS
    style: 'currency',
    currency: 'AUD'
  }).format((price/100).toFixed(2));
  return formattedPrice;
}
/*!
 * Color mode toggler for Bootstrap's docs (https://getbootstrap.com/)
 * Copyright 2011-2023 The Bootstrap Authors
 * Licensed under the Creative Commons Attribution 3.0 Unported License.
 */

(() => {
  'use strict';

  const storedTheme = localStorage.getItem('theme');

  const getPreferredTheme = () => {
    if (storedTheme) {
      return storedTheme;
    }

    return window.matchMedia('(prefers-color-scheme: dark)').matches
      ? 'dark'
      : 'light';
  };

  const setTheme = function (theme) {
    if (
      theme === 'auto' &&
      window.matchMedia('(prefers-color-scheme: dark)').matches
    ) {
      document.documentElement.setAttribute('data-bs-theme', 'dark');
    } else {
      document.documentElement.setAttribute('data-bs-theme', theme);
    }
  };

  setTheme(getPreferredTheme());

  const showActiveTheme = (theme, focus = false) => {
    const themeSwitcher = document.querySelector('#bd-theme');

    if (!themeSwitcher) {
      return;
    }

    const themeSwitcherText = document.querySelector('#bd-theme-text');
    const activeThemeIcon = document.querySelector('.theme-icon-active use');
    const btnToActive = document.querySelector(
      `[data-bs-theme-value="${theme}"]`
    );
    const svgOfActiveBtn = btnToActive
      .querySelector('svg use')
      .getAttribute('href');

    document.querySelectorAll('[data-bs-theme-value]').forEach((element) => {
      element.classList.remove('active');
      element.setAttribute('aria-pressed', 'false');
    });

    btnToActive.classList.add('active');
    btnToActive.setAttribute('aria-pressed', 'true');
    activeThemeIcon.setAttribute('href', svgOfActiveBtn);
    const themeSwitcherLabel = `${themeSwitcherText.textContent} (${btnToActive.dataset.bsThemeValue})`;
    themeSwitcher.setAttribute('aria-label', themeSwitcherLabel);

    if (focus) {
      themeSwitcher.focus();
    }
  };

  window
    .matchMedia('(prefers-color-scheme: dark)')
    .addEventListener('change', () => {
      if (storedTheme !== 'light' || storedTheme !== 'dark') {
        setTheme(getPreferredTheme());
      }
    });

  window.addEventListener('DOMContentLoaded', () => {
    showActiveTheme(getPreferredTheme());

    document.querySelectorAll('[data-bs-theme-value]').forEach((toggle) => {
      toggle.addEventListener('click', () => {
        const theme = toggle.getAttribute('data-bs-theme-value');
        localStorage.setItem('theme', theme);
        setTheme(theme);
        showActiveTheme(theme, true);
      });
    });
  });
})();
Update the package with a lower version number. In this case, npm update vue. Optionally, you may want to npm update vue-loader too
webpack.mix.js
اضف .vue()    عمل تغير فقط اضف ----
----------------------------------------------------------







const mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel applications. By default, we are compiling the CSS
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js('resources/js/app.js', 'public/js').vue()
    .postCss('resources/css/app.css', 'public/css', [
        //
    ]);
      const units = ["bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];

      function niceBytes(x) {
        let l = 0,
          n = parseInt(x, 10) || 0;
        while (n >= 1000 && ++l) {
          n = n / 1000;
        }
        return n.toFixed(n < 10 && l > 0 ? 1 : 0) + " " + units[l];
      }
const formatter = new Intl.NumberFormat("en-IN", {
  style: "currency",
  currency: "INR",
  minimumFractionDigits: 0,
  maximumFractionDigits: 0,
  notation: "compact",
  compactDisplay: "short",
});

const rtf = new Intl.RelativeTimeFormat("en", {numeric: "auto"})
import React, { useEffect, useState } from 'react';
import { Redirect, Route } from 'react-router-dom';

import Loading from './Loading';
import Error from './Error';

export default function ProtectedRoute({ component: Component, ...rest }) {
    
    const [ user, setUser ] = useState('');
    const [ fetchingUser, setFetchingUser ] = useState(true);
    const [ noError, setNoError ] = useState(true);

    useEffect(() => {
        const fetchUser = async () => {
            try {
                const response = await fetch('http://localhost:5000/user', {
                    credentials: 'include'
                });

                if (fetchingUser) {
                    const data = await response.json();
                    setUser(data.session.passport.user);
                }

                setFetchingUser(false);

            } catch {
                setNoError(false);
            }
        }

        fetchUser();
    }, [])

    return (

        <div>
            <Route { ...rest } render={ () => { if (!noError) return <Error />} }/>
            <Route { ...rest } render={ () => { if (fetchingUser && noError) return <Loading />} }/>
            <Route { ...rest } render={ () => { if (user && !fetchingUser && noError) return <Component />} }/>
            <Route { ...rest } render={ () => { if (!user && !fetchingUser && noError) return <Redirect to="/login" />} }/>
        </div>
    )
}
export function asyncSequence(items, method) {
    if (!items) {
        return Promise.resolve();
    }
    return new Promise((resolve, reject) => {
        let index = 0;
        const results = [];
        const next = () => {
            // console.info(index, 'of', items.length);
            if (index === items.length) {
                resolve(results);
            } else {
                method(items[index], index, items)
                    .then((result) => {
                        results.push(result);
                        index += 1;
                        next();
                    })
                    .catch((error) => reject(error));
            }
        };
        next();
    });
}

export function asyncFilter(items, method) {
    return new Promise((resolve, reject) => {
        Promise.all(items.map((item) => method(item)))
            .then((decisions) => {
                const results = [];
                decisions.forEach((decision, index) => {
                    if (decision) {
                        results.push(items[index]);
                    }
                });
                resolve(results);
            })
            .catch(reject);
    });
}

export function callbackToPromise(method, ...args) {
    return new Promise((resolve, reject) => {
        method(...args, (error, result) => {
            if (error) {
                reject(error);
            } else {
                resolve(result);
            }
        });
    });
}
const onChange = (e: React.FormEvent<HTMLInputElement>) => {
  const newValue = e.currentTarget.value;
}
// Iterate over each element with the '.group' class
document.querySelectorAll('.markdown').forEach(function(group) {
    // Create the copy button
    let copyBtn = document.createElement('button');
    copyBtn.innerText = 'Copy';
    
    // Add click event to the copy button
    copyBtn.addEventListener('click', function() {
        // Clone the group element to avoid modifying the original content
        let clonedGroup = group.cloneNode(true);
        
        // Remove all button elements from the cloned group
        clonedGroup.querySelectorAll('button').forEach(function(button) {
            button.remove();
        });

        // Copy the innerHTML of the cloned group (without buttons) to the clipboard
        let textArea = document.createElement('textarea');
        textArea.value = clonedGroup.innerHTML;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
    });
    
    // Append the copy button to the '.group' class
    group.appendChild(copyBtn);
});
<!DOCTYPE html>
<html>
​
<body>
The content of the body element is displayed in your browser.
</body>
​
</html>
​
fetch('www.example.com/data')
    .then((res) => {
        if (!res.ok) {
            throw new Error('Error' + res.status)
        }
        return res.json()
    }).then((data) => {
        console.log('Data', data)
    }).catch((error) => {
        console.error('Error', error)
    })
Short notes format


Condense down the above information in easy to read format with short notes for revision. 
Make sure to include all the important facts, figures and keywords

 Add a section in the end of any Important dates / Personalities / Quotations if applicable


From the above questions asked. Create a syllabus to pass the test in which these questions will be asked

Above are questions with the text in brackets meaning (year/paper I or paper II, Question no, Marks. Sanitize the above data. The numbers 1. , 2. etc correspond to a single question unit. Now give me exact questions. 

OP ED ARTICLES REWRITING
I am preparing for the UPSC exam and I find this op-ed article difficult to understand. Could you please rewrite it in a simple and straightforward manner to help me better grasp its content?
After the article please mention any figures or facts that have been provided in the content

function performActions() {
    // First operation: click the first selector
    const button1 = document.querySelector("#app > div > div > div._2QgSC > div._2Ts6i._3RGKj._318SY > span > div > span > div > div > div > div:nth-child(2) > button:nth-child(2) > span.enbbiyaj.r5qsrrlp.l7jjieqr");
    if (button1) {
        button1.click();
    }

    // Wait for 50ms
    setTimeout(() => {
        // Second operation: extract the innerText of the second selector
        const headerElement = document.querySelector("#main > header");
        if (headerElement) {
            const extractedText = headerElement.innerText;
            
            const currentTime = new Date();
            const formattedTime = `${String(currentTime.getHours()).padStart(2, '0')}:${String(currentTime.getMinutes()).padStart(2, '0')}`;
            
            console.log(`[${formattedTime}] Extracted Text:`, extractedText);
        }

        // Wait for another 50ms
        setTimeout(() => {
            // Third operation: click the third selector
            const button2 = document.querySelector("#app > div > div > div._2QgSC > div._2Ts6i._3RGKj._318SY > span > div > span > div > div > div > div:nth-child(2) > button:nth-child(4)");
            if (button2) {
                button2.click();
            }
        }, 500);

    }, 500);
}

// Initial call
performActions();

// Set an interval to perform these actions every 5 minutes
setInterval(performActions, 5 * 60 * 1000);
function* gen() {
  try {
    let result = yield "2 + 2 = ?"; // (1)

    alert("The execution does not reach here, because the exception is thrown above");
  } catch(e) {
    alert(e); // shows the error
  }
}

let generator = gen();

let question = generator.next().value;

generator.throw(new Error("The answer is not found in my database")); // (2)
function* gen() {
  try {
    let result = yield "2 + 2 = ?"; // (1)

    alert("The execution does not reach here, because the exception is thrown above");
  } catch(e) {
    alert(e); // shows the error
  }
}

let generator = gen();

let question = generator.next().value;

generator.throw(new Error("The answer is not found in my database")); // (2)
function* gen() {
  // Pass a question to the outer code and wait for an answer
  let result = yield "2 + 2 = ?"; // (*)

  alert(result);
}

let generator = gen();

let question = generator.next().value; // <-- yield returns the value

generator.next(4); // --> pass the result into the generator
// for india currency ruppes
  commaSeparatedNumber: (number) => {
    return (
      number
        ?.toString()
        ?.replaceAll(",", "")
        // ?.replace(/(\.\d{2})\d*/, "$1,")
        ?.replace(/(\d)(?=(\d\d)+\d$)/g, "$1,")
    );
  },

// for us currency ruppes 
  commaSeparatedNumber: (number) => {
    return (
      number
        ?.toString()
        ?.replaceAll(",", "")
        // ?.replace(/(\.\d{2})\d*/, "$1,")
           ?.replace(/(\d)(?=(\d{3})+\b)/g, "$1,")

    );
<script>
  import ExperimentOne from './ExperimentOne.svelte';
  import ExperimentTwo from './ExperimentTwo.svelte';
 
  let component = (Math.random() * 100) > 50 ? 
    ExperimentTwo :
    ExperimentOne;
</script>
 
<svelte:component this={component} />
function* generateSequence(start, end) {
  for (let i = start; i <= end; i++) yield i;
}

function* generateAlphaNum() {

  // 0..9
  yield* generateSequence(48, 57);

  // A..Z
  yield* generateSequence(65, 90);

  // a..z
  yield* generateSequence(97, 122);

}

let str = '';

for(let code of generateAlphaNum()) {
  str += String.fromCharCode(code);
}

alert(str); // 0..9A..Za..z
function* generateSequence() {
  yield 1;
  yield 2;
  yield 3;
}

let generator = generateSequence();

for(let value of generator) {
  alert(value); // 1, than 2, than 3
}
function* generateSequence() {
  yield 1;
  yield 2;
  yield 3;
}

let generator = generateSequence();

for(let value of generator) {
  alert(value); // 1, затем 2, затем 3
}
function* generateSequence() {
  yield 1;
  yield 2;
  return 3;
}

let generator = generateSequence();

for(let value of generator) {
  alert(value); // 1, than 2
}
function* f() {
  // star after keyword function
}

function *f() {
  // star befor function name
}
function* generateSequence() {
  yield 1;
  yield 2;
  return 3;
}

let generator = generateSequence();

let one = generator.next();
alert(JSON.stringify(one)); // {value: 1, done: false}
let two = generator.next();
alert(JSON.stringify(two)); // {value: 2, done: false}
let three = generator.next();
alert(JSON.stringify(three)); // {value: 3, done: true}
function* generateSequence() {
  yield 1;
  yield 2;
  return 3;
}
// Add delete buttons below div.markdown elements
        const markdownDivs = document.querySelectorAll('.group');

        markdownDivs.forEach((div, index) => {
            const deleteButton = document.createElement('button');
            deleteButton.textContent = 'Delete';
            deleteButton.classList.add('delete-button');
            deleteButton.addEventListener('click', () => {
                // Remove the corresponding div when the delete button is clicked
                div.remove();
            });

            // Append the delete button to the div
            div.appendChild(deleteButton);
        });
// Definir región de interés
var countries = ee.Filter.expression('ADM2_CODE == 31823')
var paises = ee.FeatureCollection("FAO/GAUL/2015/level2").filter(countries)
var roi = paises.geometry()

//Seleccionar Colección de imágenes utilizada como base para el remuestreo
var dataset = ee.ImageCollection("MODIS/061/MOD13Q1").filter(ee.Filter.date('2002-05-01','2023-05-25')).filterBounds(roi);

//Definir máscara agrícola
var v200 = ee.ImageCollection("ESA/WorldCover/v200").filterBounds(roi).median()
var AgMask = v200.eq(40).clip(roi)

// Cambiar proyección de la máscara, reducir su resolución espacial y remuestrear
var crsDS = dataset.first().projection()
var AgMask_250 = AgMask.setDefaultProjection({crs :crsDS, scale: 10}).reduceResolution({
      reducer: ee.Reducer.mean(),
      maxPixels: 625
    })
    .reproject({
      crs: crsDS
    }).gte(0.5);

// Definir parametros visualizacion
var empty = ee.Image().byte();
var outline = empty.paint({
  featureCollection: paises,
  color: 1,
  width: 1
});

//Agregar capas al mapa
Map.setOptions("SATELLITE")
Map.centerObject(roi, 12);
Map.addLayer(dataset.first().select('NDVI').clip(roi), {min: 5000, max: 8000}, "NDVI", false);
Map.addLayer(AgMask, {}, "AgMask_10m", false);
Map.addLayer(AgMask_250, {}, "AgMask_250m", false);
Map.addLayer(outline, {palette: 'ff0000'}, 'Deptos');
//Map.addLayer(paises, {}, 'paises')

//Exportar la máscara
crsDS.evaluate(function(proj_obj) {
  Export.image.toAsset({
    image: AgMask_250,
    description: 'AgMask_250',
    assetId: 'AgMask_250',  // modificar ID
    region: roi,
    //scale: 250, // No definir la escala porque reproyecta la imagen y la modifica 
    crs: proj_obj.crs,
    crsTransform: proj_obj.transform
    });
});
https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/html/deploying_different_types_of_servers/setting-apache-http-server_deploying-different-types-of-servers

Install ModSecurity on CentOS 7

1. Enter the following into a terminal window:
sudo yum install mod_security

If prompted, pres y and hit Enter to allow the process to complete.
2. Restart the Apache service:

sudo systemctl restart httpd.service
3. Check the software version (should be 2.8.0 or later):

yum info mod_security
Step: 3 Configure ModSecurity

Upon installation, ModSecurity is set to log events according to default rules. You’ll need to edit the configuration file to adjust the rules to detect and block traffic.

The default configuration file is /etc/modsecurity/modsecurity.conf-recommended.
1. Copy and rename the file:
sudo cp /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf

2. Next, change the ModSecurity detection mode. First, move into the /etc/modsecurity folder:
sudo cd /etc/modsecurity

3. Open the configuration file in a text editor (we will be using nano):
sudo nano modsecurity.conf
___________________________________________________________________________________________________
Now after installation 

Add this line in httpd.conf (full path-> /etc/httpd/conf/httpd.conf)
SecRuleEngine on
SecServerSignature " "
ServerSignature On
ServerTokens Prod

function filterAndCheckValue(array, valueToCheck) {
  const filteredArray = array.filter(item => item === valueToCheck);

  if (filteredArray.length === 0) {
    return array;
  }

  return filteredArray;
}

const myArray = [1, 2, 3, 4, 5];
const valueToFind = 6;

const result = filterAndCheckValue(myArray, valueToFind);
console.log(result); // Output: [1, 2, 3, 4, 5]
function fetchData(callback) {
  setTimeout(function () {
    const data = { id: 1, name: 'Example Data' };
    callback(data);
  }, 2000); // Simulating of 2 second delay
}

// callback
function processData(result) {
  console.log('Succesfull:', result);
}

// call function fetchData with transfer function processData like a callback
fetchData(processData);

console.log('Inquiry was sended.');
 <div className="row form-row mb-5">
            {/* Country Col */}
            <div className="col-md-6">
              <label
                htmlFor="country"
                className="form-label w-100 country-label"
              >
                Country*
              </label>
              <Autocomplete
                disablePortal
                id="country"
                defaultValue={userData?.countryName ?? ''}
                options={countriesList}
                isOptionEqualToValue={(option: any, value: any) => option.label === value.label}
                renderInput={(params) => (
                  <TextField
                    {...params}
                    {...register('countryName', {
                      required: true,
                    })}
                    sx={{
                      '& .MuiOutlinedInput-root': {
                        '& fieldset': {
                          borderColor: (countryID || !submitAttempted) ? 'grey' : 'red',
                        },
                        '&:hover fieldset': {
                          borderColor: (countryID || !submitAttempted) ? 'grey' : 'red',
                        },
                        '&.Mui-focused fieldset': {
                          borderColor: (countryID || !submitAttempted) ? 'grey' : 'red',
                        },
                      },
                    }}
                    className="country-input"
                    placeholder="Select Country"
                  />
                )}
                // onchange event handler to set the countryName state
                onChange={(e: any, newVal: any) => {
                  setCountryID(newVal.countryID);
                  setCountrySelected(true);
                  setCityID(0); // Clear the city ID
                  // Also clear any other city-related states if you have them
                }}
              />
            </div>

            {/* City Col */}
            {countrySelected && (
            <div className="col-md-6">
              <label
                htmlFor="city"
                className="form-label w-100 city-label"
              >
                City*
              </label>
              <Autocomplete
                disablePortal
                id="city"
                value={cityID ? citiesListBycountry.find((city: { cityID: number; }) => city.cityID === cityID) : null} // Use the cityID state to control the value
                options={citiesListBycountry}
                isOptionEqualToValue={(option: any, value: any) => option.label === value.label}
                renderInput={(params) => (
                  <TextField
                    {...params}
                    {...register('cityName', {
                      required: true,
                    })}
                    sx={{
                      '& .MuiOutlinedInput-root': {
                        '& fieldset': {
                          borderColor: (cityID || !submitAttempted) ? 'grey' : 'red',
                        },
                        '&:hover fieldset': {
                          borderColor: (cityID || !submitAttempted) ? 'grey' : 'red',
                        },
                        '&.Mui-focused fieldset': {
                          borderColor: (cityID || !submitAttempted) ? 'grey' : 'red',
                        },
                      },
                    }}
                    className="city-input"
                    placeholder="Choose City*"
                  />
                )}
                onChange={(e, value: any) => setCityID(
                  value?.cityID,
                )}
              />
              {/* handle errors */}
              {/* {formErrors.cityName && (
              <span className="error-message">{formErrors.cityName}</span>
              )} */}
            </div>
            )}
          </div>
db.cities.aggregate([
  { "$project": { "id_city": { "$toString": "$_id" } } }, //combiente a string los ObjectIds
  { "$lookup": {
    "localField": "id_city",
    "from": "itineraries",
    "foreignField": "cityID",
 as: "matching_docs"
    }
  },
  {
    $match: {
      matching_docs: { $ne: [] } // Filtrar documentos que tienen coincidencias
    }
  }
])
db.cities.findOne({_id:ObjectId("64a47c1447972c5696cb0765")})
  
   db.cities.updateMany(
  {_id:ObjectId("64a47c1447972c5696cb0765")}, // Filtro vacío para actualizar todos los documentos
  {
    $pull: {
      "itineraries": "64efc056590b86b1be2cdd1e"
    }
  }
)
   db.cities.updateMany(
  {_id:ObjectId("64a47c1447972c5696cb0765")}, // Filtro vacío para actualizar todos los documentos
  {
    $push: {
      "itineraries": "64efc056590b86b1be2cdd1e"
    }
  }
)
   db.getCollection("cities").updateMany({_id:ObjectId("64a47c1447972c5696cb0765")},
{$push:{"itineraries":"64efc056590b86b1be2cdd1e"}})
// Assuming you have a collection named "yourCollectionName" and a field named "yourFieldName"

// Connect to your MongoDB database
use yourDatabaseName;

// Update the documents in the collection
db.yourCollectionName.find({}).forEach(function(doc) {
    if (typeof doc.yourFieldName === 'string') {
        doc.yourFieldName = ObjectId(doc.yourFieldName); // Convert to ObjectId type
        db.yourCollectionName.save(doc);
    }
});
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));
const paginate = (array) => {
  const itemsPerPage = 10;
  const numberOfPages = Math.ceil( array.length / itemsPerPage);

  // need to create an array of arrays [[10], [20], [30]] etc
  return Array.from({ length: numberOfPages }, (_, pageIndex) => {
    const startIndex = pageIndex * itemsPerPage;
    return array.slice(startIndex, startIndex + itemsPerPage);
  });

}

export default paginate
 <form className="flex items-center space-x-5 bg-white rounded-md p-2 shadow-md flex-1 md:flex-initial">
          <MagnifyingGlassIcon className="h-6 w-6 text-gray-400" />
          <input
            type="text"
            placeholder="search"
            className="flex-1 outline-none p-2"
          />
          <button type="submit">Search</button>
        </form>
 <Image
        src="https://links.papareact.com/c2cdd5"
        alt="Trello logo"
        width={300}
        height={100}
        className="w-44 md:w-56 pb-10 md:pb-0 object-contain"
      />
<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to detect idle
        time in JavaScript ?
    </title>
</head>
  
<body>
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
      
    <b>
        How to detect idle time in
        JavaScript elegantly?
    </b>
      
    <p>
        The timer will be incremented every
        second to denote the idle time.
        Interaction with the mouse or
        keyboard will reset and hide the timer.
    </p>
  
    <p class="timertext" 
        style="font-size: 1.5rem;">
        You are idle for
        <span class="secs"></span> seconds.
    </p>
  
    <script type="text/javascript">
        let timer, currSeconds = 0;
  
        function resetTimer() {
  
            /* Hide the timer text */
            document.querySelector(".timertext")
                    .style.display = 'none';
  
            /* Clear the previous interval */
            clearInterval(timer);
  
            /* Reset the seconds of the timer */
            currSeconds = 0;
  
            /* Set a new interval */
            timer = 
                setInterval(startIdleTimer, 1000);
        }
  
        // Define the events that
        // would reset the timer
        window.onload = resetTimer;
        window.onmousemove = resetTimer;
        window.onmousedown = resetTimer;
        window.ontouchstart = resetTimer;
        window.onclick = resetTimer;
        window.onkeypress = resetTimer;
  
        function startIdleTimer() {
              
            /* Increment the
                timer seconds */
            currSeconds++;
  
            /* Set the timer text
                to the new value */
            document.querySelector(".secs")
                .textContent = currSeconds;
  
            /* Display the timer text */
            document.querySelector(".timertext")
                .style.display = 'block';
        }
    </script>
</body>
  
</html>
import React from "react";
import Wrapper from "../assets/wrappers/LandingPage";
import main from "../assets/images/main.svg";
import { Logo } from "../components/";
import { Link } from "react-router-dom";

const Landing = () => {
  return (
    <Wrapper>
      <nav>
        <Logo />
      </nav>
      <div className="container page">
        <div className="info">
          <h1>
            job <span>tracking</span> app
          </h1>
          <p>
            Introducing JobScribe - your ultimate job tracking solution.
            Seamlessly organize and streamline your job applications,
            interviews, and follow-ups with ease, empowering you to conquer your
            dream job effortlessly.
          </p>
          <Link to="/register" className="btn btn-hero">
            Login/Register
          </Link>
        </div>
        <img src={main} alt="job hunt" className="img main-img"></img>
      </div>
    </Wrapper>
  );
};

export default Landing;
import { useState, useEffect } from "react";
import { Logo, FormRow, Alert } from "../components";
import Wrapper from "../assets/wrappers/RegisterPage";
import { useAppContext } from "../context/appContext";
import { useNavigate } from "react-router-dom";

const initialState = {
  name: "",
  email: "",
  password: "",
  isMember: true,
};

const Register = () => {
  const navigate = useNavigate();
  const [values, setValues] = useState(initialState);
  const { user, isLoading, showAlert, displayAlert, registerUser, loginUser } =
    useAppContext();

  const toggleMember = () => {
    setValues({ ...values, isMember: !values.isMember });
  };

  const handleChange = (e) => {
    setValues({ ...values, [e.target.name]: e.target.value });
  };

  const onSubmit = (e) => {
    e.preventDefault();
    const { name, email, password, isMember } = values;
    if (!email || !password || (!isMember && !name)) {
      displayAlert();
      return;
    }
    const currentUser = { name, email, password };
    if (isMember) {
      loginUser(currentUser);
    } else {
      registerUser(currentUser);
    }
  };

  useEffect(() => {
    if (user) {
      setTimeout(() => {
        navigate("/");
      }, 3000);
    }
  }, [user, navigate]);

  return (
    <Wrapper className="full-page">
      <form className="form-alt" onSubmit={onSubmit}>
        <Logo />
        <h3>{values.isMember ? "Login" : "Register"}</h3>
        {showAlert && <Alert />}
        {!values.isMember && (
          <FormRow
            type="text"
            name="name"
            value={values.name}
            handleChange={handleChange}
          />
        )}

        <FormRow
          type="email"
          name="email"
          value={values.email}
          handleChange={handleChange}
        />
        <FormRow
          type="password"
          name="password"
          value={values.password}
          handleChange={handleChange}
        />

        <button type="submit" className="btn btn-block" disabled={isLoading}>
          Submit
        </button>
        <button
          type="button"
          className="btn btn-block btn-hipster"
          disabled={isLoading}
          onClick={() => {
            loginUser({
              email: "test@test.com",
              password: "hitest",
            });
          }}
        >
          {isLoading ? "Loading..." : "Demo App"}
        </button>

        <p>
          {values.isMember ? "Not a member yet?" : "Already a member?"}
          <button type="button" onClick={toggleMember} className="member-btn">
            {values.isMember ? "Register" : "Login"}
          </button>
        </p>
      </form>
    </Wrapper>
  );
};
export default Register;
<DatePicker
                onChange={handleDatePicker}
                value={userData.passportExpiryDate || null || passportExpiryDate}
                minDate={new Date().toISOString().split('T')[0].split('-').join('/')}
                renderInput={(params: any) => (
                  <TextField
                    {...params}
                    inputProps={{
                      ...params.inputProps,
                      // readonly
                      readOnly: true,
                      placeholder: 'Select Date of Expiry',
                    }}
                    {...register('passportExpiryDate', {
                      required: true,
                    })}
                    // className="date-picker date-picker-input"
                    error={
                      (errors?.passportExpiryDate?.type === 'required' && passportExpiryDate === '')
                    }
                    sx={{
                      '& .MuiOutlinedInput-root': {
                        '& fieldset': {
                          borderColor: (passportExpiryDate || !submitAttempted) ? 'grey' : 'red',
                        },
                        '&:hover fieldset': {
                          borderColor: (passportExpiryDate || !submitAttempted) ? 'grey' : 'red',
                        },
                        '&.Mui-focused fieldset': {
                          borderColor: (passportExpiryDate || !submitAttempted) ? 'grey' : 'red',
                        },
                      },
                    }}
                  />
                )}
              />
    function dynamicVetIsNav(){
        const vetisMainNavLinks = document.querySelectorAll('#vetis-main-navigation .vet-nav__menu-link');
        const currentURL = window.location.pathname;

        const pathSegments = currentURL.split('/').filter(segment => segment !== "");
        if(vetisMainNavLinks){
            if (pathSegments.length >= 3) {
                const vetisMainURLPathname = pathSegments.slice(0, 3).join('/');
                
                for (const navLink of vetisMainNavLinks){
                    const navhref = navLink.getAttribute("href");
                    
                    if (navhref.includes(vetisMainURLPathname)) navLink.classList.add("active");
                }
            }
        }
    }
    
    document.addEventListener("DOMContentLoaded", dynamicVetIsNav);
import { jsPDF } from "jspdf";
import "jspdf/dist/polyfills.es.js";
import { regex } from "./constant";

const htmlPdfConverter = (basicDetails, inputs) => {
  
  const pdfHeading = `
  <div class="h-full w-full text-dream_vacation block justify-center items-end">
  <div class="w-full flex justify-end h-full">
    <img
     src=${window.location.origin + "/indiafirst-color.png"}
      alt=""
      class="h-[110px] w-[130px]"
    />
  </div>
  <div class="w-full mb-4 mt-2 h-20 font-semibold text-[38px] text-center">
    Future Wealth Creation Report
  </div>
</div>
  `;

  const date = new Date();
  const doc = new jsPDF();
  doc.setFontSize(12);
  doc.setProperties({
    title: "Future Wealth Creation Report",
    subject: "Future Wealth Creation Report",
    author: "India first life",
    keywords: "generated, javascript, web 2.0, ajax",
    creator: "India first life"
  });

  doc.html(pdfHeading, {
    useCORS: true,
    pageSplit: true,
    callback: function (pdf) {
      pdf.save(
        `Wealth Creation Calculator Report_${
          date.getDate() +
          "-" +
          (date.getMonth() + 1) +
          "-" +
          date.getFullYear() 
        }.pdf`
      );
    },
    margin: [10, 10, 10, 10],
    autoPaging: "text",
    x: 0,
    y: 0,
    width: 195,
    windowWidth: 900
  });
  return true;
};

export default htmlPdfConverter;
For react build deployment - put buli in (/var/www/html) folder
PORT 80 - is for http ip access link (comment it out in httpd.conf file)
PORT 443 is for HTTPS ip access link 

For redirection reload "404 error" issues-

1) Change httpd.conf file in (/etc/httpd/conf)and in .htaccess build folder (/var/www/html). 

2) Note: This two files should contain the same below code i.e.-> 

RewriteEngine On
RewriteBase / 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^ index.html [QSA,L]

3) Note:  in document root "/var/www/html" change AllowOverride to All.

After this re-run the Apache server command - apachectl restart
  const handleFileDrop = (acceptedFiles: any) => {
    console.log('Accepted Files:', acceptedFiles);
    checkFileValidity(acceptedFiles, documentTypeID);

    // Accept same file again
    if (dropzoneInputRef.current) {
      dropzoneInputRef.current.value = '';
    }
  };
copy build to var/www/html

/usr/share/httpd/noindex  .... 


local -> fpts to srv.arcosunix (buil import)

cd in build folder (cmd prmpt) -> command -[    cp -rv * /var/www/html/     ]  (this will override/copy new build)
 

*-------------------------------------*

if on restart if apache didn't restart then 

delete  indiafirstlife-ssl.conf     (path -  /etc/httpd/conf.d)

then apache will work 


commentd on line 87 on  vi /etc/httpd/conf.d/ssl.conf
 
let totalSeconds = 9.4342
let time = toHoursAndMinutes(Math.floor(totalSeconds));
console.log(time.s); 
function toHoursAndMinutes(totalSeconds) {
    let totalMinutes = Math.floor(totalSeconds / 60);
    let seconds= totalSeconds % 60;
    let hours = Math.floor(totalMinutes / 60);
    let minutes = totalMinutes % 60;
    if (hours < 9) {
      let hour = 0 + "" + hours;
      hours = hour.toString();
    }
    if (minutes < 9) {
      let min = 0 + "" + minutes;
      minutes = min.toString();
    }
    if (seconds <= 9) {
      let sec = 0 + "" + seconds;
      seconds = sec.toString();
    }
    else {
        console.log("second block not execute");
    } 
    return { h: hours, m: minutes, s: seconds };
}
export function calculateAge(dob) {
  const userDob = dob.split("/");
  const birthDate = new Date(userDob[2], userDob[1]-1, userDob[0]);

  const today = new Date();
  const yyyy = today.getFullYear();
  let mm = today.getMonth();
  let dd = today.getDate();
  if (dd < 10) dd = "0" + dd;
  if (mm < 10) mm = "0" + mm;
  const formattedTodayDate = new Date(yyyy, mm, dd);

  let year_difference =
    formattedTodayDate.getFullYear() - birthDate.getFullYear(); // 2001 - 2000 = 1
  let one_or_zero =
    formattedTodayDate.getMonth() < birthDate.getMonth() ||
    (formattedTodayDate.getMonth() === birthDate.getMonth() &&
      formattedTodayDate.getDate() < birthDate.getDate())
      ? 1
      : 0;
  let age = year_difference - one_or_zero;

  return age;
}
<?php
// error_reporting(E_ALL);
// ini_set('display_errors', 1);
error_reporting(0);
date_default_timezone_set('Asia/Kolkata');
function get($url)
{
  // Initialize a CURL session.
  $ch = curl_init();

  // Return Page contents.
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

  //grab URL and pass it to the variable.
  curl_setopt($ch, CURLOPT_URL, $url);

  $result = curl_exec($ch);

  return $result;
}

$user = $_POST['user'];
$offer = $_POST['offer'];
$cname = $_POST['cname'];
$event = $_POST['event'];

$rp = get('https://nextpower.cashinmedia.in/api/v1/checkRefer/0a51d09c-f329-4436-89d5-bdbb52bea07c/' . $offer . '?number=' . $user . '');

// JSON response from the URL
$response = $rp;

// Decode the JSON response
$response_data = json_decode($response, true);

$totalClicks = $response_data['clicks'];

$count = $response_data['count'];

// Extract the 'data' section from the response
$data = $response_data['data'];

// Check if there's any data to display
if (count($data) > 0) {
  // Echo the table header
//     echo '<table border="1">
//         <tr>
//             <th>Click</th>
//             <th>User Amount</th>
//             <th>Refer Amount</th>
//             <th>User</th>
//             <th>Refer</th>
//             <th>Event</th>
//             <th>Status</th>
//             <th>Payment Status</th>
//             <th>Payment Message</th>
//             <th>Created At</th>
//         </tr>';

  //     // Loop through each data entry and display in table rows
//     foreach ($data as $entry) {
//     $userEncoded = preg_replace('/\d{5}(?=\d{4}$)/', 'xxxxx', $entry['user']);

  //     echo '<tr>';
//     echo '<td>' . $entry['click'] . '</td>';
//     echo '<td>' . $entry['userAmount'] . '</td>';
//     echo '<td>' . $entry['referAmount'] . '</td>';
//     echo '<td>' . $userEncoded . '</td>'; // Display encoded user
//     echo '<td>' . $entry['refer'] . '</td>';
//     echo '<td>' . $entry['event'] . '</td>';
//     echo '<td>' . $entry['status'] . '</td>';
//     echo '<td>' . $entry['referPaymentStatus'] . '</td>';
//     echo '<td>' . $entry['payMessage'] . '</td>';
//     echo '<td>' . $entry['createdAt'] . '</td>';
//     echo '</tr>';
// }

  //     // Close the table
//     echo '</table>';
// } else {
//     // If there's no data, show a JavaScript alert
//     echo '<script>alert("No data found.");</script>';
// }
  ?>
  <html lang="en" dir="ltr">


  <head>
    <meta charset="utf-8">
    <title>FokatCash</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600&display=swap">
    <link rel="stylesheet" href="report.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" charset="utf-8"></script>
    <meta name="viewport" content="width=device-width">
  </head>
  <style>
    .data-table td,
    .data-table th {
      font-size: 17px;
      /* Adjust the value as needed */
    }

    .credited {
      color: #FFA500;
      /* Orange color */
    }
  </style>

  <body>
    <center>
      <div class="login-form">
        <h1>
          <font color='#0f0f0f'>REPORT
        </h1>
        <center>

  </body>

  </html>

  <div class="statics">
    <center><br>
      <fieldset>Refferer:
        <?php echo $user; ?>
        <hr>Camp:
        <?php echo $cname; ?>
        <hr>Total Clicks:
        <?php echo $totalClicks; ?>
        <hr>Total Conversions: <span id="totalLeads">Calculating...</span> <!-- Placeholder for total leads -->
        <hr>
        <font color="#008000"> Cashback Sent: Rs. <span id="totalAcceptedReferAmount">Calculating...</span> </font>
        <!-- Placeholder for total refer amount -->
        <hr>
        <font color="#FFA500">Pending Cashback : Rs.<span id="totalPendingReferAmount">Calculating...</span></font>
        <hr>
      </fieldset><br><br>
      <table class="data-table">
        <tr>

          <th>Camp Name</th>
          <th>Refer Amount</th>
          <!--<th>Refer Status</th>-->
          <th>Cashback Status</th>
          <th>Time</th>
        </tr>
        <?php
        foreach ($data as $entry) {
          $userEncoded = preg_replace('/\d{5}(?=\d{4}$)/', 'xxxxx', $entry['user']);
          $dateTime = new DateTime($entry['createdAt']);

          // Convert to IST timezone
          $dateTime->setTimezone(new DateTimeZone('Asia/Kolkata'));

          // Format the time in desired format
          $istTimeFormatted = $dateTime->format('Y-m-d H:i:s');

          if ($entry['referPaymentStatus'] === 'REJECTED' || $entry['referPaymentStatus'] === 'BLOCKED') {
            continue;
          }

          if ($entry['referPaymentStatus'] == 'ACCEPTED' || $entry['referPaymentStatus'] == 'UNKNOWN' || $entry['referPaymentStatus'] == 'FAILURE') {
            $cashbackStatus = '<b><span style="color: #198754;">Credited</span></b>';
          } elseif ($entry['referPaymentStatus'] == 'PENDING') {
            $cashbackStatus = '<b><span style="color: #FFA500;">Processing</span></b>';
          } else {
            // Handle other cases or set a default value for $cashbackStatus
            // For example: $cashbackStatus = 'Unknown Status';
            $cashbackStatus = $entry['referPaymentStatus'];
          }


          if ($entry['referAmount'] > 0) {
            echo '<tr>';
            // echo '<td>' . $entry['click'] . '</td>';
            // echo '<td>' . $entry['userAmount'] . '</td>';
            echo '<td>' . $cname . '</td>';
            echo '<td>' . $entry['referAmount'] . '</td>';
            // echo '<td>' . $userEncoded . '</td>'; // Display encoded user
            // echo '<td>' . $entry['refer'] . '</td>';
            // echo '<td>' . $entry['event'] . '</td>';
            // echo '<td>' . $entry['status'] . '</td>';
            echo '<td>' . $cashbackStatus . '</td>';
            // echo '<td>' . $entry['payMessage'] . '</td>';
            echo '<td>' . $istTimeFormatted . '</td>';
            echo '</tr>';
          }
        }
        // Close the table
        echo '</table>';
} else {
  // If there's no data, show a JavaScript alert
  ?>
        <html lang="en" dir="ltr">


        <head>
          <meta charset="utf-8">
          <title>FokatCash</title>
          <link rel="stylesheet"
            href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600&display=swap">
          <link rel="stylesheet" href="report.css">
          <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" charset="utf-8"></script>
          <meta name="viewport" content="width=device-width">
        </head>
        <style>
          .data-table td,
          .data-table th {
            font-size: 17px;
            /* Adjust the value as needed */
          }

          .credited {
            color: #FFA500;
            /* Orange color */
          }
        </style>

        <body>
          <center>
            <div class="login-form">
              <h1>
                <font color='#0f0f0f'>REPORT
              </h1>
              <center>

        </body>

        </html>

        <div class="statics">
          <center><br>
            <fieldset>Refferer:
              <?php echo $user; ?>
              <hr>Camp:
              <?php echo $cname; ?>
              <hr>Total Clicks:
              <?php echo $totalClicks; ?>
              <hr>Total Conversions: <span id="totalLeads">Calculating...</span> <!-- Placeholder for total leads -->
              <hr>
              <font color="#008000"> Cashback Sent: Rs. <span id="totalAcceptedReferAmount">Calculating...</span> </font>
              <!-- Placeholder for total refer amount -->
              <hr>
              <font color="#FFA500">Pending Cashback : Rs.<span id="totalPendingReferAmount">Calculating...</span></font>
              <hr>
            </fieldset><br><br>

            <h5>No data Found</h5>
            <?php


}
?>
    </table>
    <!-- ... Your existing code ... -->
    <script>
  // JavaScript to calculate and display the total leads count and total refer amounts
  document.addEventListener("DOMContentLoaded", function () {
    // Calculate the total leads count and total refer amounts based on the payment statuses and refer amount conditions
    var totalLeads = 0;
    var totalAcceptedReferAmount = 0;
    var totalPendingReferAmount = 0;
    var totalFailedReferAmount = 0;
    var totalUnknownReferAmount = 0;
    var event = "<?php echo $event; ?>";

    <?php foreach ($data as $entry): ?>
      <?php if ($entry['referPaymentStatus'] !== 'REJECTED' && $entry['referPaymentStatus'] !== 'BLOCKED' && $entry['referAmount'] > 0): ?>
        totalLeads++;
        <?php if ($entry['referPaymentStatus'] === 'ACCEPTED'): ?>
          totalAcceptedReferAmount += parseFloat(<?php echo $entry['referAmount']; ?>);
        <?php elseif ($entry['referPaymentStatus'] === 'PENDING'): ?>
          totalPendingReferAmount += parseFloat(<?php echo $entry['referAmount']; ?>);
        <?php elseif ($entry['referPaymentStatus'] === 'FAILURE'): ?>
          totalFailedReferAmount += parseFloat(<?php echo $entry['referAmount']; ?>);
        <?php elseif ($entry['referPaymentStatus'] === 'UNKNOWN'): ?>
          totalUnknownReferAmount += parseFloat(<?php echo $entry['referAmount']; ?>);
        <?php endif; ?>
      <?php endif; ?>
    <?php endforeach; ?>

    // Update the HTML content to display the calculated totals
    var totalLeadsElement = document.getElementById("totalLeads");
    totalLeadsElement.textContent = totalLeads;

    var totalAcceptedReferAmountElement = document.getElementById("totalAcceptedReferAmount");
    totalAcceptedReferAmountElement.textContent = totalAcceptedReferAmount.toFixed(2);

    var totalPendingReferAmountElement = document.getElementById("totalPendingReferAmount");
    totalPendingReferAmountElement.textContent = totalPendingReferAmount.toFixed(2);

    var totalFailedReferAmountElement = document.getElementById("totalFailedReferAmount");
    totalFailedReferAmountElement.textContent = totalFailedReferAmount.toFixed(2);

    var totalUnknownReferAmountElement = document.getElementById("totalUnknownReferAmount");
    totalUnknownReferAmountElement.textContent = totalUnknownReferAmount.toFixed(2);
  });
</script>



    <br><br><br>
    <footer id="footer">
      <div class="copyright">
        &copy; Copyright <strong><span>FokatCash</span></strong>
      </div>
    </footer><!-- End Footer -->
</div><!-- End statics div -->
</center><!-- End center div -->
</body><!-- End body tag -->

</html><!-- End HTML document -->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="google-signin-client_id"
        content="CLIENT_ID">
    <title>Google Auth</title>
</head>

<body>
    <button onclick="signIn()"> SignIn with Google</button>
    <script src="https://accounts.google.com/gsi/client" async></script>
    <script src="https://apis.google.com/js/platform.js" async defer></script>
    <script>
        let signIn = function () {
            console.log("Windows Loaded")
            google.accounts.id.initialize({
                client_id: 'CLIENT_ID',
                callback: handleCredentialResponse
            });
            google.accounts.id.prompt();
        };
        function handleCredentialResponse(res) {
            console.log("Response : ");
            console.log(res);
        }
    </script>
</body>

</html>
class ClassMates{
	constructor(name,age){
    	this.name=name;
      	this.age=age;
    }
  	displayInfo(){
    	return this.name + "is " + this.age + " years old!";
    }
}

let classmate = new ClassMates("Mike Will",15);
classmate.displayInfo();  // result: Mike Will is 15 years old!
import Splide from '@splidejs/splide';

export default function feedSlider() {
    /**
     * get the slides
     * make an array of all the images
     * loop over the array and if one is clicked
     * then it opens up into a modal
     * when the modal is closed, then the modal is removed from the DOM
     */
    const splideElements = document.querySelectorAll('.splide');

    const splideOptions = {
        type: 'loop',
        arrows: false,
        trimSpace: false,
        perPage: 2,
        perMove: 1,
        lazyload: false,
        direction: 'ltr',
        pagination: false,
        fixedHeight: '400px',
        mediaQuery: 'min',
        snap: true,
        breakpoints: {
            0: {
                perPage: 1,
                padding: { left: '0rem', right: '30%' },
                fixedHeight: '400px',
            },
            1200: {
                perPage: 1,
                fixedHeight: '400px',
            },
        },
    };

    if (splideElements) {
        for (let i = 0; i < splideElements.length; i++) {
            new Splide(splideElements[i], splideOptions).mount();
        }
    }

    const component = [...document.querySelectorAll('.feed-carousel-wrapper')];

    function modal(imageClicked) {
        const feedImageModal = document.createElement('div');
        feedImageModal.dataset.component = 'feeback_modal';
        feedImageModal.classList.add('feedback_modal', 'open');

        feedImageModal.innerHTML = `
            <div class="feedback_modal__image-wrapper">
            <div class="feedback_modal__closeBtn" data-feedbackaction="open">
             <svg className="svg-icon svg-icon--small svg-icon--close">
               <use href="#close" />
              </svg>
            </div>
            <img src="${imageClicked ?? imageClicked}" data-image="main">
            </div>
        `;

        document.body.insertAdjacentElement('afterbegin', feedImageModal);

        const closeBtn = document.querySelector('[data-feedbackaction="open"]');
        closeBtn.addEventListener('click', () => {
            feedImageModal.remove();
        });

        feedImageModal.addEventListener('click', () => {
            feedImageModal.remove();
        });
    }

    function getParent(target, id) {
        let parent = target;
        while (parent) {
            if (parent.localName && parent.classList.contains(id)) {
                return parent;
            }
            parent = parent.parentNode;
        }
        return false;
    }

    function componentClick(e) {
        const { target } = e;
        const parentEl = getParent(target, 'splide__slide');
        if (!parentEl) return;

        const image = parentEl.querySelector('img');
        const imageUrl = image.getAttribute('src');
        modal(imageUrl);
    }

    component.forEach((template) => {
        template.addEventListener('click', componentClick);
    });
}

window.addEventListener('DOMContentLoaded', feedSlider);
<Autocomplete
  id="google-map-demo"
  defaultValue={userData.addressLine1 || ''}
  freeSolo // <-- Add this line
  clearOnEscape={false}
  clearIcon={null}
  // ...rest of your props
/>

onChange={(event: any, newValue: PlaceType | string | null) => {
  if (typeof newValue === 'string') {
    // The user entered a new address manually
    setAddress(newValue);
    console.log('Manual input:', newValue);
  } else if (newValue) {
    // The user selected an address from the dropdown
    setAddress(newValue.description);
    console.log('Selected Value:', newValue.description);
  }
}}

    
    
const setTimeout = (ms, cb) => timeout(ms, 0, cb);
const setInterval = (ms, cb) => timeout(0, ms, cb);
const setTimeoutAsync = (ms) =>
    new Promise(resolve => setTimeout(ms, resolve));

; (async function asyncFn() {
    print(new Date().toISOString(), 'waiting a sec....');
    await setTimeoutAsync(1000);
    print(new Date().toISOString(), 'waiting a sec....');
    await setTimeoutAsync(1000);
    print(new Date().toISOString(), 'finished....');
})();
import { jsPDF } from "jspdf";

export default async function lead({
}) {

  const doc = new jsPDF('p', 'pt', 'a4');
  doc.setFontSize(12)
  doc.html(document.getElementById("dream-house-full"),  {
    useCORS: true,
    autoPaging:'text',
    // html2canvas:
    callback: function (pdf) {
      pdf.save("12.pdf");
    },
    html2canvas: {
      scale: 0.5,
      // ignoreElements: element => element.id === autoTableConfig?.elementId,
    },
    x:10,
    y:10,
    width:1400,
  });
  // doc.save("a4.pdf");

  // htmlPdf.create(html, options).then((pdf) => pdf.toFile('test.png'));
}
function generateUniqueId() {
    const timestamp = Date.now();
    const randomNumber = Math.random();
    const hexadecimalString = randomNumber.toString(16);

    return `id-${timestamp}-${hexadecimalString}`;
}
    // Check if primaryEmail and secondaryEmail are same
    if (primaryEmail === secondaryEmail && primaryEmail !== '' && secondaryEmail !== '') {
      errors.primaryEmail = 'Primary and Secondary email cannot be the same';
      errors.secondaryEmail = 'Primary and Secondary email cannot be the same';
    }

  // Check if primaryMobileNumber and secondaryMobileNumber are same
    if (primaryMobileNumber === secondaryMobileNumber && primaryMobileNumber !== '' && secondaryMobileNumber !== '') {
      errors.primaryMobileNumber = 'Primary and Secondary mobile number cannot be the same';
      errors.secondaryMobileNumber = 'Primary and Secondary mobile number cannot be the same';
    }

<div className="col-md-6">
              <label htmlFor="email" className="form-label w-100 email-label">
                Primary Email*
              </label>
              
// primary email

<input
                type="email"
                className={`form-control email-input ${formErrors.primaryEmail ? 'input-error' : ''}`}
                id="email"
                placeholder="abc@babc.com"
                defaultValue={userData.primaryEmail}
                onChange={(e) => setPrimaryEmail(e.target.value)}
                {...register('primaryEmail', {
                  required: true,
                })}
              />
              {
                primaryEmail === secondaryEmail
                && primaryEmail !== ''
                && secondaryEmail !== ''
                  && (
                  <div className="error-message">
                    {formErrors.primaryEmail}
                  </div>
                  )
              }
            </div>

 // secondary email

<input
                    type="email"
                    className={`form-control secondary-email-input ${formErrors.secondaryEmail ? 'input-error' : ''}`}
                    id="secondary-email"
                    placeholder="secondary@abc.com"
                    defaultValue={userData.secondaryEmail}
                    // onchange
                    onChange={(e) => setSecondaryEmail(e.target.value)}
                    // register
                    {...register('secondaryEmail', {
                      required: true,
                    })}
                  />
                  {formErrors.secondaryEmail && <div className="error-message mt-1">{formErrors.secondaryEmail}</div>}


// primary mobile number

<input
                  type="text"
                  className={`form-control mobile-input ${formErrors.primaryMobileNumber ? 'input-error' : ''}`}
                  id="mobile"
                  placeholder="XXXXXXXXXXXXXX"
                  defaultValue={userData.primaryMobileNumber}
                  onInput={(e) => {
                    const input = e.target as HTMLInputElement;
                    input.value = input.value.slice(0, 15).replace(/[^0-9 ]/g, ''); // Limit the input to 15 characters and Allow only digits and spaces
                    setPrimaryMobileNumber(input.value);
                  }}
                  {...register('primaryMobileNumber', {
                    required: true,
                  })}
                />


// secondary mobile number

                    <input
                      type="text"
                      className={`form-control secondary-mobile-input ${formErrors.secondaryMobileNumber ? 'input-error' : ''}`}
                      id="secondary-mobile"
                      placeholder="XXXXXXXXXXX"
                      defaultValue={userData.secondaryMobileNumber}
                      onInput={(e) => {
                        const input = e.target as HTMLInputElement;
                        const value = input.value.slice(0, 15).replace(/[^0-9 ]/g, ''); // Limit the input to 15 characters and Allow only digits and spaces
                        input.value = value;
                        setSecondaryMobileNumber(value);
                      }}
                      {...register('secondaryMobileNumber', {
                        required: true,
                      })}
                    />
                    {/* {
                      primaryMobileNumber === secondaryMobileNumber
                      && primaryMobileNumber !== ''
                      && secondaryMobileNumber !== ''
                        && (
                        <div className="error-message mt-1">
                          {formErrors.primaryMobileNumber}
                        </div>
                        )
                    } */}
                  </div>
                  {
                      formErrors.secondaryMobileNumber
                      && (
                      <div
                        className="error-message mt-1"
                      >
                        {formErrors.secondaryMobileNumber}
                      </div>
                      )
                    }


  // Scroll to top of page on component mount
  React.useEffect(() => {
    window.scrollTo(0, 0);
  }, []);
// This function is for the addition of numbers

function addNumbers(a, b) {
    return a + b; 
}

let a = 5
let b = 3

console.log(addNumbers(a, b)); // This is to test the function in the console 
// file data.json

{
"localItems": {
	"items": [
      {
		"title": "Halabut",
		"type": "string",
        "status": false
		},
			{
        "title": "Taco",
		"type": "string",
        "status": true
		},
      {
        "title": "Fish",
		"type": "string",
        "status": true
		},
      {
        "title": "Pork",
		"type": "string",
        "status": false
		}
		]
	}
}




//js file must be a module
// <script src="scripts.js" defer type="module"></script>

// JS file 
import data from "./data.json" assert { type: "json" };
const {localItems} = data;
const JSONDATA = localItems['items'];

/* eslint-disable no-restricted-syntax */
/* 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, useEffect, useCallback } from 'react';
import { useDropzone } from 'react-dropzone';
import { AiOutlineClose } from 'react-icons/ai';
import FileUploadIcon from '@assets/FileUploadIcon.svg';
import FileListIcon from '@assets/FileListIcon.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';
import Box from '@mui/material/Box/Box';
import Button from '@mui/material/Button/Button';
import { useForm } from 'react-hook-form';
import {
  fetchDocumentTypeList,
  fetchDocumentsList,
  deleteDocument,
  willDocumentUploadSelector,
  saveDocument,
} from '@redux/slices/will-documents-upload';
import { useSelector, useDispatch } from 'react-redux';
import { DocumentTypeList } from '@api/models';
import axios from 'axios';
import { willPersonalInformationSelector } from '@redux/slices/will-personal-information';
import { willsValidatorSelector } from '@redux/slices/willsValidator';
import MirrorWillSwitcher from '@components/MirrorWillSwitcher';
// import custom hook useDocumentsList
import useDocumentsList from '@utils/hooks/useDocumentsList';
import DeleteConfirmationModal from '@components/DeleteConfirmationModal';
import { useLocation } from 'react-router';
import DocumentManagerModal from '@components/DocumentManagerModal';
import { fetchAppointmentDetail } from '@redux/slices/wills-book-appointment';
import { Alert, AlertColor, Snackbar } from '@mui/material';
import MuiAlert from '@mui/material/Alert';

import { trackPromise } from 'react-promise-tracker';
import { getAppointmentDetail } from '../../redux/slices/wills-book-appointment';
import api from '../../api';

interface Props {
  handleNext: (step: number, stepName?: string) => void;
  currentBtnStep: number;
  handleBack: () => void;
  willTypeID: number;
}

function DocumentManager({
  handleNext, currentBtnStep, handleBack, willTypeID,
}: Props) {
  // const [documentTypeID, setDocumentTypeID] = useState<string>('');
  const [documentTypeArray, setDocumentTypeArray] = useState([]);
  const [documentTypeID, setDocumentTypeID] = useState();
  const [uniqueDocumentId, setUniqueDocumentId] = useState();
  const [witnessProfileGUID, setWitnessProfileGUID] = useState();
  const [willDocGuid, setWillDocGuid] = useState<string>('');
  // const bookedForProfileGUID = 'ba125f2d-8c78-41ce-b576-6aaef9b57c2a';
  const [uploadedFiles, setUploadedFiles] = useState([]);
  const [showModal, setShowModal] = useState(false);
  const { state } = useLocation();
  const [showBookAppointnentModal, setShowBookAppointnentModal] = useState(false);
  // State for managing snackbar
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarSeverity, setSnackbarSeverity] = useState<AlertColor>('error'); // You can change 'error' to 'warning' or other values if needed

  // Snackbar message to display
  const snackbarMessage = 'Please upload all required documents before proceeding to the next step.';

  const [documentIsRequired, setDocumentIsRequired] = useState<boolean>(false);

  // check document is required or not and
  useEffect(() => {
    const isRequiredDocumentsExist = documentTypeArray.some((d) => d.isRequired);
    setDocumentIsRequired(isRequiredDocumentsExist);
  }, [documentTypeArray]);

  // profile guid
  const { isSpouseSelected, spouseGuid, profileGuid } = useSelector(willPersonalInformationSelector);

  const dispatch = useDispatch();

  const handleOpenModal = () => {
    setShowModal(true);
  };
  const handleCloseModal = () => {
    setShowModal(false);
  };

  const handleBookAppointmentModalOpen = () => {
    setShowBookAppointnentModal(true);
  };

  const handleBookAppointmentModalClose = () => {
    setShowBookAppointnentModal(false);
  };

  const handleBookAppointmentModalContinue = () => {
    setShowBookAppointnentModal(false);
    // handleNext(currentBtnStep, 'upload');
  };

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await trackPromise(api.getAppointmentDetail(profileGuid));
        console.log('fetch AppointmentDetail Result', response?.data?.Output);
        // log the timeSlotID
        console.log('timeSlotID:', response?.data?.Output?.timeSlotID);
        if (response?.data?.Output?.timeSlotID === 0) {
          console.log('No appointment details found! Opening modal');
          handleBookAppointmentModalOpen();
        } else {
          const appointmentDetails = response.data.Output;
          console.log('Appointment details:', appointmentDetails);
        }
      } catch (error) {
        console.error('Error fetching appointment detail:', error);
      }
    };
    fetchData();
  }, []);

  // API results from Redux
  const {
    bookedforprofileguid,
    docType,
    documentTypeList,
    documentsList,
    docTypeID,
    isDocumentsChanged,
  } = useSelector(willDocumentUploadSelector);
  const { mirrorWillCheck } = useSelector(willsValidatorSelector);
  // custom hook for document list
  const uploadedDocumentsList = useDocumentsList(documentsList);

  /**
   * Retrieves the list of document types and sets it to the document type array.
   *
   * @return {void} No return value.
   */
  const getDocumentTypeList = () => {
    const documentTypes: any = [];
    documentTypeList.forEach((d: DocumentTypeList) => {
      documentTypes.push({
        documentTypeID: d.docTypeID,
        documentTypeName: d.fileName,
        witnessProfileGUID: d.witnessProfileGUID,
        isRequired: d.isRequired,
      });
    });
    setDocumentTypeArray(documentTypes);
  };

  // API calls inside useEffects -------
  useEffect(() => {
    // dispatch<any>(fetchDocumentTypeList(bookedForProfileGUID));
    dispatch<any>(fetchDocumentTypeList(isSpouseSelected ? spouseGuid : profileGuid));
  }, [dispatch, isSpouseSelected]);

  useEffect(() => {
    // Dispatch the fetchDocumentsList action when documentTypeID changes
    dispatch<any>(fetchDocumentsList(isSpouseSelected ? spouseGuid : profileGuid, documentTypeID, witnessProfileGUID));
  }, [uniqueDocumentId, documentTypeID, isDocumentsChanged, isSpouseSelected]);

  // Result transformation for UI
  useEffect(() => {
    getDocumentTypeList();
  }, [documentTypeList]);

  const { handleSubmit } = useForm();
  /**
   * Sets the active element to the given element string.
   *
   * @param {string} element - The string representing the active element to set.
   */
  const handleElementClick = (docTypeId: any, witnessProfileGUID: any) => {
    const uniqueDocumentId: any = `${docTypeId}-${witnessProfileGUID}`;
    setUniqueDocumentId(uniqueDocumentId);
    setDocumentTypeID(docTypeId);
    setWitnessProfileGUID(witnessProfileGUID);
  };
  /**
   * 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: any) => ({
    backgroundColor: uniqueDocumentId === element ? '#023979' : '#F4F4F4',
  });

  /**
   * 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: any) => ({
    color: uniqueDocumentId === element ? '#FFFFFF' : '#1B202D',
  });

  const getFileUploadIcon = (element: any) => (uniqueDocumentId === element ? FileUploadIcon : FileUploadIconDark);

  const getTickMarkicon = (element: any) => (uniqueDocumentId === element ? TickMarkIconGreen : TickMarkIconGrey);

  /**
   * Handles click event on "Add File" button.
   *
   * @param {any} e - The event object.
   * @return {void} Nothing is returned by this function.
   */

  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);
  };

  /**
   * Updates the document type array by setting the 'isRequired' property to false for the document type
   * with the specified 'documentTypeID'. Returns the updated document type array.
   *
   * @param {any} documentTypeID - The ID of the document type to update
   * @return {void}
   */
  const updateDocumentTypeArray = (documentTypeID: any): void => {
    const updatedDocumentTypeArray = documentTypeArray.map((doc) => (doc.documentTypeID === documentTypeID ? { ...doc, isRequired: false } : doc));
    setDocumentTypeArray(updatedDocumentTypeArray);
  };

  /**
   * 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.
   */

  // Check the validity of uploaded files
  const checkFileValidity = async (files: any[]) => {
    const validExtensions = ['.pdf', '.jpeg', '.jpg', '.bmp', '.doc', '.docx'];
    const maxFileSize = 20 * 1024 * 1024;

    // Filter valid files based on extension and file size
    const validFiles = files.filter((file: { name: string; size: number; }) => {
      // Check if the file extension is valid
      const isValidExtension = validExtensions.some((ext) => file.name.toLowerCase().endsWith(ext));
      // Check if the file size is within the allowed limit
      const isWithinMaxSize = file.size <= maxFileSize;
      return isValidExtension && isWithinMaxSize;
    });

    // Filter invalid files
    const invalidFiles = files.filter(
      (file: any) => !validFiles.includes(file),
    );
    if (invalidFiles.length > 0) {
      // Display an alert message for invalid files
      const invalidFileNames = invalidFiles
        .map((file: { name: any; }) => file.name)
        .join(', ');
      alert(
        `Invalid files: ${invalidFileNames}. Please use A4-size PDF, JPEG, BMP, DOC, or DOCX files that are within 20MB.`,
      );
    } else {
      // Add valid files to the uploaded files list
      const updatedUploadedFiles = [...uploadedFiles, ...validFiles];
      setUploadedFiles(updatedUploadedFiles);

      // Update the document type array with the document type ID.
      updateDocumentTypeArray(documentTypeID);

      const formData = new FormData();
      for (let i = 0; i < validFiles.length; i++) {
        const file = validFiles[i];
        formData.append('FileDoc', file, file.name);
      }

      dispatch<any>(
        saveDocument(
          isSpouseSelected ? spouseGuid : profileGuid,
          documentTypeID,
          witnessProfileGUID,
          formData,
        ),
      );
    }
  };

  const handleNextStepClick = () => {
    if (!documentIsRequired) {
      // Handle Next Step click logic here
      handleNext(state === 'Guardianship Will' ? 6 : currentBtnStep, 'upload');
    } else {
      // Show the snackbar with an error message
      setSnackbarSeverity('error'); // You can change 'error' to 'warning' or other values if needed
      setSnackbarOpen(true);
    }
  };

  /**
   * Removes a file from the system.
   *
   * @param {string} willDocGuid - the unique identifier of the file to be removed
   * @return {any} the result of the delete operation
   */
  const removeFile = (willDocGuid: string) => {
    setWillDocGuid(willDocGuid);
    handleOpenModal();
  };

  const deleteFile = () => {
    console.log(`Delete the doc with GUID: ${willDocGuid}`);
    dispatch<any>(deleteDocument(willDocGuid));
    // log the result of the delete operation
    console.log('File removed successfully!');
    setShowModal(false);
  };

  const handleUploadDocument = (data: any) => {
    console.log(data);
    // handle document upload
    handleNext(currentBtnStep, 'upload');
  };

  const {
    getRootProps, // Props for the file drop zone element
    getInputProps, // Props for the file input element
  } = useDropzone({
    onDrop: handleFileDrop, // Callback function for handling dropped or selected files
  });

  return (
    <main>
      <section>
        {mirrorWillCheck && <MirrorWillSwitcher />}
        <header className="header mt-4">Upload Documents</header>
        <p className="description">
          Upload the documents in PDF or JPEG format. Click on Next Step to save
          the files once all the documents have been uploaded
        </p>
      </section>
      <div className="row document-upload-container">
        <div className="col-lg-6 content-wrapper">
          {documentTypeArray?.map((type) => (
            <div
              className={`top${
                uniqueDocumentId === `${type?.documentTypeID}-${type?.witnessProfileGUID}` ? ' active' : ''
              }`}
              style={getBackgroundStyle(`${type?.documentTypeID}-${type?.witnessProfileGUID}`)}
              onClick={() => handleElementClick(type?.documentTypeID, type?.witnessProfileGUID)}
            >
              <div className="left-container">
                <div className="file-upload-icon">
                  <img
                    src={getFileUploadIcon(`${type?.documentTypeID}-${type?.witnessProfileGUID}`)}
                    alt="File Uploader Icon"
                  />
                </div>
                <div
                  className="document-title"
                  style={getTitleStyle(`${type?.documentTypeID}-${type?.witnessProfileGUID}`)}
                >
                  {type.documentTypeName}
                </div>
              </div>
              <div className="tick-icon">
                <img
                  src={getTickMarkicon(`${type?.documentTypeID}-${type?.witnessProfileGUID}`)}
                  alt="Tick Mark"
                />
              </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 className="add-file-btn" 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>
          {uploadedDocumentsList.length > 0
            && uploadedDocumentsList.map((file: any, index) => (
              <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.fileName}</div>
                </div>
                <div className="close-icon" onClick={() => removeFile(file.willDocGuid)}>
                  <span className="close-icon-text">Remove</span>
                </div>
              </div>
            ))}
        </div>
      </div>
      {/* log documentIsRequired on template */}
      {/* {documentIsRequired && <div>Document is required</div>} */}
      <Box sx={{ display: 'flex', flexDirection: 'row', pt: 2 }}>
        <button
          type="button"
          className="next-btn"
          onClick={handleNextStepClick}
        >
          Next Step
        </button>
      </Box>
      {/* Snackbar */}
      <Snackbar open={snackbarOpen} autoHideDuration={3000} onClose={() => setSnackbarOpen(false)}>
        <MuiAlert
          elevation={6}
          variant="filled"
          severity={snackbarSeverity}
          onClose={() => setSnackbarOpen(false)}
        >
          {snackbarMessage}
        </MuiAlert>
      </Snackbar>
      <span className="next-btn-text mt-4">
        *Before clicking next, please make sure the details provided here are
        correct.
      </span>
      <DeleteConfirmationModal
        show={showModal}
        handleClose={handleCloseModal}
        handleContinue={deleteFile}
        type="Document"
      />
      {
          (willTypeID === 1 || willTypeID === 2) && (
            <DocumentManagerModal
              showBookAppointnentModal={showBookAppointnentModal}
              handleBookAppointmentModalClose={handleBookAppointmentModalClose}
              handleBookAppointmentModalContinue={handleBookAppointmentModalContinue}
              handleNext={handleNext}
              currentBtnStep={currentBtnStep}
              handleBack={handleBack}
            />
          )
        }

    </main>
  );
}

export default DocumentManager;
import Snackbar from '@mui/material/Snackbar';
import MuiAlert, { AlertProps as MuiAlertProps } from '@mui/material/Alert';


// snackbar states
  const [snackbarSeverity, setSnackbarSeverity] = React.useState('success');
  const [snackbarOpen, setSnackbarOpen] = React.useState(false);
  const [snackbarMessage, setSnackbarMessage] = React.useState('');



  const handleSnackbarClose = () => {
    // Handle the closing here
    setSnackbarOpen(false);
  };


 	try {
        const response = await trackPromise(api.saveUserRegistrationInformation(formData));
        // console.log('user reg response:', response?.data?.itemGUID);
        if (response?.data?.Output?.isAlreadyExists) {
          setSnackbarMessage('User already exists');
          setSnackbarSeverity('error');
          setSnackbarOpen(true);
        } else {
          dispatch(setUserInfo(response?.data?.Output?.itemGUID));
          setSnackbarMessage('User registered successfully');
          setSnackbarSeverity('success');
          setSnackbarOpen(true);
          setShowModal(true);
        }
      } catch (error) {
        setSnackbarMessage('An error occurred while submitting user registration');
        setSnackbarSeverity('error');
        setSnackbarOpen(true);
      }

// place snackbar at end of root jsx element. for example if parent jsx element is <main>,
 // place snackbar at the end of <main> element.
 
	  <Snackbar
        open={snackbarOpen}
        autoHideDuration={2000}
        onClose={handleSnackbarClose}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
      >
        <MuiAlert
          onClose={handleSnackbarClose}
          variant="filled"
          elevation={6}
          severity={snackbarSeverity as MuiAlertProps['severity']}
          sx={{ width: '100%' }}
        >
          {snackbarMessage}
        </MuiAlert>
      </Snackbar>
yes it is working, our client needs further upadates here.

when user uploads all the required files and then moves to other component and return back to DocumentManager component. isRequired property is true in which userhas to upload the requried files again. 

i want to keep documentTypeArray in redux or any state management technique. so when user returns back it should be available. or you can try any other methods. 

ie once reuiqred docs are updated and when we move to documentmanager component, next step button should be disabled. 

below attaching code for your reference:

"""
function DocumentManager({
  handleNext, currentBtnStep, handleBack, willTypeID,
}: Props) {
  // const [documentTypeID, setDocumentTypeID] = useState<string>('');
  const [documentTypeArray, setDocumentTypeArray] = useState([]);
  const [documentTypeID, setDocumentTypeID] = useState();
  const [uniqueDocumentId, setUniqueDocumentId] = useState();
  const [witnessProfileGUID, setWitnessProfileGUID] = useState();
  const [willDocGuid, setWillDocGuid] = useState<string>('');
  // const bookedForProfileGUID = 'ba125f2d-8c78-41ce-b576-6aaef9b57c2a';
  const [uploadedFiles, setUploadedFiles] = useState([]);
  const [showModal, setShowModal] = useState(false);
  const { state } = useLocation();
  const [showBookAppointnentModal, setShowBookAppointnentModal] = useState(false);

  const [documentIsRequired, setDocumentIsRequired] = useState<boolean>(false);

  // check document is required or not and
  useEffect(() => {
    const isRequiredDocumentsExist = documentTypeArray.some((d) => d.isRequired);
    setDocumentIsRequired(isRequiredDocumentsExist);
  }, [documentTypeArray]);

  // profile guid
  const { isSpouseSelected, spouseGuid, profileGuid } = useSelector(willPersonalInformationSelector);

  const dispatch = useDispatch();

  const handleOpenModal = () => {
    setShowModal(true);
  };
  const handleCloseModal = () => {
    setShowModal(false);
  };

  const handleBookAppointmentModalOpen = () => {
    setShowBookAppointnentModal(true);
  };

  const handleBookAppointmentModalClose = () => {
    setShowBookAppointnentModal(false);
  };

  const handleBookAppointmentModalContinue = () => {
    setShowBookAppointnentModal(false);
    // handleNext(currentBtnStep, 'upload');
  };

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await trackPromise(api.getAppointmentDetail(profileGuid));
        console.log('fetch AppointmentDetail Result', response?.data?.Output);
        // log the timeSlotID
        console.log('timeSlotID:', response?.data?.Output?.timeSlotID);
        if (response?.data?.Output?.timeSlotID === 0) {
          console.log('No appointment details found! Opening modal');
          handleBookAppointmentModalOpen();
        } else {
          const appointmentDetails = response.data.Output;
          console.log('Appointment details:', appointmentDetails);
        }
      } catch (error) {
        console.error('Error fetching appointment detail:', error);
      }
    };
    fetchData();
  }, []);

  // API results from Redux
  const {
    bookedforprofileguid,
    docType,
    documentTypeList,
    documentsList,
    docTypeID,
    isDocumentsChanged,
  } = useSelector(willDocumentUploadSelector);
  const { mirrorWillCheck } = useSelector(willsValidatorSelector);
  // custom hook for document list
  const uploadedDocumentsList = useDocumentsList(documentsList);

  /**
   * Retrieves the list of document types and sets it to the document type array.
   *
   * @return {void} No return value.
   */
  const getDocumentTypeList = () => {
    const documentTypes: any = [];
    documentTypeList.forEach((d: DocumentTypeList) => {
      documentTypes.push({
        documentTypeID: d.docTypeID,
        documentTypeName: d.fileName,
        witnessProfileGUID: d.witnessProfileGUID,
        isRequired: d.isRequired,
      });
    });
    setDocumentTypeArray(documentTypes);
  };

  // API calls inside useEffects -------
  useEffect(() => {
    // dispatch<any>(fetchDocumentTypeList(bookedForProfileGUID));
    dispatch<any>(fetchDocumentTypeList(isSpouseSelected ? spouseGuid : profileGuid));
  }, [dispatch, isSpouseSelected]);

  useEffect(() => {
    // Dispatch the fetchDocumentsList action when documentTypeID changes
    dispatch<any>(fetchDocumentsList(isSpouseSelected ? spouseGuid : profileGuid, documentTypeID, witnessProfileGUID));
  }, [uniqueDocumentId, documentTypeID, isDocumentsChanged, isSpouseSelected]);

  // Result transformation for UI
  useEffect(() => {
    getDocumentTypeList();
  }, [documentTypeList]);

  const { handleSubmit } = useForm();
  /**
   * Sets the active element to the given element string.
   *
   * @param {string} element - The string representing the active element to set.
   */
  const handleElementClick = (docTypeId: any, witnessProfileGUID: any) => {
    const uniqueDocumentId: any = `${docTypeId}-${witnessProfileGUID}`;
    setUniqueDocumentId(uniqueDocumentId);
    setDocumentTypeID(docTypeId);
    setWitnessProfileGUID(witnessProfileGUID);
  };
  /**
   * 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: any) => ({
    backgroundColor: uniqueDocumentId === element ? '#023979' : '#F4F4F4',
  });

  /**
   * 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: any) => ({
    color: uniqueDocumentId === element ? '#FFFFFF' : '#1B202D',
  });

  const getFileUploadIcon = (element: any) => (uniqueDocumentId === element ? FileUploadIcon : FileUploadIconDark);

  const getTickMarkicon = (element: any) => (uniqueDocumentId === element ? TickMarkIconGreen : TickMarkIconGrey);

  /**
   * Handles click event on "Add File" button.
   *
   * @param {any} e - The event object.
   * @return {void} Nothing is returned by this function.
   */

  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);
  };

  /**
   * Updates the document type array by setting the 'isRequired' property to false for the document type
   * with the specified 'documentTypeID'. Returns the updated document type array.
   *
   * @param {any} documentTypeID - The ID of the document type to update
   * @return {void}
   */
  const updateDocumentTypeArray = (documentTypeID: any): void => {
    const updatedDocumentTypeArray = documentTypeArray.map((doc) => (doc.documentTypeID === documentTypeID ? { ...doc, isRequired: false } : doc));
    setDocumentTypeArray(updatedDocumentTypeArray);
  };

  /**
   * 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.
   */

  // Check the validity of uploaded files
  const checkFileValidity = async (files: any[]) => {
    const validExtensions = ['.pdf', '.jpeg', '.jpg', '.bmp', '.doc', '.docx'];
    const maxFileSize = 20 * 1024 * 1024;

    // Filter valid files based on extension and file size
    const validFiles = files.filter((file: { name: string; size: number; }) => {
      // Check if the file extension is valid
      const isValidExtension = validExtensions.some((ext) => file.name.toLowerCase().endsWith(ext));
      // Check if the file size is within the allowed limit
      const isWithinMaxSize = file.size <= maxFileSize;
      return isValidExtension && isWithinMaxSize;
    });

    // Filter invalid files
    const invalidFiles = files.filter(
      (file: any) => !validFiles.includes(file),
    );
    if (invalidFiles.length > 0) {
      // Display an alert message for invalid files
      const invalidFileNames = invalidFiles
        .map((file: { name: any; }) => file.name)
        .join(', ');
      alert(
        `Invalid files: ${invalidFileNames}. Please use A4-size PDF, JPEG, BMP, DOC, or DOCX files that are within 20MB.`,
      );
    } else {
      // Add valid files to the uploaded files list
      const updatedUploadedFiles = [...uploadedFiles, ...validFiles];
      setUploadedFiles(updatedUploadedFiles);

      // Update the document type array with the document type ID.
      updateDocumentTypeArray(documentTypeID);

      const formData = new FormData();
      for (let i = 0; i < validFiles.length; i++) {
        const file = validFiles[i];
        formData.append('FileDoc', file, file.name);
      }

      dispatch<any>(
        saveDocument(
          isSpouseSelected ? spouseGuid : profileGuid,
          documentTypeID,
          witnessProfileGUID,
          formData,
        ),
      );
    }
  };

  /**
   * Removes a file from the system.
   *
   * @param {string} willDocGuid - the unique identifier of the file to be removed
   * @return {any} the result of the delete operation
   */
  const removeFile = (willDocGuid: string) => {
    setWillDocGuid(willDocGuid);
    handleOpenModal();
  };

  const deleteFile = () => {
    console.log(`Delete the doc with GUID: ${willDocGuid}`);
    dispatch<any>(deleteDocument(willDocGuid));
    // log the result of the delete operation
    console.log('File removed successfully!');
    setShowModal(false);
  };

  const handleUploadDocument = (data: any) => {
    console.log(data);
    // handle document upload
    handleNext(currentBtnStep, 'upload');
  };

  const {
    getRootProps, // Props for the file drop zone element
    getInputProps, // Props for the file input element
  } = useDropzone({
    onDrop: handleFileDrop, // Callback function for handling dropped or selected files
  });

  return (
    <main>
      <section>
        {mirrorWillCheck && <MirrorWillSwitcher />}
        <header className="header mt-4">Upload Documents</header>
        <p className="description">
          Upload the documents in PDF or JPEG format. Click on Next Step to save
          the files once all the documents have been uploaded
        </p>
      </section>
      <div className="row document-upload-container">
        <div className="col-lg-6 content-wrapper">
          {documentTypeArray?.map((type) => (
            <div
              className={`top${
                uniqueDocumentId === `${type?.documentTypeID}-${type?.witnessProfileGUID}` ? ' active' : ''
              }`}
              style={getBackgroundStyle(`${type?.documentTypeID}-${type?.witnessProfileGUID}`)}
              onClick={() => handleElementClick(type?.documentTypeID, type?.witnessProfileGUID)}
            >
              <div className="left-container">
                <div className="file-upload-icon">
                  <img
                    src={getFileUploadIcon(`${type?.documentTypeID}-${type?.witnessProfileGUID}`)}
                    alt="File Uploader Icon"
                  />
                </div>
                <div
                  className="document-title"
                  style={getTitleStyle(`${type?.documentTypeID}-${type?.witnessProfileGUID}`)}
                >
                  {type.documentTypeName}
                </div>
              </div>
              <div className="tick-icon">
                <img
                  src={getTickMarkicon(`${type?.documentTypeID}-${type?.witnessProfileGUID}`)}
                  alt="Tick Mark"
                />
              </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 className="add-file-btn" 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>
          {uploadedDocumentsList.length > 0
            && uploadedDocumentsList.map((file: any, index) => (
              <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.fileName}</div>
                </div>
                <div className="close-icon" onClick={() => removeFile(file.willDocGuid)}>
                  <span className="close-icon-text">Remove</span>
                </div>
              </div>
            ))}
        </div>
      </div>
      {/* log documentIsRequired on template */}
      {/* {documentIsRequired && <div>Document is required</div>} */}
      <Box sx={{ display: 'flex', flexDirection: 'row', pt: 2 }}>
        <button
          type="button"
          className="next-btn"
          onClick={() => handleNext(state === 'Guardianship Will' ? 6 : currentBtnStep, 'upload')}
          disabled={documentIsRequired}
        >
          Next Step
        </button>
      </Box>
      <span className="next-btn-text mt-4">
        *Before clicking next, please make sure the details provided here are
        correct.
      </span>
      <DeleteConfirmationModal
        show={showModal}
        handleClose={handleCloseModal}
        handleContinue={deleteFile}
        type="Document"
      />
      {
          (willTypeID === 1 || willTypeID === 2) && (
            <DocumentManagerModal
              showBookAppointnentModal={showBookAppointnentModal}
              handleBookAppointmentModalClose={handleBookAppointmentModalClose}
              handleBookAppointmentModalContinue={handleBookAppointmentModalContinue}
              handleNext={handleNext}
              currentBtnStep={currentBtnStep}
              handleBack={handleBack}
            />
          )
        }

    </main>
  );
}

"""
const dataArray = [
  {
    id: 1,
    odds: 1.28,
  },
  {
    id: 15,
    odds: 2.52,
  }
];

const convertedData = dataArray.reduce((result, obj) => {
  result[obj.id.toString()] = { ...obj };
  return result;
}, {});

console.log(convertedData);
CASE
     WHEN condition_1  THEN result_1
     WHEN condition_2  THEN result_2
     ...
     ELSE  result_n
END

 OpenAI
/* 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, useEffect } from 'react';
import { useDropzone } from 'react-dropzone';
import { AiOutlineClose } from 'react-icons/ai';
import FileUploadIcon from '@assets/FileUploadIcon.svg';
import FileListIcon from '@assets/FileListIcon.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';
import Box from '@mui/material/Box/Box';
import Button from '@mui/material/Button/Button';
import { useForm } from 'react-hook-form';
import {
  fetchDocumentTypeList,
  fetchDocumentsList,
  deleteDocument,
  willDocumentUploadSelector,
  saveDocument,
} from '@redux/slices/will-documents-upload';
import { useSelector, useDispatch } from 'react-redux';
import { DocumentTypeList } from '@api/models';
import axios from 'axios';
import { willPersonalInformationSelector } from '@redux/slices/will-personal-information';
import { willsValidatorSelector } from '@redux/slices/willsValidator';
import MirrorWillSwitcher from '@components/MirrorWillSwitcher';
// import custom hook useDocumentsList
import useDocumentsList from '@utils/hooks/useDocumentsList';
import DeleteConfirmationModal from '@components/DeleteConfirmationModal';
import { useLocation } from 'react-router';
import DocumentManagerModal from '@components/DocumentManagerModal';
import { fetchAppointmentDetail } from '@redux/slices/wills-book-appointment';

import { trackPromise } from 'react-promise-tracker';
import { getAppointmentDetail } from '../../redux/slices/wills-book-appointment';
import api from '../../api';

interface Props {
  handleNext: (step: number, stepName?: string) => void;
  currentBtnStep: number;
  handleBack: () => void;
  willTypeID: number;
}

function DocumentManager({
  handleNext, currentBtnStep, handleBack, willTypeID,
}: Props) {
  // const [documentTypeID, setDocumentTypeID] = useState<string>('');
  const [documentTypeArray, setDocumentTypeArray] = useState([]);
  const [documentTypeID, setDocumentTypeID] = useState();
  const [uniqueDocumentId, setUniqueDocumentId] = useState();
  const [witnessProfileGUID, setWitnessProfileGUID] = useState();
  const [willDocGuid, setWillDocGuid] = useState<string>('');
  // const bookedForProfileGUID = 'ba125f2d-8c78-41ce-b576-6aaef9b57c2a';
  const [uploadedFiles, setUploadedFiles] = useState([]);
  const [showModal, setShowModal] = useState(false);
  const { state } = useLocation();
  const [showBookAppointnentModal, setShowBookAppointnentModal] = useState(false);
  // state for documentIsRequired with boolean type

  // profile guid
  const { isSpouseSelected, spouseGuid, profileGuid } = useSelector(willPersonalInformationSelector);

  const dispatch = useDispatch();

  const handleOpenModal = () => {
    setShowModal(true);
  };
  const handleCloseModal = () => {
    setShowModal(false);
  };

  const handleBookAppointmentModalOpen = () => {
    setShowBookAppointnentModal(true);
  };

  const handleBookAppointmentModalClose = () => {
    setShowBookAppointnentModal(false);
  };

  const handleBookAppointmentModalContinue = () => {
    setShowBookAppointnentModal(false);
    // handleNext(currentBtnStep, 'upload');
  };

  // Show a modal on load
  // useEffect(() => {
  //   dispatch<any>(fetchAppointmentDetail(profileGuid))
  //     .then((response: any) => {
  //       console.log('fetchAppointmentDetailResult', response);
  //       // log the response status
  //       if (!response) {
  //         handleBookAppointmentModalOpen();
  //       }
  //     });
  // }, []);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await trackPromise(api.getAppointmentDetail(profileGuid));
        console.log('fetch AppointmentDetail Result', response?.data?.Output);
        // log the timeSlotID
        console.log('timeSlotID:', response?.data?.Output?.timeSlotID);
        if (response?.data?.Output?.timeSlotID === 0) {
          console.log('No appointment details found! Opening modal');
          handleBookAppointmentModalOpen();
        } else {
          const appointmentDetails = response.data.Output;
          console.log('Appointment details:', appointmentDetails);
        }
      } catch (error) {
        console.error('Error fetching appointment detail:', error);
      }
    };
    fetchData();
  }, []);

  // API results from Redux
  const {
    bookedforprofileguid,
    docType,
    documentTypeList,
    documentsList,
    docTypeID,
    isDocumentsChanged,
  } = useSelector(willDocumentUploadSelector);
  const { mirrorWillCheck } = useSelector(willsValidatorSelector);
  // custom hook for document list
  const uploadedDocumentsList = useDocumentsList(documentsList);

  /**
   * Retrieves the list of document types and sets it to the document type array.
   *
   * @return {void} No return value.
   */
  const getDocumentTypeList = () => {
    const documentTypes: any = [];
    documentTypeList.forEach((d: DocumentTypeList) => {
      documentTypes.push({
        documentTypeID: d.docTypeID,
        documentTypeName: d.fileName,
        witnessProfileGUID: d.witnessProfileGUID,
        isRequired: d.isRequired,
      });
    });
    setDocumentTypeArray(documentTypes);
    // log the document type array with a message
    console.log('Document types array:', documentTypeArray);
  };

  const [documentIsRequired, setDocumentIsRequired] = useState<boolean>(
    documentTypeArray.some((d) => d.isRequired),
  );

  // Check for Document Required or not
  // if (documentTypeArray.some((d) => d.isRequired)) {
  //   // list reuiqred documents
  //   const requiredDocuments = documentTypeArray.filter((d) => d.isRequired);
  //   console.log('Required documents:', requiredDocuments);
  // }

  // API calls inside useEffects -------
  useEffect(() => {
    // dispatch<any>(fetchDocumentTypeList(bookedForProfileGUID));
    dispatch<any>(fetchDocumentTypeList(isSpouseSelected ? spouseGuid : profileGuid));
  }, [dispatch, isSpouseSelected]);

  useEffect(() => {
    // Dispatch the fetchDocumentsList action when documentTypeID changes
    dispatch<any>(fetchDocumentsList(isSpouseSelected ? spouseGuid : profileGuid, documentTypeID, witnessProfileGUID));
  }, [uniqueDocumentId, documentTypeID, isDocumentsChanged, isSpouseSelected]);

  // Result transformation for UI
  useEffect(() => {
    getDocumentTypeList();
  }, [documentTypeList]);

  const { handleSubmit } = useForm();
  /**
   * Sets the active element to the given element string.
   *
   * @param {string} element - The string representing the active element to set.
   */
  const handleElementClick = (docTypeId: any, witnessProfileGUID: any) => {
    const uniqueDocumentId: any = `${docTypeId}-${witnessProfileGUID}`;
    setUniqueDocumentId(uniqueDocumentId);
    setDocumentTypeID(docTypeId);
    setWitnessProfileGUID(witnessProfileGUID);
    console.log(witnessProfileGUID, uniqueDocumentId);
  };

  /**
   * 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: any) => ({
    backgroundColor: uniqueDocumentId === element ? '#023979' : '#F4F4F4',
  });

  /**
   * 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: any) => ({
    color: uniqueDocumentId === element ? '#FFFFFF' : '#1B202D',
  });

  const getFileUploadIcon = (element: any) => (uniqueDocumentId === element ? FileUploadIcon : FileUploadIconDark);

  const getTickMarkicon = (element: any) => (uniqueDocumentId === element ? TickMarkIconGreen : TickMarkIconGrey);

  /**
   * Handles click event on "Add File" button.
   *
   * @param {any} e - The event object.
   * @return {void} Nothing is returned by this function.
   */
  const [documentTypeArrayCopy, setDocumentTypeArrayCopy] = useState([...documentTypeArray]);

  const handleAddFileClick = (e: any) => {
    e.preventDefault();
    documentTypeArrayCopy.forEach((d) => {
      if (d.isRequired) {
        setDocumentIsRequired(true);
        // update the documentTypeArrayCopy with the new value of documentIsRequired
        documentTypeArrayCopy.push({ ...d, isRequired: false });
        // log the updated documentTypeArrayCopy
        console.log('documentTypeArrayCopy:', documentTypeArrayCopy);
        setDocumentTypeArrayCopy(documentTypeArrayCopy);
      }
      setDocumentIsRequired(false);
    });
    if (e.target !== e.currentTarget) {
      return;
    }
    document.getElementById('file-upload-input')?.click();
    // store documentTypeArray to a new array
    // check if any of the documents is required, if yes, set documentIsRequired to true

    // const isRequiredDocumentsExist = documentTypeArray.some((d) => d.isRequired);
    // // log the result of the check
    // console.log('isRequiredDocumentsExist:', isRequiredDocumentsExist);
    // setDocumentIsRequired(isRequiredDocumentsExist);
  };

  /**
   * 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.
   */

  // Check the validity of uploaded files
  const checkFileValidity = async (files: any) => {
    const validExtensions = ['.pdf', '.jpeg', '.jpg', '.bmp', '.doc', '.docx'];
    const maxFileSize = 20 * 1024 * 1024;

    // Filter valid files based on extension and file size
    const validFiles = files.filter((file: any) => {
      // Check if the file extension is valid
      const isValidExtension = validExtensions.some((ext) => file.name.toLowerCase().endsWith(ext));
      // Check if the file size is within the allowed limit
      const isWithinMaxSize = file.size <= maxFileSize;
      return isValidExtension && isWithinMaxSize;
    });

    // Filter invalid files
    const invalidFiles = files.filter(
      (file: any) => !validFiles.includes(file),
    );
    if (invalidFiles.length > 0) {
      // Display an alert message for invalid files
      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 {
      // Add valid files to the uploaded files list
      setUploadedFiles((prevFiles) => [...prevFiles, ...validFiles]);
      if (uploadedFiles) {
        const formData = new FormData();
        for (let i = 0; i < validFiles.length; i++) {
          const file = validFiles[i];
          formData.append('FileDoc', file, file.name);
        }

        dispatch<any>(saveDocument(isSpouseSelected ? spouseGuid : profileGuid, documentTypeID, witnessProfileGUID, formData));
      }
    }
  };

  /**
   * Removes a file from the system.
   *
   * @param {string} willDocGuid - the unique identifier of the file to be removed
   * @return {any} the result of the delete operation
   */
  const removeFile = (willDocGuid: string) => {
    setWillDocGuid(willDocGuid);
    handleOpenModal();
  };

  const deleteFile = () => {
    console.log(`Delete the doc with GUID: ${willDocGuid}`);
    dispatch<any>(deleteDocument(willDocGuid));
    // log the result of the delete operation
    console.log('File removed successfully!');
    setShowModal(false);
  };

  const handleUploadDocument = (data: any) => {
    console.log(data);
    // handle document upload
    handleNext(currentBtnStep, 'upload');
  };

  const {
    getRootProps, // Props for the file drop zone element
    getInputProps, // Props for the file input element
  } = useDropzone({
    onDrop: handleFileDrop, // Callback function for handling dropped or selected files
  });

  return (
    <main>
      <section>
        {mirrorWillCheck && <MirrorWillSwitcher />}
        <header className="header mt-4">Upload Documents</header>
        <p className="description">
          Upload the documents in PDF or JPEG format. Click on Next Step to save
          the files once all the documents have been uploaded
        </p>
      </section>
      <div className="row document-upload-container">
        <div className="col-lg-6 content-wrapper">
          {documentTypeArray?.map((type) => (
            <div
              className={`top${
                uniqueDocumentId === `${type?.documentTypeID}-${type?.witnessProfileGUID}` ? ' active' : ''
              }`}
              style={getBackgroundStyle(`${type?.documentTypeID}-${type?.witnessProfileGUID}`)}
              onClick={() => handleElementClick(type?.documentTypeID, type?.witnessProfileGUID)}
            >
              <div className="left-container">
                <div className="file-upload-icon">
                  <img
                    src={getFileUploadIcon(`${type?.documentTypeID}-${type?.witnessProfileGUID}`)}
                    alt="File Uploader Icon"
                  />
                </div>
                <div
                  className="document-title"
                  style={getTitleStyle(`${type?.documentTypeID}-${type?.witnessProfileGUID}`)}
                >
                  {type.documentTypeName}
                </div>
              </div>
              <div className="tick-icon">
                <img
                  src={getTickMarkicon(`${type?.documentTypeID}-${type?.witnessProfileGUID}`)}
                  alt="Tick Mark"
                />
              </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 className="add-file-btn" 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>
          {uploadedDocumentsList.length > 0
            && uploadedDocumentsList.map((file: any, index) => (
              <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.fileName}</div>
                </div>
                <div className="close-icon" onClick={() => removeFile(file.willDocGuid)}>
                  <span className="close-icon-text">Remove</span>
                </div>
              </div>
            ))}
        </div>
      </div>
      <Box sx={{ display: 'flex', flexDirection: 'row', pt: 2 }}>
        {documentIsRequired}
        <button
          type="button"
          className="next-btn"
          onClick={() => handleNext(state === 'Guardianship Will' ? 6 : currentBtnStep, 'upload')}
          disabled={documentIsRequired}
        >
          Next Step
        </button>
      </Box>
      <span className="next-btn-text mt-4">
        *Before clicking next, please make sure the details provided here are
        correct.
      </span>
      <DeleteConfirmationModal
        show={showModal}
        handleClose={handleCloseModal}
        handleContinue={deleteFile}
        type="Document"
      />
      {/* render DocumentManagerModal */}
      {
          (willTypeID === 1 || willTypeID === 2) && (
            <DocumentManagerModal
              showBookAppointnentModal={showBookAppointnentModal}
              handleBookAppointmentModalClose={handleBookAppointmentModalClose}
              handleBookAppointmentModalContinue={handleBookAppointmentModalContinue}
              handleNext={handleNext}
              currentBtnStep={currentBtnStep}
              handleBack={handleBack}
            />
          )
        }

    </main>
  );
}

export default DocumentManager;
<DesktopDatePicker 
    value={dateOfBirth} 
    disableFuture 
    onChange={(e:any, newVal:any)=> handleDate(e, newVal)}
    renderInput={(params:any) =>
        <TextField {...params} error={false} />}
    />
 
HandleChange Function
    const handleDate = (e: any, newVal: any) => {
      console.log('formatted date', moment(e?._d).format());
      const formattedDate = moment(e?._d).format();
      setDateOfBirth(formattedDate);
    };
 
State variable and datatype
    const [dateOfBirth, setDateOfBirth] = useState<string>(null);
 
Repopulating value
    setDateOfBirth(selectedBeneficiary?.dateOfBirth?.slice(0, 10));
const path = require("path");
let sassRule= {
        test: /\.sass|scss$/i,
        use: ["style-loader", "css-loader", "sass-loader"],
    }
 module.exports = {
  entry: path.resolve(__dirname, "/src/index.js") // import sass file on javascript file
   module: {rules: sassRule}
 }
function sumTo(n) {
  return n * (n + 1) / 2;
}

alert( sumTo(100) );
function showMenu({ title = "Menu", width = 100, height = 200 } = {}) {
  alert( `${title} ${width} ${height}` );
}

showMenu(); // Menu 100 200
// we pass object to function
let options = {
  title: "My menu",
  items: ["Item1", "Item2"]
};

// ...and it immediately expands it to variables
function showMenu({title = "Untitled", width = 200, height = 100, items = []}) {
  // title, items – taken from options,
  // width, height – defaults used
  alert( `${title} ${width} ${height}` ); // My Menu 200 100
  alert( items ); // Item1, Item2
}

showMenu(options);
// default values
let [name = "Guest", surname = "Anonymous"] = ["Julius"];

alert(name);    // Julius (from array)
alert(surname); // Anonymous (default used)
.App {
  font-family: sans-serif;
  text-align: center;
}
html,
body {
  display: flex;
  height: 100vh;
  width: 100%;
  justify-content: center;
  align-items: center;
  font-size: 15px;
  margin: 2rem;
}
form > div {
  width: 120px;
}
module.exports = {
  // ...
  parserOptions: {
    project: "tsconfig.json",
    tsconfigRootDir: __dirname,
    sourceType: "module",
  },
  // ...
}
"""
function ChooseMethodModal({ showModal, handleModalClose, handleContinue }: ChooseMethodModalProps) {
  const [activeCard, setActiveCard] = useState('draftWill');
  const [selectedWillCard, setSelectedWillCard] = React.useState({
    willTypeName: 'Templated Full Will',
    willTypeID: '6',
  });
  const { results } = useSelector(willsListSelector);

  const dispatch = useDispatch();

  React.useEffect(() => {
    // dispatch<any>(fetchWillsList());
  }, []);

  /**
 * Handles the click event on the card and sets the active card name.
 *
 * @param {string} cardName - The name of the card that was clicked.
 * @return {void} This function does not return anything.
 */
  const handleCardClick = (cardName: string) => {
    setActiveCard(cardName);
    const { willTypeName, willTypeID } = results.find((will: any) => {
      if (cardName === 'draftWill') return will.willTypeName === 'Templated Full Will';
      if (cardName === 'willCopyUpload') return will.willTypeName === 'Full Will';
      return false;
    }) || { willTypeName: '', willTypeID: '' };
    setSelectedWillCard({ willTypeName, willTypeID });
  };

  const isAnyWillCardSelected = selectedWillCard.willTypeName !== '' && selectedWillCard.willTypeID !== '';

  return (
    <Modal show={showModal} onHide={handleModalClose} dialogClassName="modal-dialog-centered" size="lg">
      <Modal.Header closeButton>
        <Modal.Title className="modal-title">Choose Method</Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <div>
          <div className="modal-choose-method-subtitle mb-3">
            List your Substitute Beneficiaries below and click on Add Substitute to add them to your List
          </div>
        </div>
        <div className="d-flex flex-row">
          <div
            className={`card-container-draft-will d-flex flex-column align-items-center ${activeCard === 'draftWill' ? 'active' : ''}`}
            style={{ width: '50%', marginRight: '10px', position: 'relative' }}
            onClick={() => handleCardClick('draftWill')}
          >
            {activeCard === 'draftWill' && (
            <div
              className="check-icon"
            >
              <img src={FillCheckRoundIcon} alt="Fill Check Icon" />
            </div>
            )}
            <div className="choose-method-draft-will-icon-container" style={{ marginBottom: '20px', marginTop: '20px' }}>
              <img src={DraftWillIcon} alt="Will Copy Upload Icon" />
            </div>
            <div className="text-center choose-method-draft-will-title" style={{ marginTop: '10px', marginBottom: '10px', textAlign: 'center' }}>
              Draft Will Using the System
            </div>
            <div
              className="text-center choose-method-draft-will-desc"
              style={{ marginTop: '10px', marginBottom: '10px' }}
            >
              It is a long established fact that a reader will be distracted by the readable content.
            </div>
          </div>
          <div
            className={`card-container-will-copy-upload d-flex flex-column align-items-center ${activeCard === 'willCopyUpload' ? 'active' : ''}`}
            style={{ width: '50%', marginRight: '10px', position: 'relative' }}
            onClick={() => handleCardClick('willCopyUpload')}
          >
            {activeCard === 'willCopyUpload' && (
            <div
              className="check-icon"
              style={{
                position: 'absolute', top: '10px', left: '10px', margin: '10px',
              }}
            >
              <img src={FillCheckRoundIcon} alt="Fill Check Icon" />
            </div>
            )}
            <div
              className="choose-method-will-upload-icon-container"
              style={{ marginBottom: '20px', marginTop: '20px' }}
            >
              <img src={WillCopyUploadIcon} alt="Will Copy Upload Icon" />
            </div>
            <div className="text-center choose-method-will-upload-title" style={{ marginTop: '10px', marginBottom: '10px', textAlign: 'center' }}>
              Upload the Copy of Will
            </div>
            <div className="text-center choose-method-will-upload-desc" style={{ marginTop: '10px', marginBottom: '10px' }}>
              It is a long established fact that a reader will be distracted by the readable content.
            </div>
          </div>
        </div>
      </Modal.Body>
      <Modal.Footer className="justify-content-center">
        {
          activeCard && (
            <Link
              to={`/wills/${selectedWillCard.willTypeName.split(' ').join('-')}/${selectedWillCard.willTypeID}`}
              state={selectedWillCard.willTypeName}
            >
              <Button
                variant="primary"
              >
                Continue
              </Button>
            </Link>
          )
        }
      </Modal.Footer>
    </Modal>
  );
}
"""

You are react developer expert.
when i click on card-container-draft-will div element, to attribute of Link component is not changing.
it should be `/wills/Templated-Full-Will/6`.
right now it is `/wills//`.
pleasde make neccessary change ans return the correct code.


your solution is appreciated gpt.
but when i click on card-container-draft-will div element second time, route is not updating. initially when component loads, route is correct, route navigated to `/wills/Templated-Full-Will/6`.
but when user clicks on second time or more it is set to  `/wills//` as route.
somethnig is wrong. please check code thouroghly and find a solution to resolve this bug.

It is still not working.
when component loads initially, route is /wills/Templated-Full-Will/6, then i click on card-container-will-copy-upload, route again updated to wills/Full-Will/1, but when i again click on 
card-container-draft-will div element, route is not set to /wills/Templated-Full-Will/6. i want the route to set to /wills/Templated-Full-Will/6. there are some bugs in handleCardClick function.
please update the code.\


  const handleContinueButtonClick = () => {
    const formattedWillTypeName = selectedWillCard.willTypeName.split(' ').join('-');
    const toPath = `/wills/${formattedWillTypeName}/${selectedWillCard.willTypeID}`;
    console.log('Path: ', toPath);
    navigate(toPath, { state: selectedWillCard.willTypeName });
  };

Path:  /wills//

i am getting the path as above when i again click on card-container-draft-will div element.

 i want path to be: /wills/Templated-Full-Will/6
import React, { useState } from "react";
import { HobbyList } from "./Child";
import "./style.css";

function App() {
  const hobbies = ["playing", "singing", "shooting"];

  const [hobbiess, setHobbies] = useState(hobbies);

  const handleDelete = (hobbo) => {
    const hob = hobbiess.filter((hobby) => hobby !== hobbo);
    setHobbies(hob);
  };

  return (
    <div className="App">
      {hobbiess.map((hobby) => (
        <HobbyList key={hobby} hobby={hobby} handleDelete={handleDelete} />
      ))}
    </div>
  );
}

export default App;


// Child Component 

import React, { useState } from "react";

export const HobbyList = (props) => {
  const [checkBox, setCheckBox] = useState(false);
  const handleCheckBox = () => {
    setCheckBox(!checkBox);
  };

  console.log(props);

  return (
    <div style={{ display: "flex" }}>
      <input type="checkbox" onChange={handleCheckBox} />
      <div>{props.hobby}</div>
      {checkBox ? (
        <button onClick={() => props.handleDelete(props.hobby)}>delete</button>
      ) : null}
    </div>
  );
};
function isEmpty(value) {
  if (value === undefined) {
    return true;
  }

  if (value === null) {
    return true;
  }

  if (typeof value === 'string' && /^[\s\u00A0]*$/.test(value)) {
    return true;
  }

  if (Array.isArray(value) && value.length === 0) {
    return true;
  }

  if (typeof value === 'object' && Object.keys(value).length === 0) {
    return true;
  }

  if (typeof value === 'number' && isNaN(value)) {
    return true;
  }

  if (value instanceof Date && isNaN(value.getTime())) {
    return true;
  }

  if (typeof value === 'boolean' && !value) {
    return true;
  }

  if (typeof value === 'function') {
    return true;
  }

  // Treat any other object as non-empty
  if (typeof value === 'object') {
    return false;
  }

  return false;
}

// Usage
var moment = require('moment');

var variable1;
console.log(isEmpty(variable1)); // true

var variable2 = null;
console.log(isEmpty(variable2)); // true

var variable3 = 'Hello';
console.log(isEmpty(variable3)); // false

var variable4 = 0;
console.log(isEmpty(variable4)); // true

var variable5 = '0';
console.log(isEmpty(variable5)); // true

var variable6 = '    ';
console.log(isEmpty(variable6)); // true

var variable7 = '\t\t';
console.log(isEmpty(variable7)); // true

var variable8 = '\n';
console.log(isEmpty(variable8)); // true

var variable9 = [];
console.log(isEmpty(variable9)); // true

var variable10 = {};
console.log(isEmpty(variable10)); // true

var variable11 = new Date('Invalid Date');
console.log(isEmpty(variable11)); // true

var variable12 = function() {
  // Function body
};
console.log(isEmpty(variable12)); // true

var variable13 = moment('2023-07-10', 'YYYY-MM-DD');
console.log(isEmpty(variable13)); // false

var variable14 = false;
console.log(isEmpty(variable14)); // true

var variable15 = { foo: 'bar' };
console.log(isEmpty(variable15)); // false
import React, { useEffect, useState } from "react";
import "./style.css";

const App = () => {
  const [data, setData] = useState({});
  const [showInfo, setShowInfo] = useState(false);

  const fetchData = async () => {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts");
    const result = await response.json();
    setData(result);
    console.log(result);
  };

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

  const handleButtonClick = () => {
    setShowInfo(!showInfo);
  };

  return (
    <>
      <button onClick={handleButtonClick}>
        {showInfo ? "Hide Info" : "Get Info"}
      </button>
      <br />
      {showInfo && data[10].title}
    </>
  );
};

export default App;
"""
function ChooseMethodModal({ showModal, handleModalClose, handleContinue }: ChooseMethodModalProps) {
  const [activeCard, setActiveCard] = useState('draftWill');
  const [selectedWillCard, setSelectedWillCard] = React.useState({
    willTypeName: 'Templated Full Will',
    willTypeID: '6',
  });
  const { results } = useSelector(willsListSelector);

  const dispatch = useDispatch();

  React.useEffect(() => {
    // dispatch<any>(fetchWillsList());
  }, []);

  /**
 * Handles the click event on the card and sets the active card name.
 *
 * @param {string} cardName - The name of the card that was clicked.
 * @return {void} This function does not return anything.
 */
  const handleCardClick = (cardName: string) => {
    setActiveCard(cardName);
    // log the card name
    console.log(cardName);
    // log active card
    console.log(activeCard);
    const { willTypeName, willTypeID } = results.find((will: any) => {
      if (cardName === 'draftWill') return will.willTypeName === 'Templated Full Will';
      if (cardName === 'willCopyUpload') return will.willTypeName === 'Full Will';
      return false;
    }) || { willTypeName: '', willTypeID: '' };
    setSelectedWillCard({ willTypeName, willTypeID });
  };

  const isAnyWillCardSelected = selectedWillCard.willTypeName !== '' && selectedWillCard.willTypeID !== '';

  return (
    <Modal show={showModal} onHide={handleModalClose} dialogClassName="modal-dialog-centered" size="lg">
      <Modal.Header closeButton>
        <Modal.Title className="modal-title">Choose Method</Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <div>
          <div className="modal-choose-method-subtitle mb-3">
            List your Substitute Beneficiaries below and click on Add Substitute to add them to your List
          </div>
        </div>
        <div className="d-flex flex-row">
          <div
            className={`card-container-draft-will d-flex flex-column align-items-center ${activeCard === 'draftWill' ? 'active' : ''}`}
            style={{ width: '50%', marginRight: '10px', position: 'relative' }}
            onClick={() => handleCardClick('draftWill')}
          >
            {activeCard === 'draftWill' && (
            <div
              className="check-icon"
            >
              <img src={FillCheckRoundIcon} alt="Fill Check Icon" />
            </div>
            )}
            <div className="choose-method-draft-will-icon-container" style={{ marginBottom: '20px', marginTop: '20px' }}>
              <img src={DraftWillIcon} alt="Will Copy Upload Icon" />
            </div>
            <div className="text-center choose-method-draft-will-title" style={{ marginTop: '10px', marginBottom: '10px', textAlign: 'center' }}>
              Draft Will Using the System
            </div>
            <div
              className="text-center choose-method-draft-will-desc"
              style={{ marginTop: '10px', marginBottom: '10px' }}
            >
              It is a long established fact that a reader will be distracted by the readable content.
            </div>
          </div>
          <div
            className={`card-container-will-copy-upload d-flex flex-column align-items-center ${activeCard === 'willCopyUpload' ? 'active' : ''}`}
            style={{ width: '50%', marginRight: '10px', position: 'relative' }}
            onClick={() => handleCardClick('willCopyUpload')}
          >
            {activeCard === 'willCopyUpload' && (
            <div
              className="check-icon"
              style={{
                position: 'absolute', top: '10px', left: '10px', margin: '10px',
              }}
            >
              <img src={FillCheckRoundIcon} alt="Fill Check Icon" />
            </div>
            )}
            <div
              className="choose-method-will-upload-icon-container"
              style={{ marginBottom: '20px', marginTop: '20px' }}
            >
              <img src={WillCopyUploadIcon} alt="Will Copy Upload Icon" />
            </div>
            <div className="text-center choose-method-will-upload-title" style={{ marginTop: '10px', marginBottom: '10px', textAlign: 'center' }}>
              Upload the Copy of Will
            </div>
            <div className="text-center choose-method-will-upload-desc" style={{ marginTop: '10px', marginBottom: '10px' }}>
              It is a long established fact that a reader will be distracted by the readable content.
            </div>
          </div>
        </div>
      </Modal.Body>
      <Modal.Footer className="justify-content-center">
        {
          activeCard && (
            <Link
              to={`/wills/${selectedWillCard.willTypeName.split(' ').join('-')}/${selectedWillCard.willTypeID}`}
              state={selectedWillCard.willTypeName}
            >
              <Button
                variant="primary"
              >
                Continue
              </Button>
            </Link>
          )
        }
      </Modal.Footer>
    </Modal>
  );
}
"""

when component loads, card-container-draft-will is selected by default. when user clicks on card-container-will-copy-upload, that element is selected. But when user clicks on card-container-draft-will again after clickin will-copy-upload, problem is when clicking continue button, Link is not naviating to the indented component/page. it is not moving to indented page.
please update the code. and make it correct.
but now when i click on card-container-draft-will element, COnitnue button not showing. please fix this bug.
import React, { useState } from "react";
import "./style.css";

const App = () => {
  const initialState = {
    userName: "",
    fullName: "",
    age: "",
  };

  const [data, setData] = useState(initialState);
  const [display, setDisplay] = useState(false);

  const printValues = (e) => {
    e.preventDefault();
    setDisplay(true);
  };

  const updateField = (e) => {
    setData({
      ...data,
      [e.target.name]: e.target.value,
    });
  };

  return (
    <>
      <form onSubmit={printValues}>
        <div>
          <label htmlFor="userName">
            User Name:
            <input
              value={data.userName || ""}
              name="userName"
              onChange={updateField}
            />
          </label>
        </div>
        <br />
        <div>
          <label htmlFor="fullName">
            Full-name:
            <input
              name="fullName"
              value={data.fullName || ""}
              onChange={updateField}
            />
          </label>
        </div>
        <br />
        <div>
          <label htmlFor="age">
            Age:
            <input name="age" value={data.age || ""} onChange={updateField} />
          </label>
        </div>
        <br />
        <button type="submit">Submit</button>
      </form>

      {display && (
        <>
          <h4>Request sent to DB with below request data</h4>
          <ul>
            <li>UserName: {data.userName.toUpperCase()}</li>
            <li>FullName: {data.fullName.toUpperCase()}</li>
            <li>Age: {data.age}</li>
          </ul>
        </>
      )}
    </>
  );
};

export default App;
function getParent(element) {
  return element.parentNode;
}

var body = document.querySelector("body");
var bodyParent = getParent(body);
function getAllElementsByXpath(xpath) {
  var results = [];
  var query = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  for (var i = 0, length = query.snapshotLength; i < length; ++i) {
    results.push(query.snapshotItem(i));
  }
  return results;
}
//Get a element by xpath
function getElementByXpath(path) {
  return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
getElementByXpath("//*[@id='someId']/div[3]/div/div/div[1]/a[2]")
import React, { useState } from "react";

const App = () => {
  const [list, setList] = useState([]);
  const [input, setInput] = useState("");

  const handleSetInput = (e) => {
    setInput(e.target.value);
  };

  const addTodo = (todo) => {
    const newTodo = {
      id: Math.random(),
      todo: todo,
      completed: false,
    };

    setList([...list, newTodo]);

    setInput("");
  };

  const handleAddClick = () => {
    addTodo(input);
  };

  const handleToggleComplete = (id) => {
    setList((prevList) =>
      prevList.map((todo) => {
        if (todo.id === id) {
          return { ...todo, completed: !todo.completed };
        }
        return todo;
      })
    );
  };

  const handleDelete = (id) => {
    const filtered = list.filter((todo) => todo.id !== id);
    setList(filtered);
  };

  return (
    <div>
      <h1>Todo List</h1>
      <input type="text" value={input} onChange={handleSetInput} />
      <button onClick={handleAddClick}>Add</button>
      <ul>
        {list.map((todo) => (
          <li key={todo.id}>
            <input
              type="checkbox"
              checked={todo.completed}
              onChange={() => handleToggleComplete(todo.id)}
            />
            <span
              style={{
                textDecoration: todo.completed ? "line-through" : "none",
              }}
            >
              {todo.todo}
            </span>
            {todo.completed && (
              <button onClick={() => handleDelete(todo.id)}>&times;</button>
            )}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default App;
function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    var ga = new GlideAjax('PhoneNumberFormatter');
    ga.addParam('sysparm_name', 'process');
    ga.addParam('sysparm_phoneNumber', newValue);
    ga.getXMLAnswer(checkPhoneNumber);

    function checkPhoneNumber(response) {
        var responseArr = response.split(',');
        //if phonenumber is invalid
        if (responseArr[0] == "NO_MATCH") {
            g_form.clearValue('phone_number');
            if (responseArr[1] != 'null')
                g_form.showFieldMsg('phone_number', getMessage('XXX not a valid phone number') + decodeURI(responseArr[1]), 'error'); //invalid number
            else
                g_form.showFieldMsg('phone_number', getMessage('XXX phone number no country code'), 'error'); //no country code provide
        }
        //For valid phonenumbers, set phoneumber with returned value and remove spaces for uniformity
        else {
            g_form.hideFieldMsg('phone_number');
            g_form.setValue('phone_number', decodeURI(responseArr[0]).replaceAll(" ", ""));
        }
    }

}
/**
 * Base data service that provide dataUtils and other default helper functions
 * @constructor
 * @type {XXXServiceBase}
 * @extends Base
 * @ignore
 */
var XXXServiceBase = Class.create();
XXXServiceBase.prototype = Object.extendsObject(XXXBase, /** @lends BACServiceBase.prototype */ {


    /** @member {string} */
    TABLE: '',

    /** @constant {String} */
    LOG_PROPERTY: 'base_script_include.log.level',

    /**
     * @return {XXXServiceBase}
     */
    initialize: function () {
        XXXBase.prototype.initialize.call(this);
        return this;
    },

    /**
     * Returns an empty initialized GlideRecord for the current table
     * @return {GlideRecord} return initialized GlideRecord
     */
    getEmptyRecord: function () {
        var gr = new GlideRecord(this.TABLE);
        gr.newRecord();
        return gr;
    },

    /**
     * @param {string} id
     * @returns {GlideRecord|null}
     */
    getGlideRecordByID: function (id) {
        var gr = new GlideRecord(this.TABLE);
        if (gr.get(id)) {
            return gr;
        }
        return null;
    },

    /**
     * @param {GlideRecord|GlideRecordSecure} grToValidate
     * @param {string} encodedQuery
     * @returns {string[]|null}
     */
    getSysIDArrayByCondition: function (grToValidate, encodedQuery) {
        var matchedGR = [];
        var grSource = this.getGlideRecordByEncodedQuery(encodedQuery);
        if (grSource) {
            while (grSource.next()) {
                // check if record fulfill conditions on interface record
                var hasMatch = GlideFilter.checkRecord(grToValidate, grSource.condition);
                if (hasMatch) {
                    gs.debug('Found match: ' + grSource.name);
                    matchedGR.push('' + grSource.sys_id);
                }
            }
            if (matchedGR.length > 0) {
                gs.debug('Found results');
                return matchedGR;
            }
            gs.debug('Nothing in matchedGR');
            return null;

        }
        gs.debug('No matches found for this GlideRecord.');
        return null;

    },

    /**
     * @param {string} key
     * @param {*} value
     * @returns {GlideRecord|GlideRecordSecure|null}
     */
    getGlideRecordByKeyValue: function (key, value) {
		this.logger.logDebug('result id ' + this.TABLE);
        var gr = new GlideRecord(this.TABLE);
        if (gr.get(key, value)) {
            return gr;
        }
        return null;

    },

    /**
     * @param {string} encodedQuery
     * @returns {number|null}
     */
    getCountAggregate: function (encodedQuery) {
        var gr = new GlideAggregate(this.TABLE);
        gr.addAggregate('COUNT');
        if (encodedQuery != '') {
            gr.addEncodedQuery(encodedQuery);
        }
        gr.query();
        if (gr.next()) {
            return gr.getAggregate('COUNT');
        }
        return null;


    },

    /**
     * @param {string} encodedQuery
     * @returns {GlideRecord|GlideRecordSecure|null}
     */
    getGlideRecordByEncodedQuery: function (encodedQuery) {
        var gr = new GlideRecord(this.TABLE);
        if (encodedQuery != '') {
            gr.addEncodedQuery(encodedQuery);
        }
        gr.query();
        if (gr.hasNext()) {
            return gr;
        }
        return null;

    },

    /**
     * @param {GlideRecord|GlideRecordSecure} recordGr
     * @param {string} parentField
     * @returns {boolean}
     */
    checkParentRecursion: function (recordGr, parentField) {
        var table = this.TABLE;
        var recursion = false;
        var parentId = recordGr.getValue(parentField);
        if (parentId == recordGr.getValue('sys_id')) {
            recursion = true;
        } else {
            checkRecursion(recordGr);
        }

        function checkRecursion(recordGr) {
            var childGr = new GlideRecord(table);
            childGr.addQuery(parentField, recordGr.getValue('sys_id'));
            childGr.query();
            while (childGr.next()) {
                if (childGr.getValue('sys_id') == parentId) {
                    recursion = true;
                    return;
                }

                checkRecursion(childGr);
            }
        }

        return recursion;
    },

    type: 'XXXServiceBase'
});
/**
 * XXXBase Script include
 * @constructor
 * @type {XXXBase}
 * @ignore
 */
var XXXBase = Class.create();
XXXBase.prototype = /** @lends XXXBase.prototype */{

    /** @member {DataUtils} */
    //  dataUtils: new DataUtils(),

    /** @member {QueryUtils} */
    //  queryUtils: new QueryUtils(),

    /** @member {DateTimeUtils} */
    //  dateTimeUtils: new DateTimeUtils(),

    /** @constant {String} */
    LOG_PROPERTY: 'base_script_include.log.level',

    initialize: function () {
        this.logger = new global.GSLog(this.LOG_PROPERTY, this.type);
        this.logger.includeTimestamp();
    },

    type: 'XXXBase'
};
import { Component, OnDestroy, OnInit } from '@angular/core';
// RxJs 6.x+ import paths
import { filter, startWith, takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { BookService } from '../books.service';

@Component({
    selector: 'app-books',
    templateUrl: './books.component.html'
})
export class BooksComponent implements OnDestroy, OnInit {
    private ngUnsubscribe = new Subject<void>();

    constructor(private booksService: BookService) { }

    ngOnInit() {
        this.booksService.getBooks()
            .pipe(
               startWith([]),
               filter(books => books.length > 0),
               takeUntil(this.ngUnsubscribe)
            )
            .subscribe(books => console.log(books));

        this.booksService.getArchivedBooks()
            .pipe(takeUntil(this.ngUnsubscribe))
            .subscribe(archivedBooks => console.log(archivedBooks));
    }

    ngOnDestroy() {
        this.ngUnsubscribe.next();
        this.ngUnsubscribe.complete();
    }
}
import React, { useState, useEffect } from "react";

import "./style.css";

function App() {
  const [data, setData] = useState({});
  const [unit, setUnit] = useState("fahrenheit");

  const fetchData = async (lat, lon) => {
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=ce309858c9580a2f86ac0e0f45374afb`;
    const response = await fetch(url);
    const result = await response.json();
    setData(result);
    console.log(result);
  };

  function myGeoLocator() {
    navigator.geolocation.getCurrentPosition((position) => {
      const lat = position.coords.latitude;
      const lon = position.coords.longitude;
      fetchData(lat, lon);
    });
  }

  const kelvinToFahrenheit = (temp) => {
    return (((temp - 273.15) * 9) / 5 + 32).toFixed(2);
  };

  const kelvinToCelsius = (temp) => {
    return (temp - 273.15).toFixed(2);
  };

  const handleUnitChange = () => {
    setUnit((prev) => (prev === "celsius" ? "fahrenheit" : "celsius"));
  };

  return (
    <div className="app">
      <div className="temperature">{data.name ? data.name : null}</div>

      <div className="temperature">
        {data.main ? (
          <>
            {" "}
            {unit === "celsius"
              ? kelvinToCelsius(data.main.temp)
              : kelvinToFahrenheit(data.main.temp)}
            {unit === "celsius" ? "°C" : "°F"}
          </>
        ) : null}
      </div>

      <button className="button" onClick={myGeoLocator}>
        Get Weather
      </button>

      <button className="button" onClick={handleUnitChange}>
        Celsius/Fahrenheit
      </button>
    </div>
  );
}

export default App;
import React, { useState } from "react";

function App() {
  const [data, setData] = useState({});
  const [location, setLocation] = useState("");

  const url = `https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid=ce309858c9580a2f86ac0e0f45374afb`;

  const fetchData = async () => {
    const response = await fetch(url);
    const result = await response.json();
    setData(result);
    console.log(result);
  };

  const handleSearch = () => {
  };
  
  
  function myGeoLocater() {
    {
      navigator.geolocation.getCurrentPosition((position)=>{
        let lat = position.coords.latitude;
        let long = position.coords.longitude;
        fetchData();
      }
    }
  }


  const kelvinToFahrenheit = (temp) => {
    return (((temp - 273.15) * 9) / 5 + 32).toFixed(2);
  };

  return (
    <div className="app">
      <div className="temperature">{data.name ? data.name : null}</div>

      <div className="temperature">
        {data.main ? <>{kelvinToFahrenheit(data.main.temp)}</> : null}
      </div>

      <button className="button" onClick={handleSearch}>
        Get Weather
      </button>
    </div>
  );
}

export default App;
@param -> items : Conjunto de datos a recorrer, este debe de ser un Array de Objetos.
@param -> filters : Conjunto de criterior y valores a buscar, el parametro debe de ser de tipo objeto dentro de la cual debe de haber objetos de tipo array, como se muestra en el ejemplo de las notas.
const multiFilter = (items, filters) => {
  const filterKeys = Object.keys(filters);
  return items.filter(item => {
    return filterKeys.every(key => {
      if (!filters[key].length) return true;
      if (Array.isArray(item[key])) {
        return item[key].some(keyEle => filters[key].includes(keyEle));
      }
      return filters[key].includes(item[key]);
    });
  });
};
"""
<div className="col-md-6">
              <label
                htmlFor="companyContactNumber"
                className="form-label w-100 company-contact-number-label"
              >
                Company Contact Number*
              </label>
              <div className="d-flex">
                {/* autocomlete field for isdcodelist */}
                <Autocomplete
                  ref={autocompleteRef}
                  disablePortal
                  id="isdcodelist"
                  options={isdCodesList}
                  isOptionEqualToValue={(option: any, value: any) => option.label === value.label}
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      {...register('isdCode', {
                        required: true,
                      })}
                      className="isd-code-input"
                      placeholder="+971"
                    />
                  )}
                  renderOption={(props, option) => (
                    <span
                      className="phone-number-option"
                      {...props}
                    >
                      {option.countryName}
                    </span>
                  )}
                            // onchange event handler to set the isdCode state
                  onChange={(e, value: any) => setIsdCode(
                    value?.label,
                  )}
                />
                {/* handle errors */}
                {formErrors.isdCode && (
                <span className="error-message">{formErrors.isdCode}</span>
                )}
                {/* company contact input */}
                <input
                  type="text"
                  className="form-control company-contact-number-input"
                  id="companyContactNumber"
                  placeholder="XXXXXXXXXXXXXX"
                  onInput={(e) => {
                    const input = e.target as HTMLInputElement;
                    input.value = input.value.slice(0, 15).replace(/[^0-9 ]/g, ''); // Limit the input to 15 characters and Allow only digits and spaces
                    setCompanyContactNumber(input.value);
                  }}
                  {...register('companyContactNumber', {
                    required: true,
                  })}
                />
                {/* handle errors */}
                {formErrors.companyContactNumber && (
                <span className="error-message">{formErrors.companyContactNumber}</span>
                )}
              </div>
</div>
"""

consider you are react developer.
client wants to achieve below changes in the form.

1. You have to display isdCode error below that particular autocomplete field. currently it is shown right to the field. Show it under field.

2. You have to display company contact number error below that particular field. currently it is shown right to the field. Show it under field.

3. make appropriate changes in the code and return the code.



""" 
<div className="row form-row mb-4 align-items-center">
            <div className="col-md-6">
              <label
                htmlFor="resident"
                className="form-label w-100 resident-label"
              >
                Are you a Resident of the UAE?
              </label>
            </div>
            <div className="col-md-6 d-flex justify-content-between align-items-center">
              <OptionButtons
                options={residentOrNotOptions}
                selectedOption={resident}
                onOptionSelected={handleResidentOptionSelect}
              />
            </div>
          </div>

          {/* row with columns for emirates id */}
          <div className="row form-row mb-5">
            {/* Emirates ID Col */}
            <div className="col-md-6">
              <label
                htmlFor="emiratesId"
                className="form-label w-100 emirates-id-label"
              >
                Emirates ID*
              </label>
              <input
                type="text"
                className="form-control emirates-id-input"
                id="emiratesId"
                placeholder="XXXX XXXX XXXX"
                defaultValue={userData.emiratesID}
                maxLength={15}
                onChange={(e) => setEmiratesID(e.target.value)}
                onInput={(e) => {
                  const input = e.target as HTMLInputElement;
                  input.value = input.value.replace(/\D/g, '');
                  setEmiratesID(input.value);
                }}
                {...register('emiratesID', {
                  required: true,
                })}
              />

              {/* handle errors */}
              {/* {formErrors.emiratesID && (
              <span className="error-message">{formErrors.emiratesID}</span>
              )} */}
            </div>
            {/* passport expiry date col */}
            <div className="col-md-6">
              <label
                htmlFor="emiratesIdExpiryDate"
                className="form-label w-100 emiratesId-expiry-date-label"
              >
                Emirates ID Expiry Date*
              </label>
              {/* Date Picker to handle emirates id expiry */}
              <DatePicker
                onChange={handleEmiratesExpiryDatePicker}
                value={emiratesIDExpiryDate}
                minDate={new Date().toISOString().split('T')[0].split('-').join('/')}
                renderInput={(params: any) => (
                  <TextField
                    {...params}
                    inputProps={{
                      ...params.inputProps,
                      // readonly
                      readOnly: true,
                      placeholder: 'Choose Date',
                    }}
                    {...register('emiratesIDExpiryDate', {
                      required: true,
                    })}
                    className="date-picker date-picker-input"
                  />
                )}
                className="date-picker-field"
              />
              {/* handle errors */}
              {formErrors.emiratesIDExpiryDate && (
              <span className="error-message">{formErrors.emiratesIDExpiryDate}</span>
              )}
            </div>
          </div>

"""

You are an experienced react developer.
Client want some changes in form. Details were given in below bullet points:

1. When the value of resident props of OptionButtons is No, emiratesid and emirates expiry date datepicker should be disabled.
Ie user should  not be able to input or select any data in both fields.
2. if the value is Yes, both emiratesid and emirates expiry date datepicker are enabled. 
3. Initialy when component is loaded, both were enabled.
4. It is disable only when user choose resident as No, else both the inputs were enabled.

please update the code as per my above requirements.


<p><script>
    var video1 = document.getElementById("thebpresident");
    video1.style.opacity = 1;
    video1.addEventListener("loadedmetadata", function() {
setTimeout(function() {        video1.play();<br />
      }, 1000);
    });
   slidein.className = "slidein";
});
setTimeout(function() {
video1.style.display = "block";
  }, 4000);
});
var video2 = document.getElementById("majorcities");
setTimeout(function() {
video2.style.display = "block";
video2.className = "wp-block-video MajorCities video2";
        video2.addEventListener("animationend", function() {
          video2.style.opacity = 1;
          video2.addEventListener("loadedmetadata", function() {
            setTimeout(function() {
              video2.play();
            }, 4000);
          });
        });
      }, 156000);
    });
  });  document.addEventListener("DOMContentLoaded", function() {
    var videos = document.getElementsByClassName("onPause");
    for (var i = 0; i < videos.length; i++) {
      var video = videos[i];
      video.addEventListener("click", function() {
        if (this.paused) {
          this.play();
        } else {
          this.pause();
        }
      });
    }
  });
</script></p>
import React, { useEffect, useState } from "react";
import axios from "axios";

function App() {
  const [data, setData] = useState({});
  const [location, setLocation] = useState("");
  const [showResults, setShowResults] = useState(false);

  const url = `https://api.openweathermap.org/data/2.5/weather?q=${location}&units=imperial&appid=80e8dda85f86ac0d7028efe74f5b553e`;

  const fetchData = async () => {
    const response = await axios.get(url);
    setData(response.data);
    console.log(response.data);
    setShowResults(true);
    setTimeout(() => {
      setShowResults(false);
      setLocation("");
    }, 3000);
  };

  const handleSearch = () => {
    fetchData();
  };

  const handleLocationChange = (event) => {
    setLocation(event.target.value);
  };

  const handleKeyPress = (event) => {
    if (event.key === "Enter") {
      handleSearch();
    }
  };

  return (
    <div className="app">
      <div className="search">
        <input
          type="text"
          value={location}
          onChange={handleLocationChange}
          onKeyDown={handleKeyPress}
          placeholder="EnterLocation"
        />
        <button onClick={handleSearch}>Search</button>
      </div>

      {showResults && (
        <div className="top">
          <div className="temp">
            {data.main ? <h1>{data.main.temp.toFixed()}°F</h1> : null}
          </div>
        </div>
      )}
    </div>
  );
}

export default App;

// CSS 


.app {
  max-width: 400px;
  margin: 3rem auto;
  padding: 20px;
}

.search {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

input[type="text"] {
  width: 200px;
  padding: 8px;
  border-radius: 4px;
  border: 1px solid #ccc;
  margin-right: 10px;
}

button {
  padding: 8px 16px;
  border-radius: 4px;
  background-color: #4caf50;
  color: white;
  border: none;
  cursor: pointer;
}
To populate the form fields of the previous step when the "Back" button is clicked, you can store the form data in the parent component and pass it as props to the child components. Here's an updated example:

UserOnBoardingMain component:

```jsx
import React, { useState } from 'react';
import UserRegistrationForm from './UserRegistrationForm';
import UserRegistrationFormAddressInfo from './UserRegistrationFormAddressInfo';
import UserRegistrationFormCompanyInfo from './UserRegistrationFormCompanyInfo';

const UserOnBoardingMain = () => {
  const [step, setStep] = useState(1);
  const [userData, setUserData] = useState({});

  const handleNextStep = (data) => {
    setUserData((prevData) => ({ ...prevData, ...data }));
    setStep((prevStep) => prevStep + 1);
  };

  const handleBackStep = () => {
    setStep((prevStep) => prevStep - 1);
  };

  return (
    <>
      {step === 1 && (
        <UserRegistrationForm onNextStep={handleNextStep} userData={userData} />
      )}
      {step === 2 && (
        <UserRegistrationFormAddressInfo
          onNextStep={handleNextStep}
          onBackStep={handleBackStep}
          userData={userData}
        />
      )}
      {step === 3 && (
        <UserRegistrationFormCompanyInfo
          onNextStep={handleNextStep}
          onBackStep={handleBackStep}
          userData={userData}
        />
      )}
    </>
  );
};

export default UserOnBoardingMain;
```

UserRegistrationForm component:

```jsx
import React from 'react';
import { useForm } from 'react-hook-form';

const UserRegistrationForm = ({ onNextStep, userData }) => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm();

  const onSubmit = (data) => {
    onNextStep(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {/* Form fields */}
      <input {...register('fieldName')} defaultValue={userData.fieldName} />
      {/* Other form fields */}
      <button type="submit">Next</button>
    </form>
  );
};

export default UserRegistrationForm;
```

UserRegistrationFormAddressInfo and UserRegistrationFormCompanyInfo components would have similar implementations.

In the above code, the `userData` state is updated whenever the `handleNextStep` function is called, which is triggered when the "Next" button is clicked in each form step. The `userData` is then passed as props to the child components. When the "Back" button is clicked, the `handleBackStep` function is called, which reduces the `step` value by 1, allowing you to navigate back to the previous step.

By providing the `defaultValue` prop to each form field in the `UserRegistrationForm` component, the fields will be populated with the corresponding values from the `userData` object. This way, when you navigate back to the previous step, the form fields will be prepopulated with the previously entered values.

Make sure to adjust the form field names and structure according to your specific requirements.
To create a Google Maps API, follow these steps:

1. Go to the Google Cloud Console: https://console.cloud.google.com.
2. Sign in with your Google account or create a new account if you don't have one.
3. Create a new project by clicking on the project dropdown at the top of the page and selecting "New Project." Enter a name for your project and click "Create."
4. Once your project is created, you will be redirected to the project dashboard.
5. Enable the Google Maps JavaScript API:
   - Click on the menu icon (☰) in the upper-left corner of the Cloud Console.
   - In the sidebar, click on "APIs & Services" > "Library."
   - Search for "Google Maps JavaScript API" and select it from the results.
   - Click on the "Enable" button.
6. Set up API credentials:
   - Click on the menu icon (☰) in the upper-left corner of the Cloud Console.
   - In the sidebar, click on "APIs & Services" > "Credentials."
   - Click on the "Create credentials" button and select "API key."
   - Copy the generated API key.
7. Restrict your API key (optional, but recommended for security):
   - On the credentials page, click on the API key you created.
   - Under "Key restriction," select the option that best fits your use case (e.g., HTTP referrers, IP addresses).
   - Configure the allowed referrers or IP addresses as needed.
8. Use your API key in your code:
   - Replace `YOUR_API_KEY` in your code with the API key obtained in the previous step.

Make sure to follow any additional usage limits and terms of service specified by Google. It's also important to secure and protect your API key to prevent unauthorized usage.

Please note that creating and using the Google Maps API may involve costs depending on your usage and the services used. Refer to the Google Cloud Console for pricing information and billing details.
Error:
Google Maps JavaScript API error: ApiNotActivatedMapError
https://developers.google.com/maps/documentation/javascript/error-messages#api-not-activated-map-error

https://www.youtube.com/watch?v=n1UorU1PALk&t=47s

The "ApiNotActivatedMapError" error typically occurs when the Google Maps JavaScript API is not activated or enabled for your project. Here are some steps you can follow to resolve this error:

1. Go to the Google Cloud Console (https://console.cloud.google.com).
2. Select your project or create a new project if needed.
3. Make sure you have a billing account associated with your project. The Google Maps JavaScript API requires a billing account to be set up.
4. Enable the Google Maps JavaScript API for your project. You can do this by following these steps:
   - Click on the menu icon (☰) in the upper-left corner of the Cloud Console.
   - In the sidebar, click on "APIs & Services" > "Library".
   - Search for "Google Maps JavaScript API" and select it from the results.
   - Click on the "Enable" button.
5. Set up the required API credentials. You need to create an API key and configure it to be used in your code.
   - Click on the menu icon (☰) in the upper-left corner of the Cloud Console.
   - In the sidebar, click on "APIs & Services" > "Credentials".
   - Click on the "Create credentials" button and select "API key".
   - Copy the generated API key.
6. Update your code with the API key.
   - Replace `GOOGLE_MAPS_API_KEY` in your code with the API key obtained in the previous step.

After completing these steps, the Google Maps JavaScript API should be activated and the "ApiNotActivatedMapError" should no longer occur.
Sure, here is an email you can send to your HR:

Subject: Sick Leave Request

Dear Sony R,

I am writing to request a sick leave for today, June 28, 2023, due to fever and cold. I woke up this morning with a fever of 102 degrees Fahrenheit and a sore throat. I have also been feeling congested and have a runny nose.

I have already made an appointment with my doctor and will be going to see them later today. I will keep you updated on my condition and let you know when I expect to be back in the office.

In the meantime, I have already informed my team of my absence and have asked [colleague's name] to cover my workload.

I apologize for any inconvenience this may cause.

Thank you for your understanding.

Sincerely,

Jissmon Jose
Software Developer
8921762662
setTimeout(function(){
    modal.style.display = 'inline'
}, 1500)
  const handleMobileNumberValidation = (phone: string) => {
    // const mobileNumberRegex = /^[+0-9\s]*$/;
    // const mobileNumberRegex = /^\+(?:[0-9] ?){6,14}[0-9]$/;
    const mobileNumberRegex = /^(?:[0-9] ?){6,14}[0-9]$/;
    return mobileNumberRegex.test(phone);
  };


    if (primaryMobileNumber.trim() !== '') {
      if (!handleMobileNumberValidation(primaryMobileNumber)) {
        errors.primaryMobileNumber = 'Invalid mobile number';
      }
    }


    <div className="col-md-6">
              <label htmlFor="mobile" className="form-label w-100 mobile-label">
                Primary Mobile Number*
              </label>
              <div className="d-flex">
                {/* autocomlete field for isdcodelist */}
                <Autocomplete
                  disablePortal
                  id="isdcodelist"
                  options={isdCodesList}
                  isOptionEqualToValue={(option: any, value: any) => option.label === value.label}
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      {...register('isdCode', {
                        required: true,
                      })}
                      className="isd-code-input"
                      placeholder="+971"
                    />
                  )}
                  renderOption={(props, option) => (
                    <span
                      className="phone-number-option"
                      {...props}
                    >
                      {option.countryName}
                    </span>
                  )}
                            // onchange event handler to set the isdCode state
                  onChange={(e, value: any) => setIsdCode(
                    value?.label,
                  )}
                />
                <input
                  type="text"
                  className="form-control mobile-input"
                  id="mobile"
                  placeholder="XXX XXX XXXX"
                // onchange
                  onChange={(e) => setPrimaryMobileNumber(e.target.value)}
                  {...register('primaryMobileNumber', {
                    required: true,
                  })}
                />
              </div>
              {/* handle errors */}
              {formErrors.primaryMobileNumber && (
              <span className="error-message">{formErrors.primaryMobileNumber}</span>
              )}
            </div>

const [formErrors, setFormErrors] = useState<UserRegistrationDetails>({
    firstName: '',
    lastName: '',
    gender: '',
    dateOfBirth: '',
    primaryEmail: '',
    secondaryEmail: '',
    primaryMobileNumber: '',
    secondaryMobileNumber: '',
    service: '',
  });

  const validateEmail = (email: string) => {
    const emailRegex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
    return emailRegex.test(email);
  };

 const handleUserRegistrationForm = () => {
   
  const handleEmptyField = (fieldName: string, fieldValue: string, errorMessage: string) => {
      if (!fieldValue) {
        errors[fieldName] = errorMessage;
      }
    };

    handleEmptyField('firstName', firstName, 'First name is required');
    handleEmptyField('lastName', lastName, 'Last name is required');
    handleEmptyField('primaryEmail', primaryEmail, 'Primary email is required');
    handleEmptyField('primaryMobileNumber', primaryMobileNumber, 'Primary mobile number is required');
    handleEmptyField('dateOfBirth', dateOfBirth, 'Date of birth is required');

    if (primaryEmail.trim() !== '') {
      if (!validateEmail(primaryEmail)) {
        errors.primaryEmail = 'Invalid email';
      }
    }

    setFormErrors(errors);

 }
 
<input
                type="email"
                className="form-control email-input"
                id="email"
                placeholder="abc@babc.com"
                // onchange
                onChange={(e) => setPrimaryEmail(e.target.value)}
                {...register('primaryEmail', {
                  required: true,
                })}
              />




<DatePicker
                onChange={handleDatePicker}
                value={dateOfBirth}
                disableFuture
                maxDate={subYears(new Date(), 21)}
                renderInput={(params: any) => (
                  <TextField
                    {...params}
                    inputProps={{
                      ...params.inputProps,
                      readOnly: true,
                      placeholder: 'Select Date of Birth',
                    }}
                    {...register('dateOfBirth', {
                      required: true,
                      validate: {
                        ageVerification: (dateString) => {
                          const date = new Date(dateString);
                          return isAfter(subYears(new Date(), 21), date);
                        },
                      },
                    })}
                    className="date-picker date-picker-input"
                  />
                )}
                className="date-picker-field"
              />
<input
  type="text"
  className="form-control firstname-input"
  id="firstname"
  placeholder="John"
  onInput={(e) => {
    const input = e.target as HTMLInputElement;
    input.value = input.value.replace(/[^a-zA-Z ]/g, '');
    setFirstName(input.value);
  }}
  {...register('firstName', {
    required: true,
  })}
/>
<input
  type="text"
  className="form-control firstname-input"
  id="firstname"
  placeholder="John"
  onInput={(e) => {
    const input = e.target as HTMLInputElement;
    input.value = input.value.replace(/[^a-zA-Z ]/g, '');
    setFirstName(input.value);
  }}
  {...register('firstName', {
    required: true,
  })}
/>
//Combining arrays
const obj1 = 
{
  name: 'A',
  age: 25
},
{
  name: 'B',
  age: 25
};

const obj2 = 
{
  name: 'C',
  age: 25
};

const total = [...obj1, ...obj2];

// getting elements from array
const [a, b] = total;
//console.log: a = first element from total

const numbers = array.map(function (n)) {
  return n.name;
}
const arr = ["1", "2", "3"];

for(let cont of arr) {
  console.log(cont);
}


const arr = [
  {
    name: '1',
    agr: 2
  },
  {
    name: '1',
    agr: 2
  }
];

for(let cont of arr) {
  console.log(cont.name);
}
const obj = {
  name: 'Test',
  age: '99'
};

console.log(Object.keys(obj));
//console: ["name", "age"]

console.log(Object.values(obj));
//console: ["Test", "99"]
const names = [{name:'abc'},{name:'def'},{name:'ghi'}];
const entries = Object.fromEntries(names.entries());
const mappedNames = Object.keys(entries).map(key => [`string${key}`, entries[key]])

const newNames = Object.fromEntries(mappedNames)
data(){
return {
      colors: [
        "red",
        "blue",
        "green",
        "indigo",
        "purple",
        "teal",
        "orange",
        "brown",
        "deep-orange",
        "blue-grey",
        "cyan"
      ],
      currentColor: ""
    }
},

 methods: {
    randomColors() {
      this.currentColor = 
        this.colors[Math.floor(Math.random() * this.colors.length)];
    },
  }
import Autocomplete from './autocomplete';
import countries from '../data/countries';

describe('Test the autocomplete functionality', () => {
  beforeEach(() => {
    cy.mount(<Autocomplete countries={countries} />);
  })

  it('check everything is working in ui', () => {
    cy.get('[data-cy="heading"]').contains('Search your country:');
    cy.get('input[type="text"]').should('have.value', '');
    cy.get('[data-cy="suggestion-list"]').should('not.exist');
  })

  it('check filter is working', () => {
    cy.get('input[type="text"]').type('no');
    cy.get('[data-cy="suggestion-list"]').should('be.visible').as('suggestList');
    cy.get('@suggestList').should('have.length', 1);
  })


  it('check selections are working', () => {
    cy.get('input[type="text"]').as('inputText');
    cy.get('@inputText').type('no').type(Cypress._.repeat('{downArrow}{downArrow}', 1));
    cy.get('[data-cy="suggestion-list"] li:nth-child(3)').should('have.class', 'active');
    cy.get('@inputText').type(Cypress._.repeat('{upArrow}', 1));
    cy.get('[data-cy="suggestion-list"] li:nth-child(2)').should('have.class', 'active');
    cy.get('[data-cy="suggestion-list"] li:nth-child(2)').click();
    cy.get('input[type="text"]').should('have.length', 1);
    cy.get('[data-cy="suggestion-list"]').should('not.exist');
  })

})
import { fetchBaseQuery } from '@reduxjs/toolkit/query'
import { tokenReceived, loggedOut } from './authSlice'

const baseQuery = fetchBaseQuery({ baseUrl: '/' })
const baseQueryWithReauth = async (args, api, extraOptions) => {
  let result = await baseQuery(args, api, extraOptions)
  if (result.error && result.error.status === 401) {
    // try to get a new token
    const refreshResult = await baseQuery('/refreshToken', api, extraOptions)
    if (refreshResult.data) {
      // store the new token
      api.dispatch(tokenReceived(refreshResult.data))
      // retry the initial query
      result = await baseQuery(args, api, extraOptions)
    } else {
      api.dispatch(loggedOut())
    }
  }
  return result
}
<!doctype html>

  <head>
    <!-- CSS CODE -->
   <style>
    #pdf_renderer {
      display: block;
      margin: 0 auto;
    }
    </style>
  
  </head>
<body>
     <div id="my_pdf_viewer">
        <div id="canvas_container">
            <canvas id="pdf_renderer"></canvas>
        </div>

        <center>
            <div id="navigation_controls">
                <button id="go_previous">Previous</button>
                <input id="current_page" value="1" type="number"/>
                <button id="go_next">Next</button>
            </div>

            <a href="Resume_14.docx.pdf" download="Resume_14.docx.pdf">
            Download PDF</a>
        </center>
    </div>
    <script>
        var myState = {
            pdf: null,
            currentPage: 1,
            zoom: 1
        }
     
        pdfjsLib.getDocument('./Resume_14.docx.pdf').then((pdf) => {
            myState.pdf = pdf;
            render();
        });

        function render() {
            myState.pdf.getPage(myState.currentPage).then((page) => {
         
                var canvas = document.getElementById("pdf_renderer");
                var ctx = canvas.getContext('2d');
     
                var viewport = page.getViewport(myState.zoom);
                canvas.width = viewport.width;
                canvas.height = viewport.height;
         
                page.render({
                    canvasContext: ctx,
                    viewport: viewport
                });
            });
        }

        document.getElementById('go_previous').addEventListener('click', (e) =>
        {
          if(myState.pdf == null || myState.currentPage == 1) 
            return;
          myState.currentPage -= 1;
          document.getElementById("current_page").value = myState.currentPage;
          render();
        });
        document.getElementById('go_next').addEventListener('click', (e) => {
          if(myState.pdf == null || myState.currentPage > myState.pdf._pdfInfo.numPages) 
             return;
          myState.currentPage += 1;
          document.getElementById("current_page").value = myState.currentPage;
          render();
        });
        document.getElementById('current_page').addEventListener('keypress', (e) => {
          if(myState.pdf == null) return;
         
          // Get key code 
          var code = (e.keyCode ? e.keyCode : e.which);
         
          // If key code matches that of the Enter key 
          if(code == 13) {
            var desiredPage = document.getElementById('current_page').valueAsNumber;
                                 
            if(desiredPage >= 1 && desiredPage <= myState.pdf._pdfInfo.numPages) {
                myState.currentPage = desiredPage;
                document.getElementById("current_page").value = desiredPage;
                render();
            }
           }
        });

    </script>
  </body>
</html>
HTML, XML
<div id="fecha"></div>

<script src="js/fecha.js"></script>
function fetxa() {
    const diasSemana = ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"];
    const meses = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Júnio", "Júlio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];
    var fexa = new Date();
    var hoy = diasSemana[fexa.getUTCDay()];
    var dia = fexa.getUTCDate();
    var mes = meses[fexa.getUTCMonth()];
    var any = fexa.getUTCFullYear();

    document.getElementById("fecha").innerHTML = `<span>${hoy} ${dia}, del mes de ${mes} del ${any}</span>`;
    
}

<link href="https://fonts.cdnfonts.com/css/ds-digital" rel="stylesheet">
                
function digital() {
    let laHora = new Date();

    let horas = laHora.getHours();

    if (horas < 10) {
        horas = "0" + horas;
    }


    let minutos = laHora.getMinutes();

    if (minutos < 10) {
        minutos = "0" + minutos;
    }


    let segundos = laHora.getSeconds();

    if (segundos < 10) {
        segundos = "0" + segundos;
    }


    const reloj = `<aside id="relojillo"><h1>${horas} : </h1> <h2>${minutos}</h2><sup><h3> : ${segundos}</h3></sup></aside>`;

    const salida = document.getElementById("elReloj").innerHTML = reloj;

    setTimeout(digital, 1000);


    return salida;
}
digital();
<body>
    <aside id="elReloj"></aside>
    <script src="js/digital02.js"></script>
</body>
  <style>
      * {
          box-sizing: border-box;
      }
      
      @font-face {
          font-family: 'ds-digital';
          src: url('./ds_digital/DS-DIGII.TTF');
      }
      body {
          
      }
      #relojillo {
          width: fit-content;
          height: auto;
          position: relative;
          background-image: linear-gradient(232deg, #888, #888, #888);
          margin: auto auto;
          text-align: center;
          background-color: transparent;
          padding: 10% 10%;
      }
      
      #relojillo h1,
      #relojillo h2,
      #relojillo h3 {
          display: inline-block;
          font-family: 'ds-digital';
          font-size: 43pt;
          text-shadow: 0vw -3vw .1vw #999, -.3vw 4vw .1vw #f0f8ff;
          color: khaki;
          padding: 0vw .2vw;
      }
      #relojillo h3 {
          font-size: 21pt !important;
          text-shadow: 0vw -3vw .1vw orange, -.3vw 4vw .1vw orange;
      }
  </style>
"""
Problem Description
Given a number N, you have to find the largest Fibonacci number which is less than N.

Input Format
First line contains an integer T - Number of test cases.

Next T lines each have a given number N

Output Format
Print the answer for each test case in a separate line.

Sample Input 1
2

6

13

Sample Output 1
5

8

Explanation 1
In the first test case the largest Fibonacci number less than 6 is 5.

In the second test case the largest Fibonacci number less than 13 is 8 (the next Fibonacci number after 8 is 13 which is equal to the number N i.e. 13)

Constraints
T <= 10^4

0 < N <= 10^9
"""

Please help me to debug the below code based on details given above and return the updated full version of code.

"""
'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.replace(/\s+/g, " ").trim();
    });
    main();
});

function readLine() {
    return inputString[currentLine++];
}

function readIntArr() {
    let str = readLine();
    str = str.split(" ");
    let arr = [];
    for ( let i = 0; i < str.length; i++ ) {
        arr.push(parseInt(str[i], 10));
    }
    return arr;
}

function print(x) {
    process.stdout.write(x + "");
}

function largestFibonacciNumber(n) {
    let a = 0;
    let b = 1;
    while (b <= n)
    {
        a = b;
        b = a + b;
    }
    return a;
}

function main() {
    let t=parseInt(readLine(),10);
    while(t--){
    let n=parseInt(readLine(),10)

    let result=largestFibonacciNumber(n);
    console.log(result);
    }
}
"""
let model = new models.Model<Post>({
    name: 'posts',
    sync: getPost(123),
    streams: [postEvents, commentEvents],
});

// define mutation functions
function updatePost(post: Post) {
    return async function() {
        await fetch(`/posts/${post.id}`, {
            method: "PUT",
            body: JSON.stringify(post),
        });
    }
}
// register the mutations on the model
model.NewMutation(updatePost, {
    name: 'updatePost',
    stream: 'post',
    optimistic: function(post) {
        return post;
    }
});
model.subscribe('loading', loading => ...);
model.subscribe('update', data => ...);
model.subscribe('error', err => ...);
model.subscribe((loading, data, err) => ...);
// update a post by replacing the old value with the new
model.on('post', 'update', (state: Post, event: PostEvent) => event);

// the like event increments the like counter on the post
model.on('post', 'like', (state: Post) => {
	state.likes++;
	return state;
});

// the add comment event adds a new comment to the post
model.on('comments', 'add', (state: Post, event: CommentEvent) => {
	state.comments.push(event);
	return state;
});
let postEvents = new models.EventStream<PostEvent>({
	name: 'post',
	channel: 'posts',
	filter: 'id == `123`',
});

let commentEvents = new models.EventStream<CommentEvent>({
	name: 'comment',
	channel: 'comments',
	filter: 'post_id == `123`',
	orderingKey: 'id',
});
// define the Post model as required by the client application
interface Post {
	id: number,
	title: string,
	comments: Array<string>,
}

// create a live, observable data model for post 123
let model = new models.Model<Post>({
    	name: 'posts',
    	sync: getPost(123),
streams: [postEvents, commentEvents],
});

"""
<main className="main-container">
      <section className="image-section">
        <div className="image-container">
          <img
            src={WelcomeImageUserOnBoarding}
            alt="Welcome User On Boarding Image"
            sizes=""
          />
          <div className="image-overlay">
            <h2 className="image-title">Welcome</h2>
            <p className="image-content">The DIFC Courts is an independent common law judiciary based in the Dubai International Financial Centre (DIFC) with jurisdiction governing civil and commercial disputes.</p>
          </div>
        </div>
      </section>
      <section className="registration-section">
        <Typography className="question" sx={{ mt: 2, mb: 1 }}>
          Register Now
        </Typography>
        <Typography className="question-helper">
          Enter Below Details to Continue
        </Typography>
        <div className="button-wrapper">
          <button
            type="button"
          >
            <img
              src={FingerPrintIcon}
              className="finger-print-icon"
              alt="Finger Print Icon"
              sizes=""
            />
            Signup with UAE Pass

          </button>
        </div>
        <Typography
          className="question-helper sub-text"
          sx={{ mt: 3 }}
        >
          Or Enter Details Below
        </Typography>
        <form className="form mt-3">
          <div className="row form-row mb-4">
            {/* FirstName Col */}
            <div className="col-md-6">
              <label
                htmlFor="firstname"
                className="form-label w-100 firstname-label"
              >
                FirstName*
              </label>
              <input
                type="text"
                className="form-control firstname-input"
                id="firstname"
                placeholder="John"
              />
            </div>
            {/* LastName Col */}
            <div className="col-md-6">
              <label
                htmlFor="lastname"
                className="form-label w-100 lastname-label"
              >
                LastName*
              </label>
              <input
                type="text"
                className="form-control lastname-input"
                id="lastname"
                placeholder="Doe"
              />
            </div>
          </div>
          <div className="row form-row mb-4">
            {/* gender selection buttons */}
            <div className="col-md-6">
              <label
                htmlFor="gender"
                className="form-label w-100 gender-label"
              >
                Gender
              </label>
              <OptionButtons />
            </div>
            {/* Date of Birth Col */}
            <div className="col-md-6">
              <label
                htmlFor="dob"
                className="form-label w-100 dob-label"
              >
                Date of Birth*
              </label>
              <DatePicker
                onChange={handleDatePicker}
                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"
              />
            </div>
          </div>
          <div className="row form-row mb-2">
            {/* Email Col */}
            <div className="col-md-6">
              <label
                htmlFor="email"
                className="form-label w-100 email-label"
              >
                Primary Email*
              </label>
              <input
                type="email"
                className="form-control email-input"
                id="email"
                placeholder="abc@babc.com"
              />
            </div>
            {/* Mobile Number Col */}
            <div className="col-md-6">
              <label
                htmlFor="mobile"
                className="form-label w-100 mobile-label"
              >
                Primary Mobile Number*
              </label>
              <input
                type="text"
                className="form-control mobile-input"
                id="mobile"
                placeholder="+971 50 123 4567"
              />
            </div>
          </div>
          <div className="row form-row mb-4">
            {/* Secondary Email Col */}
            <div className="col-md-6">
              <div className="secondary-email">
                <span>
                  Add Secondary Email
                </span>
                {/* increase the size of below AiOutlinePlusCircle icon */}
                <AiOutlinePlusCircle
                  className="secondary-email-icon"
                  // increase the size
                  size={30}
                />
              </div>
            </div>
            {/* Secondary Mobile Number Col */}
            <div className="col-md-6">
              <div className="secondary-mobile">
                <span>
                  Add Secondary Mobile
                </span>
                <AiOutlinePlusCircle
                  className="secondary-mobile-icon"
                  // increase the size
                  size={30}
                />
              </div>
            </div>
          </div>

          {/* Select Services from dropdown list */}
          <div className="row form-row mb-4">
            <div className="col-md-12">
              <label
                htmlFor="services"
                className="form-label w-100 services-label"
              >
                How did you know about this service?
              </label>
              {/* add autocomplete to select */}
              <Autocomplete
                disablePortal
                id="combo-box-demo"
                options={services}
                isOptionEqualToValue={(option, value) => option.label === value.label}
                renderInput={(params) => (
                  <TextField
                    {...params}
                    placeholder="Social Media - LinkedIn / Twitter / Instagram"
                    className="services-input"
                  />
                )}
              />
            </div>
          </div>

          {/* add new row */}
          <div className="row form-row mb-4">
            <div className="col-md-4">
              {/* add a next step button that follows default styles */}
              <button
                type="button"
                className="next-step-button"
              >
                Next
              </button>
            </div>
          </div>

          {/* add new row below */}
          <div className="row form-row mb-4">
            <div className="col-md-6">
              {/* add a text 'Already have an account? Login ' */}
              <span className="already-have-account">
                Already have an account?
              </span>
              {/* wrap login by Link component */}
              <Link
                to="/accounts/login"
                className="login-link"
              >
                Login
              </Link>

            </div>
          </div>

        </form>
      </section>
    </main>
"""

SASS
--------
"""
/* stylelint-disable */ 
.main-container {
    display: flex;
    width: 100%;
    justify-content: center;
    margin-top: 112px;
    background: #FFFFFF;
    border-radius: 20px;
}

.image-section {
    position: relative;
    flex: 1;
  }
  
  .image-section img {
    width: 100%; /* Set the desired width */
    height: auto; /* Maintain aspect ratio */
  }

  .registration-section {
    flex: 1;
    padding: 20px;
    margin: 30px;
    box-sizing: border-box; 
    overflow: hidden; 
  }
  
  .image-container {
    position: relative;
    display: inline-block;
  }
  
  .image-overlay {
    position: absolute;
    bottom: 0;
    left: 0;
    padding: 20px;
    margin-bottom: 130px;
  }
  
  .image-title {
    font-family: 'Basis Grotesque Arabic Pro';
    font-style: normal;
    font-weight: 700;
    font-size: 70px;
    line-height: 64px;
    letter-spacing: -0.04em;
    text-transform: capitalize;
    color: #FFFFFF;
  }
  
  .image-content {
    color: #FFFFFF;
    text-align: left;
    font-family: 'Basis Grotesque Arabic Pro';
    font-style: normal;
    font-weight: 500;
    font-size: 16px;
    line-height: 19px;
  }
  
  .question {
    font-family: "Basis Grotesque Arabic Pro" !important;
    font-style: normal !important;
    font-weight: 500 !important;
    font-size: 40px !important;
    line-height: 45px !important;
    letter-spacing: -0.04em !important;
    color: #1b202d !important;
  }
  
.question-helper {
    font-family: "Basis Grotesque Arabic Pro" !important;
    font-style: normal !important;
    font-weight: 300 !important;
    font-size: 14px !important;
    line-height: 18px !important;
    color: #1b202d !important;
}

.button-wrapper {
    margin-top: 40px;
  }
  
  .button-wrapper button {
    width: 100%;
    background: #000000;
    border-radius: 5px;
    font-family: 'Inter';
    font-style: normal;
    font-weight: 600;
    font-size: 14px;
    line-height: 17px;
    color: #F5F5F5;
    padding: 16px 50px;
  }

  .finger-print-icon {
    margin-right: 14px;
  }
  
  .firstname-label,
  .lastname-label,
  .gender-label,
  .email-label,
  .mobile-label,
  .services-label
  {
    font-family: 'Basis Grotesque Arabic Pro';
    font-style: 'normal';
    font-weight: 500;
    font-size: 0.75rem;
    line-height: 18px;
    color: #1b202d;
    margin-top: 0px !important;
  }

  .firstname-input,
  .lastname-input,
  .email-input,
  .mobile-input,
  .services-input
    {
    font-family: 'Basis Grotesque Arabic Pro' !important;
    font-style: 'normal' !important;
    font-weight: 500 !important;
    font-size: 0.75rem !important;
    line-height: 18px !important;
    color: #1b202d !important;
    height: 2.5rem !important;
  }

  .date-picker-field .date-picker-input {
    font-family: 'Basis Grotesque Arabic Pro';
    font-style: normal;
    font-weight: 500;
    font-size: 0.75rem;
    line-height: 18px;
  }

  // right align secondary-email and secondary-mobile
  .secondary-email,
  .secondary-mobile {
    text-align: right;
  }

  // add left spacing between secondary-email and secondary-email-icon
  .secondary-email-icon {
    margin-left: 10px;
  }

  // add left spacing between secondary-mobile and secondary-mobile-icon
  .secondary-mobile-icon {
    margin-left: 10px;
  }

  // add background: #023979;
// border-radius: 10px; to next-step-button
.next-step-button {
  background: #023979;
  border-radius: 10px;
  font-family: 'Inter';
  font-style: normal;
  font-weight: 600;
  font-size: 14px;
  line-height: 17px;
  color: #F5F5F5;
  padding: 16px 50px;
  border: none;
}

// add below style to already-have-account
.already-have-account {
  font-family: 'Basis Grotesque Arabic Pro';
  font-style: normal;
  font-weight: 500;
  font-size: 16px;
  line-height: 16px;
  color: #494A53;
}

// add below style to login-text
.login-link {
  font-family: 'Basis Grotesque Arabic Pro';
  font-style: normal;
  font-weight: 500;
  font-size: 16px;
  line-height: 16px;
  color: #1B202D;
  margin-left: 5px;
  text-decoration: underline;
  text-underline-offset: 4px;
}

"""


You are a CSS expert.

Client wanrs to Auto Update the WelcomeImageUserOnBoarding image height when main container height increments. image height should be in sync
with the height change of main container div element.
So when main container height updates image height also auto update with same. Thus it wont leave any spacing at bottom.
I have given the jsx and sass file for your reference.
If you have any questions you can ask.


Solutions:

To achieve the desired effect of the `WelcomeImageUserOnBoarding` image height being in sync with the height change of the `main-container` div element, you can use CSS to make the image responsive and adjust its height accordingly.

Here's an updated version of the SASS code with modifications to make the image height responsive:

```sass
.main-container {
  display: flex;
  width: 100%;
  justify-content: center;
  margin-top: 112px;
  background: #FFFFFF;
  border-radius: 20px;
  position: relative; /* Add position relative to main-container */
}

.image-section {
  position: relative;
  flex: 1;
}

.image-section img {
  width: 100%;
  height: 100%; /* Set the image height to 100% of the parent container */
  object-fit: cover; /* Maintain aspect ratio and cover the entire container */
}

.registration-section {
  flex: 1;
  padding: 20px;
  margin: 30px;
  box-sizing: border-box;
  overflow: hidden;
}

.image-container {
  position: relative;
  display: inline-block;
  width: 100%; /* Set the image container width to 100% */
  height: 100%; /* Set the image container height to 100% */
}

.image-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  padding: 20px;
  margin-bottom: 130px;
}

/* Rest of the styles remain the same */
```

In this code, I've added `position: relative` to the `main-container` to establish a positioning context for its child elements. Then, I've modified the styles for the `image-section`, `image-container`, and `image-section img` to make the image responsive. By setting the image height to `100%` of the parent container and using `object-fit: cover`, the image will automatically adjust its height to match the height of the `main-container`.

Please ensure you include this updated SASS code in your project and recompile it to generate the CSS styles.
  <Link
                to="/accounts/login"
                className="login-link"
              >
                Login
              </Link>


.login-link {
  font-family: 'Basis Grotesque Arabic Pro';
  font-style: normal;
  font-weight: 500;
  font-size: 16px;
  line-height: 16px;
  /* identical to box height */
  color: #1B202D;
  // assign left margin to login-text
  margin-left: 5px;
  // add an underline to login-link
  text-decoration: underline;
}

You are a front end developer
I have applied underline to login link. but letter 'g'  of login text has no underline. i dont how to resolve this. You can apply any styling to put the underline for whole text.

Solution:

It sounds like the g in the word "login" is not being underlined along with the rest of the text, which can happen if the text is not aligned properly with the underline.

To fix this issue, you can try adding the text-underline-offset property to the .login-link class, with a value of 3px or 4px. This property will adjust the position of the underline so that it lines up correctly with the text.



.login-link {
  font-family: 'Basis Grotesque Arabic Pro';
  font-style: normal;
  font-weight: 500;
  font-size: 16px;
  line-height: 16px;
  color: #1B202D;
  margin-left: 5px;
  text-decoration: underline;
  text-underline-offset: 3px; /* Adjust value as needed */
}


With this change, the underline should now cover the entire text, including the g. You can adjust the value of text-underline-offset as needed to ensure that the underline lines up properly with the text.
JSX
"""
<Modal show={showModal} onHide={handleModalClose} dialogClassName="modal-dialog-centered" size="lg">
      <Modal.Header closeButton>
        <Modal.Title className="modal-title">Choose Method</Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <div>
          <div className="modal-choose-method-subtitle mb-3">
            List your Substitute Beneficiaries below and click on Add Substitute to add them to your List
          </div>
        </div>
        <div className="d-flex flex-row">
          <div
            className={`card-container-draft-will d-flex flex-column align-items-center ${activeCard === 'draftWill' ? 'active' : ''}`}
            onClick={() => handleCardClick('draftWill')}
          >
            {activeCard === 'draftWill' && (
            <div
              className="check-icon"
            >
              <img src={FillCheckRoundIcon} alt="Fill Check Icon" />
            </div>
            )}
            <div className="choose-method-draft-will-icon-container" style={{ marginBottom: '20px', marginTop: '20px' }}>
              <img src={DraftWillIcon} alt="Will Copy Upload Icon" />
            </div>
            <div className="text-center choose-method-draft-will-title" style={{ marginTop: '10px', marginBottom: '10px' }}>
              Draft Will Using the System
            </div>
            <div className="text-center choose-method-draft-will-desc" style={{ marginTop: '10px', marginBottom: '10px' }}>
              It is a long established fact that a reader will be distracted by the readable content.
            </div>
          </div>
          <div
            className={`card-container-will-copy-upload d-flex flex-column align-items-center ${activeCard === 'willCopyUpload' ? 'active' : ''}`}
            style={{ width: '50%', marginRight: '10px', position: 'relative' }}
            onClick={() => handleCardClick('willCopyUpload')}
          >
            {activeCard === 'willCopyUpload' && (
            <div
              className="check-icon"
              style={{
                position: 'absolute', top: '10px', left: '10px', margin: '10px',
              }}
            >
              <img src={FillCheckRoundIcon} alt="Fill Check Icon" />
            </div>
            )}
            <div className="choose-method-will-upload-icon-container">
              <img src={WillCopyUploadIcon} alt="Will Copy Upload Icon" />
            </div>
            <div className="text-center choose-method-will-upload-title" style={{ marginTop: '10px', marginBottom: '10px' }}>
              Upload the Copy of Will
            </div>
            <div className="text-center choose-method-will-upload-desc" style={{ marginTop: '10px', marginBottom: '10px' }}>
              It is a long established fact that a reader will be distracted by the readable content.
            </div>
          </div>
        </div>
      </Modal.Body>
      <Modal.Footer className="justify-content-center">
        {
          activeCard && isAnyWillCardSelected && (
            <Link
              to={`/wills/${selectedWillCard.willTypeName.split(' ').join('-')}/${selectedWillCard.willTypeGUID}`}
              state={selectedWillCard.willTypeName}
            >
              <Button
                variant="primary"
              >
                Continue
              </Button>
            </Link>
          )
        }
      </Modal.Footer>
    </Modal>
    
   """
   
   css
   ------
   """
   /* stylelint-disable */ 

.card-container-draft-will.active, .card-container-will-copy-upload.active  {
    background-color: #E4FDFF;
    border-radius: 20px;
    padding: 28px;
}
.card-container-draft-will {
    width: 50%;
    margin-right: 10px;
    position: relative;
}
.modal-choose-method-subtitle {
    font-family: 'Basis Grotesque Arabic Pro';
    font-style: normal;
    font-weight: 300;
    font-size: 0.875rem;
    line-height: 18px;
    color: #1B202D;
}

.modal-title {
    font-family: 'Basis Grotesque Arabic Pro';
    font-style: normal;
    font-weight: 500;
    font-size: 2.5rem;
    line-height: 45px;
    letter-spacing: -0.04em;
    color: #1B202D;
}

.btn-close {
    color: #494A53 !important;
    font-size: 10px !important;
    position: absolute !important;
    top: 20px !important;
    right: 20px !important;
}

.btn-close:before {
    background-color: #f1f1f1 !important;
    border-radius: 50px !important;
  }

  .check-icon {
    position: absolute;
    top: 10px;
    left: 10px;
    margin: 10px;
  }
  
  .choose-method-draft-will-icon-container {
    margin-bottom: 20px;
    margin-top: 20px;
  }
  
  .choose-method-will-upload-title {
    margin-top: 10px;
    margin-bottom: 10px;
    text-align: center;
  }
  """
  
  You are expert in css to sass conversion.
  Client want the above css to be converted in to sass format.
  it should follow sass styling conventions.
  you have to convert it as per the requirement of client.
  for your reference, i have given the respective JSX content for the above styles.
  you can check the css selectors and make sure current styles wont break.
  Return the converted sass 
const firstResolvedPromiseResult = await Promise.race([
  this.page.waitForSelector('div#abc'),
  this.page.waitForSelector('div#efg'),
]);
import { useDispatch, useSelector } from 'react-redux';
import fetchWillsList, { willsListSelector } from '@redux/slices/wills-list';


  const { results } = useSelector(willsListSelector);

  const dispatch = useDispatch();

  React.useEffect(() => {
    dispatch<any>(fetchWillsList());
  }, []);


  const handleCardClick = (cardName: string) => {
    let willTypeName: string = '';
    let willTypeGUID: string = '';
    setActiveCard(cardName);
    results.forEach((will: any) => {
      if (cardName === 'draftWill' && will.willTypeName === 'Templated Full Will') {
        willTypeName = will.willTypeName;
        willTypeGUID = will.willTypeGUID;
      } else if (cardName === 'willCopyUpload' && will.willTypeName === 'Full Will') {
        willTypeName = will.willTypeName;
        willTypeGUID = will.willTypeGUID;
      }
    });

    setSelectedWillCard({ willTypeName, willTypeGUID });
  };
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");

mongoose.connect("mongodb://127.0.0.1:27017/datasbase").then(() =>{
    console.log("Mongodb Connected");
}).catch((err) =>{
    console.log(err);
});

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

const productSchema = new mongoose.Schema({
    _id: Number,
    name: String,
    price: Number
});

const productModel = new mongoose.model("data", productSchema);

//product create
app.post("/api/v1/product/new", async (req, res) =>{
    const productCreate = await productModel.create(req.body);


    res.status(201).json({
        success: true,
        productCreate
    });
});

//products find
app.get("/api/v1/products", async (req, res) =>{
    const productFInd = await productModel.find();


    res.status(200).json({
        success: true,
        productFInd
    });
});


//product update
app.put("/api/v1/product/:id", async (req, res) =>{
    let productUpdate = await productModel.findById(req.params.id);

    if(!productUpdate){
        return res.status(500).json({
            success: false,
            message: "product not found"
        })
    }
    productUpdate = await productModel.findByIdAndUpdate(req.params.id, req.body, {new: true,
    useFindAndModify: false,
    runValidators: true
    });

        res.status(200).json({
            success: true,
            productUpdate
        });
});

//delete product

app.delete("/api/v1/product/:id", async(req, res) =>{
    let productDelete = await productModel.findById(req.params.id);

    if(!productDelete){
        return res.status(500).json({
            success: false,
            message: "product not found"
        })
    }

    await productModel.findByIdAndDelete(req.params.id);

    
    res.status(200).json({
        success: true,
        message: "product deleted"
    });
});



app.listen(4500, () =>{
    console.log("Server is working");
});
document.addEventListener('DOMContentLoaded', function() {
    var button = document.getElementById('myButton');
    button.addEventListener('click', function() {
        alert('¡Haz hecho clic en el botón!');
    });
});
In react-router-dom v6 useHistory() is replaced by useNavigate()

import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
navigate('/home');


"""
 <Link to="/wills/quick-booking">
                    <span className="box-title">
                      Book Quick Appointment
                    </span>
                  </Link>
  """                
                  
You are a experienced react developer.
  
currently when user clicks on above link, moves to `/wills/quick-booking` route. 
what you need to do is to first show a bootstrap modal popup before moving to that route. 
so you have to show a modal popup before moving to above quick booking page.
you have to also create a modal pop using boostrap. 

modal contents were given below:

Heading or title
-------------------
Confirm


Content or Subcontent 
--------------------
Testators may enter minimum information to secure an appointment. 
Full details must be completed 72 hours prior to the booking date to avoid appointment cancellation. 
Registered Will Draftsmen are requested to refrain from using the quick booking option

Two Buttons
---------
Continue Button - When user clicks on this button, it moves to /wills/quick-booking to open quick booing page.
Cancel Button - Close the modal popup and not redirected to above route.


No need to apply any styling as of now. We can do it later on. You have to use boostrap modal.
const mongoose = require("mongoose");

mongoose.connect("mongodb://127.0.0.1:27017/base").then(() =>{
    console.log("server connectet to mongodb");
}).catch((err) =>{
    console.log(err);
});

const student = new mongoose.Schema({
    name: String,
    class: Number,
    study: Boolean
});

const Student = new mongoose.model("data", student);

const adder = async () =>{
    const detail = await Student.create({
        name: "Alex",
        class: 5,
        study: true
    });

};

adder();
Sure! I can help you with that. Here's an example of how you can create a Bootstrap modal in React and use it to show a confirmation popup before redirecting to the `/wills/quick-booking` route:

First, make sure you have the Bootstrap CSS and JS files included in your project.

Next, create a new React component called `ConfirmationModal`:

```jsx
import React from 'react';
import { Modal, Button } from 'react-bootstrap';

const ConfirmationModal = ({ show, handleClose, handleContinue }) => {
  return (
    <Modal show={show} onHide={handleClose}>
      <Modal.Header closeButton>
        <Modal.Title>Confirm</Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <p>Testators may enter minimum information to secure an appointment.</p>
        <p>
          Full details must be completed 72 hours prior to the booking date to avoid appointment cancellation.
        </p>
        <p>Registered Will Draftsmen are requested to refrain from using the quick booking option.</p>
      </Modal.Body>
      <Modal.Footer>
        <Button variant="secondary" onClick={handleClose}>
          Cancel
        </Button>
        <Button variant="primary" onClick={handleContinue}>
          Continue
        </Button>
      </Modal.Footer>
    </Modal>
  );
};

export default ConfirmationModal;
```

In your main component where the link is located, you can use the `ConfirmationModal` component and handle its state:

```jsx
import React, { useState } from 'react';
import { Link, useHistory } from 'react-router-dom';
import ConfirmationModal from './ConfirmationModal';

const MainComponent = () => {
  const [showModal, setShowModal] = useState(false);
  const history = useHistory();

  const handleShowModal = () => {
    setShowModal(true);
  };

  const handleCloseModal = () => {
    setShowModal(false);
  };

  const handleContinue = () => {
    handleCloseModal();
    history.push('/wills/quick-booking');
  };

  return (
    <div>
      <Link to="/wills/quick-booking" onClick={handleShowModal}>
        <span className="box-title">Book Quick Appointment</span>
      </Link>
      <ConfirmationModal
        show={showModal}
        handleClose={handleCloseModal}
        handleContinue={handleContinue}
      />
    </div>
  );
};

export default MainComponent;
```

In the above example, the `MainComponent` renders a link with the class name `box-title`, and when clicked, it calls the `handleShowModal` function to show the modal popup. The modal is conditionally rendered based on the `showModal` state.

The `ConfirmationModal` component receives three props: `show` (to determine whether the modal should be displayed), `handleClose` (to close the modal), and `handleContinue` (to handle the continue button click and redirect to the desired route).

When the user clicks "Continue" in the modal, the `handleContinue` function is called, which first closes the modal and then uses the `useHistory` hook from React Router to navigate to the `/wills/quick-booking` route.

Remember to adjust the code and import the necessary dependencies based on your project structure and setup.

I hope this helps! Let me know if you have any further questions.
you have to suggest me a branch name in which i implement UI of confirm modal pop up. branch name should follow convention.


//Using the new ES6 Syntax

    console.log(["a", "b", "c", "d", "e", "f", "g"].filter(el => !["b", "c", "g"].includes(el)));

    // OR

    // Main array
    let myArray = ["a", "b", "c", "d", "e", "f", "g"];

    // Array to remove
    const toRemove = ["b", "c", "g"];

    const diff = () => (myArray = myArray.filter((el) => !toRemove.includes(el)));
  console.log(diff()); // [ 'a', 'd', 'e', 'f' ]

    // OR

    const diff2 = () => {
      return myArray = myArray.filter((el) => !toRemove.includes(el));
    };
    console.log(diff2()); // [ 'a', 'd', 'e', 'f' ]
function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

$(window).scroll(function () {
    $('.textbox').each(function () {
        if (isScrolledIntoView(this) === true) {
            $(this).addClass('visible');
        }
    });

});
async function successA(){return 'A'}
async function successB(){return 'B'}
async function failC(){throw 'error c'}
async function failD(){throw 'error d'}

const results = await Promise.allSettled([
    successA(),
    successB(),
    failC(),
    failD()
])

const successfullResults = results
    .filter(result => result.status === "fulfilled")
    .map(result => result.value)

console.log(successfullResults)

results
    .filter(result => result.status === "rejected")
    .forEach(error => console.log(error.reason))
  <Link to="/wills/quick-booking">
                    <span className="box-title">
                      Book Quick Appointment
                    </span>
                  </Link>
                  
                  
                  you are an expert in react development.
                  i have added a link component and set the route. 
                  but when i clikc "Book Quick Appointment". it throws error message like  
                  "No route matches URL \"/wills/quick-booking\""
                  its status is 404 not found.
                  Help me to find and fix solution for the problem.
                  
                  

                  Solutions:
                  
                  1. Make sure that you have a Route component in your app that matches the /wills/quick-booking path. You can do this by adding the following code to your app:

<Route exact path="/wills/quick-booking">
  {/* Insert the component for the quick booking page here */}
</Route>

check routes file in projct directory and update the path.







                  
<!DOCTYPE html>
<html>
<body>

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

<p id="demo">My name is Lillian.</p>

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

</body>
</html> 
"""
Problem Description
Given a non-empty array of digits representing a non-negative integer, plus one to the integer and return the same list.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Input format
You will be given a list of integers.

Output format
Return a list of integer +1.

Sample Input 1
1 2 3

Sample Output 1
1 2 4

Explanation 1
The array represents the integer 123.

Sample Input 2
4 3 2 1

Sample Output 2
4 3 2 2
"""

Consider you are an experienced python developer.
Help me to solve the above problem and integrate the code into below code.
Code should follow python naming conventions
Return the updated code.

```py
def plusOne(digits):
if __name__ == '__main__':
    digits = input().split()
    digits = [int(i) for i in digits]
    result = plusOne(digits)
    for i in result:
        print(i,end=' ')
```
<!DOCTYPE html>
<html>
<body>

<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>

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

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

<button onclick="document.getElementById('myImage').src='pic_lightoff.gif'">Turn off light</button>

</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Express js</title>
</head>
<body>
    <form action="/data" method="post">
        <input type="text" name="name"  >
        <input type="email" name="email"   >
        <input type="submit" value="submit" >
    </form>
</body>
</html>
const expres = require("express");
const app = expres();
const path = require("path");
const bodyParser = require("body-parser");

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

app.get("/",(req, res) =>{
    res.sendFile(path.join(__dirname + "/index.html"));
})

app.post("/data", (req, res) =>{
    const userName = req.body.name;
    const email = req.body.email;
    const sum = userName+ " " + email;
    res.send(sum);
    
});

const PORT = 4000;

app.listen(PORT, () =>{
    console.log(`Server is working on ${PORT}`)
});
const express = require("express");
const app = express();
const path = require("path");

app.get("/", (req, res) =>{
    res.sendFile(path.join(__dirname +  "/index.html"))
});

const PORT = 4000;

app.listen(PORT, () =>{
    console.log(`Server is working on ${PORT}`)
});
first npm init
second npm i express nodemon


const http = require("http");
const fs = require("fs");

const home = fs.readFileSync("./index.html", "utf-8");
const server = http.createServer((req, res) =>{
    if(req.url === "/"){
     return   res.end(home);
    }
   
});

const PORT = 4000;
const hostname = "localhost";

server.listen(PORT, hostname, () =>{
    console.log("Server is working");
});
Code 1:
"""
# TODO: Implement this method
from typing import List


def findElement(n: int, arr: List[int], x: int) -> int:

# NOTE: Please do not modify this function
def main():
    n = int(input().strip())
    arr = list(map(int, input().strip().split(' ')))
    x = int(input().strip())

    xIndex = findElement(n, arr, x)
    print(xIndex)

if __name__=="__main__":
    main()
"""

Code 2:
"""
def find_index(n,arr,x):
    for i in range(n):
        if arr[i]==x:
            return i
    return -1
"""


Consider you are a python devekoper.
Help me to integrate the Code 2 into Code 1.
Return the updated version of code. 
"""
 <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>`);
}
"""
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')

})
/* NOTIFICATION ___________________________________________________________________________________ */

var notification_number = 0;

function noti(title, text, color, bgcolor) {
    var not = document.createElement("div");
    not.style = "transition-duration:0.5s;width:300px;border-radius:8px;padding:10px;position:fixed;z-index:999;" +
        "bottom:20px;right:20px;";
    if (color) { not.style += "color:" + color + ";" }
    if (bgcolor) { not.style += "background-color:" + bgcolor + ";" }
    not.innerHTML =
        "<span id='notification_" + notification_number + "' class='closeButton' style='position:absolute;top:2px;right:10px;font-size:30px;cursor:pointer;'>&times;</span>" +
        "<h2 style='margin:0px;'>" +
        title + "</h3><hr style='border-color:" +
        color + ";'><p style='margin-top:15px;margin-bottom:10px;font-size:1.2em;'>" +
        text + "</p>";
    not.classList.add("notification");
    not.id = "notification_" + notification_number + "_div";
    notification_number++;
    document.body.appendChild(not);
    var closeButtons = document.querySelectorAll(".closeButton");
    closeButtons.forEach(element => {
        element.addEventListener("click", function () {
            var delNot = document.getElementById(element.id + "_div");
            delNot.style.opacity = "0";
            setTimeout(() => {
                delNot.remove();
            }, 1000);
        });
    });
    setTimeout(() => {
        if (not) {
            not.style.opacity = "0";
        }
    }, 5000);
    setTimeout(() => {
        if (not) {
            not.remove();
        }
    }, 6000);
}
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
    }
]
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>
NPM I SLUGIFY
NPM I NODEMON --save-dev   
npm i nodemon --global   <--globalurad amaxsovrebs
#HTML#
<lightning-layout-item size="6" >
                <lightning-input type="text" onchange={handleInput} maxlength="9" placeholder="Digite o CEP"> </lightning-input>
</lightning-layout-item>

<lightning-layout-item size="12" padding="horizontal-small">
                <lightning-input disabled="true" value={obj.logradouro} type="text" placeholder="Rua" data-id="form"> </lightning-input>
</lightning-layout-item>

<lightning-button class="btn" onclick={clearFields} label="Limpar" variant="brand"></lightning-button>

#JS#
clearFields() {
        this.template.querySelectorAll('lightning-input').forEach(element => {
            element.value = null;
        });

        // you can also reset one by one by id
        // this.template.querySelector('lightning-input[data-id="form"]').value = null;
}
function disemvowel(str) {
    const vowel = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
    let result = "";
  
  for (let i=0; i<str.length; i++)
    
    if (!vowel.includes (str[i])) {
      result += str[i]
    }
    return result;  
}
 var m_names = new Array("JAN", "FEB", "MAR",
     "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC");
 var d = new Date();
 d.setDate(d.getDate() + 70);
 var curr_date = d.getDate();
 var curr_month = d.getMonth();
 var curr_year = d.getFullYear();
 var current = curr_date + "-" + m_names[curr_month] + "-" + curr_year;

 console.log(current)
// Find process
lsof -Pi :3000

// Kill by PID 
kill 14704


// If it doesn't work using SIGTERM will force it (The SIGTERM signal is a generic signal used to cause program termination. Unlike SIGKILL , this signal can be blocked, handled, and ignored.)
kill -9 14704

function findNeedle(haystack) {
  const indexOfNeedle = haystack.indexOf("needle");
 return haystack.includes("needle"), `found the needle at position ${indexOfNeedle}`;
}
function countPositivesSumNegatives(input) {
  if (!input || !input.length) return []
  let positives = 0
  let negSum = 0
  for(const num of input){
    if(num > 0)positives++
    else negSum+=num
  }
  return [positives, negSum]
}
//OR 
function countPositivesSumNegatives(input) {
  if (!input || !input.length)
    return []
  let countPositive = 0
  let sumNegative = 0
  for (let i=0; i<input.length; i++)
    if(input[i] > 0) {
      countPositive++; 
    }
  else if(input[i] < 0) {
    sumNegative += input[i]};
return [countPositive, sumNegative]
}
function makeUpperCase(str) {
 return str.toUpperCase()
  
}
function abbrevName(name){
  const nameArr = name.split(' ')
  return `${nameArr[0][0].toUpperCase()}.${nameArr[1][0].toUpperCase()}`
}
const zeroFuel = (distanceToPump, mpg, fuelLeft) => {
  return fuelLeft * mpg >= distanceToPump

};
// Write a function "greet" that returns "hello world!"
function greet() {
  return "hello world!"
}
function boolToWord( bool ){
 if (bool === true) return "Yes"
  else return "No"
}
function evenOrOdd(number) {
  if (number%2===0) return "Even"
  else return "Odd"
}
const rps = (p1, p2) => {

if (p1 ==="rock" && p2 === "rock") return "Draw!"
if (p1 ==="rock" && p2 === "paper") return "Player 2 won!"
if (p1 ==="rock" && p2 === "scissors") return "Player 1 won!"
  
if (p1 ==="paper" && p2 === "rock") return "Player 1 won!"
if (p1 ==="paper" && p2 === "paper") return "Draw!"
if (p1 ==="paper" && p2 === "scissors") return "Player 2 won!" 
 
if (p1 ==="scissors" && p2 === "rock") return "Player 2 won!"
if (p1 ==="scissors" && p2 === "paper") return "Player 1 won!" 
if (p1 ==="scissors" && p2 === "scissors") return "Draw!"
  
};
function greet(name){
  return `Hello, ${name} how are you doing today?`
}
function simpleMultiplication(number) {
   if (number%2 === 0) return number*8
  else return number *9
}
function squareSum(numbers){
  let sum = 0
  for (let i=0; i<numbers.length; i++) {
   sum += numbers[i]**2 
  }
return sum
}
function numberToString(num) {
return ""+num
}
function booleanToString(b){
if(b) { return "true"}
  else{return "false"}
}
function removeChar(str){
return str.substring(1, str.length -1)
};
function highAndLow(numbers){
  numbers = numbers.split(" ");
 return `${Math.max(...numbers)} ${Math.min(...numbers)}`
}
$(window).click(function() {
  //Hide the menus if visible
});

$('#menucontainer').click(function(event){
  event.stopPropagation();
});
const Arithmetic = require("../arithmetic");
//tests arithmetic class
describe("Arithmetic", () => {
  //organizational tool containing tests
  describe("Initialization", () => {
    it("should set 'number' when created", () => {
      // Arrange
      const num = 108;
      // Act
      const obj = new Arithmetic(num);
      // Assert
      expect(obj.number).toEqual(num);
    });
  })
           })
           
const rockets = [
    { country:'Russia', launches:32 },
    { country:'US', launches:23 },
    { country:'China', launches:16 },
    { country:'Europe(ESA)', launches:7 },
    { country:'India', launches:4 },
    { country:'Japan', launches:3 }
];

const launchOptimistic = rockets.map(function(elem) {
  return {
    country: elem.country,
    launches: elem.launches+10,
  } 
});

console.log(launchOptimistic);
npm run pre-build && npm run build_logic && npm run post_build && npm run exit
Use && (double ampersand) for sequential execution.
Use & (single ampersand) for parallel execution.
const people = [
  { name: "Kyle", age: 26 },
  { name: "John", age: 31 },
  { name: "Sally", age: 42 },
  { name: "Jill", age: 42 },
];
// reduce people array down to an individual result which groups by age
const result = people.reduce((groupedPeople, person) => {
    const age = person.age;
    // if theres no one with this age, create array
    if (groupedPeople[age] == null) groupedPeople[age] = [];
    // add person to array by age
    groupedPeople[age].push(person);
    // return all people grouped 
    return groupedPeople;
}, {})

console.log(result)
<!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>
</head>

<body>
    <h1>select an Element By ID</h1>
    <ul>
        <li>List 1</li>
        <li id="second">List 2</li>
        <li>List 3</li>
        <li>List 4</li>
        <li>List 5</li>
    </ul>
    <script>
        let elm = document.getElementById("second");
        console.log(elm);   // this stores an element as a object, it returns <li id="second">List 2</li>
        console.log(elm.innerHTML);        // this return the value store by an object  "List 2" // this method is used to get value
        elm.innerHTML = "<p>List Modified</p>";       // this method is used to set the value of an object
        // console.log("This value is After Modifying : " + elm.innerHTML);
    </script>
</body>

</html>
<!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>
</head>

<body>
    <h1>Select an Element By Class Name</h1>
    <ol>
        <li class="class para">List 1</li>
        <li class="class1">List 2</li>
        <li class="class">List 3</li>
        <li class="class1">List 4</li>
        <li class="class">List 5</li>
    </ol>
    <script>
        let elm1=document.getElementsByClassName("class");
        // Here in case of class there is a collection created of objects
        console.log(elm1);   // This return a collection
        console.log(elm1.length)     // return no. of elements in object
        // to access each elent we use loop
        for(let i=0; i<elm1.length;i++){
            // console.log(elm[i]);    // return object details 
            console.log(elm1[i].innerHTML);      // returns value of an object
            elm1[i].innerHTML="Upadted element with 1 class contains"
        }
        let elm=document.getElementsByClassName("class para");
        // Here in case of class there is a collection created of objects
        console.log(elm);   // This return a collection
        console.log(elm.length)     // return no. of elements in object
        // to access each elent we use loop
        for(let i=0; i<elm.length;i++){
            // console.log(elm[i]);    // return object details 
            console.log(elm[i].innerHTML);      // returns value of an object
            elm[i].innerHTML="Upadted elements with 2 class contains"
            console.log(elm[i].innerHTML);
        
            // Note : if same properties is used in different scripts then last one is executed
        }
    </script>
</body>

</html>
function sayHello() {
  console.log("Hello World");
}

sayHello();

function add(num1, num2) {
  console.log(num1 + num2);
}

add(5, 10);

function substract(num1, num2) {
  return num1 - num2;

  console.log("After the return"); // it won't be logged because it's after return
}

const result = substract(10, 2);

console.log(result, substract(20, 5));
function getDirection() {
  
  // DECLARE SHEET
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var mapSheet = ss.getSheetByName("MAP");
  
  var start = mapSheet.getRange('B1').getValue();
  var end = mapSheet.getRange('B2').getValue();
  
  var directions = Maps.newDirectionFinder()
    .setOrigin(start)
    .setDestination(end)
    .setMode(Maps.DirectionFinder.Mode.DRIVING)
    .getDirections();
  
  //Logger.log(directions.routes[0].legs[0].duration.text);

  //CLEAR QUESTION AND ANSWER
  mapSheet.getRange('A6:D500').clear();
  
  //NEXT ROW ON MAP SHEET
  var nextRow = mapSheet.getLastRow() + 1;

  for (var i = 0; i < directions.routes[0].legs.length; i++) 
  {
    var endAddress = directions.routes[0].legs[i].end_address;
    var startAddress = directions.routes[0].legs[i].start_address;
    var distance = directions.routes[0].legs[i].distance.text;
    var duration = directions.routes[0].legs[i].duration.text;
    
    mapSheet.getRange(nextRow,1).setValue(startAddress);
    mapSheet.getRange(nextRow,2).setValue(endAddress);
    mapSheet.getRange(nextRow,3).setValue(distance);
    mapSheet.getRange(nextRow,4).setValue(duration);
    
    nextRow++;

  }
}
Google Apps Script Code Used in Video Below:

function doGet(e) {
  Logger.log(JSON.stringify(e));
  Logger.log(e.parameter['message']);
  return HtmlService.createHtmlOutputFromFile('ExampleFile1');  
}

//function doGet(e) 
//{
//  Logger.log(JSON.stringify(e));
//  Logger.log(e.parameter['message']);
//  var htmlOutput =  HtmlService.createTemplateFromFile('ExampleFile2');
//  htmlOutput.message = e.parameter['message'];
//  return htmlOutput.evaluate();
//}

//function doGet(e) 
//{
//  Logger.log(JSON.stringify(e));
//  var htmlOutput =  HtmlService.createTemplateFromFile('ExampleFile3');
//  if(!e.parameter['username'])
//  {
//    htmlOutput.username = '';   
//  }
//  else
//  {
//    htmlOutput.username = 'Username is: ' + e.parameter['username'];
//  }
//  htmlOutput.url = getUrl();  
//  return htmlOutput.evaluate();
//}
//
//
//function getUrl() {
// var url = ScriptApp.getService().getUrl();
// return url;
//}
test('render h1 element', () => {
  render(<App />);

  screen.debug();

  expect(screen.getByText('Hello World')).toBeInTheDocument();
});
​let x = new Date();
document.write(x, "<br>");
let y = new Date("17 Feb 2023 13:40:59");
document.write(y);
let z = y.getDay();
document.write("<br>", "<br>");
let w = [
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Firday", "Saturday"
];
document.write("Date in Term of JS Execute : " + z, "<br>", "<br>");

// Using If Else Function
/*
if (z == 0) {
  document.write(w[0]);
} else if (z == 1) {
  document.write(w[1]);
} else if (z == 2) {
  document.write(w[2]);
} else if (z == 3) {
  document.write(w[3]);
} else if (z == 4) {
  document.write(w[4]);
} else if (z == 5) {
  document.write(w[5]);
} else {
  document.write(w[6]);
}
*/
// Using same with Switch Case
switch (z) {
  case 0:
    document.write(w[0]);
    break;
  case 1:
    document.write(w[1]);
    break;
  case 2:
    document.write(w[2]);
    break;
  case 3:
    document.write(w[3]);
    break;
  case 4:
    document.write(w[4]);
    break;
  case 5:
    document.write(w[5]);
    break;
  default:
    document.write(w[6]);
}
var autoPopulateLead = function(next) {
  this.populate('lead');
  next();
};

bandSchema.
  pre('findOne', autoPopulateLead).
  pre('find', autoPopulateLead);

var Band = mongoose.model('band', bandSchema, 'bands');
var autoPopulate = function(next) {
  this.populate('updated_by','name').populate('created_by','name');
  next();
};

ProjectSchema.pre('findOne', autoPopulate);
ProjectSchema.pre('find', autoPopulate);
let mu=document.getElementById("mu")
let res=document.getElementById("result")


mu.onclick=()=>{
let num1 = document.getElementById("firstNumber").value;
let num2 = document.getElementById("secondNumber").value;
document.getElementById("result").innerHTML = num1 * num2;
}
<!-- **************************HTML****************************** -->




 <!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>
</head>

<body >

    <form>
        1st Number : <input type="text" id="firstNumber" /><br>
        2nd Number: <input type="text" id="secondNumber" /><br>
        <input type="button" id="mu" Value="Multiply" />
        <input type="button" Value="Divide" />
        </form>
        <p>The Result is : <br>
        <span id = "result"></span>
        </p>





             <!--   This JS IMPORt  -->
    <script src="main.js" type="module"></script>
</body>

</html>
 
<!-- ******************************************************** -->




 <!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>
</head>

<body >

    <form>
        1st Number : <input type="text" id="firstNumber" /><br>
        2nd Number: <input type="text" id="secondNumber" /><br>
        <input type="button" onClick="multiplyBy()" Value="Multiply" />
        <input type="button" onClick="divideBy()" Value="Divide" />
        </form>
        <p>The Result is : <br>
        <span id = "result"></span>
        </p>


<script>function multiplyBy()
    {
            num1 = document.getElementById("firstNumber").value;
            num2 = document.getElementById("secondNumber").value;
            document.getElementById("result").innerHTML = num1 * num2;
    }
    </script>





<!-- 
    
  1st Number:<input type="text" id="t1" value="23" ></br>
  2nd Number:<input type="text" id="t2"></br>
     <button onclick="multiplyBy()">Multiply</button>
     <button>Divide</button>
     <p id="result">The Result is:</p> -->
             <!--   This JS IMPORt  -->
    <script src="main.js" type="module"></script>
</body>

</html>
 
<!-- ******************************************************** -->




  const [scrollStatus, setScrollStatus] = useState({
    scrollDirection: null,
    scrollPos: 0
  });

  useEffect(() => {
    if (innerRef.current) {
      innerRef.current.addEventListener("scroll", handleScrollDocument);
    }

    return () =>
      innerRef?.current.removeEventListener("scroll", handleScrollDocument);
  }, []);

  function handleScrollDocument() {
    if (!innerRef?.current) return;
    setScrollStatus((prev) => {
      // to get 'previous' value of state
      return {
        scrollDirection:
          innerRef.current.scrollTop > prev.scrollPos ? "down" : "up",
        scrollPos: innerRef.current.scrollTop
      };
    });
  }
javascript:(function()%7Bconst selectedText %3D getSelection().toString()%3Bconst newUrl %3D new URL(location)%3BnewUrl.hash %3D %60%3A~%3Atext%3D%24%7BencodeURIComponent(selectedText)%7D%60%3Bwindow.open(newUrl)%7D)()
Not all browsers support forEach on NodeLists, but for those that do:

buttons.forEach((button) => {
  button.addEventListener('click', () => {
    console.log("forEach worked");
  });
});

bit deeper browser support.

var divs = document.querySelectorAll('div');
[].forEach.call(divs, function(div) {
  // do whatever
  div.style.color = "red";
});
var pageDate = new Date(document.lastModified);
console.log("Page was last modified on: " + pageDate);
> (function fac (n) {
    return (n === 0 ? 1 : n*fac(n-1));
  })(10)
3628800
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process
useEffect(() => {
   fetch('https://jsonplaceholder.typicode.com/posts?_limit=10')
      .then((response) => response.json())
      .then((data) => {
         console.log(data);
         setPosts(data);
      })
      .catch((err) => {
         console.log(err.message);
      });
}, []);
import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  Modal,
  Image,
  ActivityIndicator
} from 'react-native';

class Loader extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: this.props.isLoading
    }
  }

  static getDerivedStateFromProps(nextProps) {
    return {
      isLoading: nextProps.isLoading
    };
  }

  render() {
    return (
      <Modal
        transparent={true}
        animationType={'none'}
        visible={this.state.isLoading}
        style={{ zIndex: 1100 }}
        onRequestClose={() => { }}>
        <View style={styles.modalBackground}>
          <View style={styles.activityIndicatorWrapper}>
            <ActivityIndicator animating={this.state.isLoading} color="black" />
            
            {/* If you want to image set source here */}
            {/* <Image
              source={require('../assets/images/loader.gif')}
              style={{ height: 80, width: 80 }}
              resizeMode="contain"
              resizeMethod="resize"
            /> */}
          </View>
        </View>
      </Modal>
    )
  }
}

const styles = StyleSheet.create({
  modalBackground: {
    flex: 1,
    alignItems: 'center',
    flexDirection: 'column',
    justifyContent: 'space-around',
    backgroundColor: '#rgba(0, 0, 0, 0.5)',
    zIndex: 1000
  },
  activityIndicatorWrapper: {
    backgroundColor: '#FFFFFF',
    height: 100,
    width: 100,
    borderRadius: 10,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-around'
  }
});

export default Loader
const army=["Marcos", "DeltaForce", "Seals", "SWAT", "HeadHunters"];  

if(army.indexOf("DeltaForce") !== -1) {
  console.log("exist")
} else {
  console.log("not exist")
}

if(army.includes("DeltaForce")) {
  console.log("exist")
} else {
  console.log("not exist")
}

for(let i = 0; i < army.length; i++) {
  if(army[i] === "DeltaForce") {
    console.log("exist")
    break
  }
}
let array = [1, 2, 3, 4, 5];

for (let i = 0; i < array.length; i++) {
  console.log(array[i]);
}

let j = 0;
while(j < array.length) {
  console.log(array[j]);
  j++;
}

for(let value of array) {
  console.log(value)
}

for(let key in array) {
  console.log(array[key])
}

array.forEach(num => console.log(num));
document.querySelectorAll(".row").forEach(
function(node) {
var text = node.innerText.replaceAll(/\n/g, ", ");
var link = node.innerHTML.match(/reporting\/[0-9a-zA-Z\-_]*/)|| "";
console.log(text + link[0] );
}
);
Here is a JavaScript code snippet that will get the width and height of all images on a page and add the width and height attributes to each img tag:



var images = document.getElementsByTagName("img");
for (var i = 0; i < images.length; i++) {
    var img = images[i];
    var width = img.naturalWidth;
    var height = img.naturalHeight;
    img.setAttribute("width", width);
    img.setAttribute("height", height);
}


This code uses the document.getElementsByTagName method to select all img tags on the page, then loops through each one using a for loop. The naturalWidth and naturalHeight properties of each img tag are used to get its dimensions, and the setAttribute method is used to add the width and height attributes with the appropriate values.



async function connect() {
  try {
    const
      connection = await asyncDBconnect('http://localhost:1234'),
      session = await asyncGetSession(connection),
      user = await asyncGetUser(session),
      log = await asyncLogAccess(user);

    return log;
  }
  catch (e) {
    console.log('error', err);
    return null;
  }
}

// run connect (self-executing async function)
(async () => { await connect(); })();
cipheredText = "54686973007761730061007265616c6c7900746f756768006368616c6c656e676500666f72006d65210042757400490064696400697421";
textLen = cipheredText.length;
RealText = "";
for (i=0; i<textLen;i+=2)
{
 RealText = RealText.concat(String.fromCharCode((parseInt(cipheredText[i]+cipheredText[i+1],16))));
}
console.log(RealText);
/* findIndex vs indexOf methods.
All return -1 when no value is found. */

let myArray = [9, 2, 2, 8, 4, 2, 5, 6, 2, 9];

// findIndex(arg => argCondition): return the first index 
// for which the given function is true.
myArray.findIndex(x => x > 2); // → 3

// indexOf(value): return the value's first index.
myArray.indexOf(2); // → 1

// lastIndexOf(value): return the value's last index.
myArray.lastIndexOf(2); // → 8

// indexOf(value, start): return the value's first index, 
// starting at the given position.
myArray.indexOf(2, 3); // → 5

// lastIndexOf(value, stop): return the value's last index, 
// stopping at the given position.
myArray.lastIndexOf(2, 3); // → 2
test('Check addTodo able add todo to todoList', () => {
  document.body.innerHTML = `
    <input id="newTodoInput" />
    <button id="addTodoBtn">Add todo</button>
    <ol id="todoList"></ol>
  `;
  require('../todolist.js');

  const newTodoInput = document.getElementById('newTodoInput');
  const addTodoBtn = document.getElementById('addTodoBtn');
  const todolist = document.getElementById('todoList');

  newTodoInput.value = 'New todolist!';
  addTodoBtn.click();

  expect(todolist.innerHTML).toBe('<li>New todolist!</li>');
});
const APP = (() => {
  var userData = null;
  const myURL = "http://stackoverflow.com";
  const getData = () => {
    $.ajax({
      type: "GET",
      url: myURL,
      success: obj.handleSuccess,
      error: obj.handleError,
    });
  };
  const handleError = () => {
    console.log("ERROR");
  };
  const handleSuccess = (data) => {
    userData = data;
    console.log(userData);
  };
  const render = () => {
    return "<div>some stuff</div>";
  };
  const obj = {
    getData,
    handleError,
    handleSuccess,
    render,
  };
  return obj;
})();
module.exports = APP;


const APP = require("../ajax");
describe("Ajax", () => {
  beforeEach(() => {
    jest.restoreAllMocks();
  });
  it("Data should load", () => {
    const ajaxSpy = jest.spyOn($, "ajax");
    APP.getData();
    expect(ajaxSpy).toBeCalledWith({
      type: "GET",
      url: "http://stackoverflow.com",
      success: expect.any(Function),
      error: expect.any(Function),
    });
  });
  it("should handle success", () => {
    const mUser = { userId: 1 };
    const logSpy = jest.spyOn(console, "log");
    APP.handleSuccess(mUser);
    expect(logSpy).toBeCalledWith(mUser);
  });
  it("should handle error", () => {
    const logSpy = jest.spyOn(console, "log");
    APP.handleError();
    expect(logSpy).toBeCalledWith("ERROR");
  });
});
let credential = await navigator.credentials.get({ publicKey: {
  challenge: new Uint8Array([139, 66, 181, 87, 7, 203, ...]),
  rpId: "acme.com",
  allowCredentials: [{
    type: "public-key",
    id: new Uint8Array([64, 66, 25, 78, 168, 226, 174, ...])
  }],
  userVerification: "required",
}});
let credential = await navigator.credentials.create({ publicKey: {
  challenge: new Uint8Array([117, 61, 252, 231, 191, 241, ...]),
  rp: { id: "acme.com", name: "ACME Corporation" },
  user: {
    id: new Uint8Array([79, 252, 83, 72, 214, 7, 89, 26]),
    name: "jamiedoe",
    displayName: "Jamie Doe"
  },
  pubKeyCredParams: [ {type: "public-key", alg: -7} ]
}});
// Literal values (type1)
const booleanLiteral = true;
const numberLiteral = 1;
const stringLiteral = 'true';

// Literal structures (type2)
const arrayLiteral = [];
const objectLiteral = {};

// Prototypes (type3)
const booleanPrototype = new Bool(true);
const numberPrototype = new Number(1);
const stringPrototype = new String('true');
const arrayPrototype = new Array();
const objectPrototype = new Object(); // or `new function () {}
const apps = [
  {id:1, name:'Jon'}, 
  {id:2, name:'Dave'},
  {id:3, name:'Joe'}
]

//remove item with id=2
const itemToBeRemoved = {id:2, name:'Dave'}

apps.splice(apps.findIndex(a => a.id === itemToBeRemoved.id) , 1)

//print result
console.log(apps)
 Run code snippet
const newArray = array.map(({dropAttr1, dropAttr2, ...keepAttrs}) => keepAttrs)
require(['jquery'], function($){
  "use strict";

    $(window).scroll(function() {
        if ($(this).scrollTop() > 1){
        $('header').addClass('sticky');
        }
        else{
        $('header').removeClass('sticky');
        }
    });
});
a = [
  {prop1:"abc",prop2:"qwe"},
  {prop1:"bnmb",prop2:"yutu"},
  {prop1:"zxvz",prop2:"qwrq"}];
    
index = a.findIndex(x => x.prop2 ==="yutu");

console.log(index);
const findOverflows = () => {
    const documentWidth = document.documentElement.offsetWidth;

    document.querySelectorAll('*').forEach(element => {
        const box = element.getBoundingClientRect();

        if (box.left < 0 || box.right > documentWidth) {
            console.log(element);
            element.style.border = '1px solid red';
        }
    });
};

// Execute findOverflows to find overflows on the page.
findOverflows();
$(".acc:first-child h6").addClass('active');
  $(".acc:first-child .answer").addClass('active');
  $(".acc:first-child").addClass('active');
  $(".acc h6").click( function () {
      if ($(this).hasClass('active')) {
        $(this).next().slideUp(function () {
          $(this).parent().find(".active").removeClass('active');
          $(this).parent(".acc.active").removeClass('active');
        });     
      } else {
        $(this).parent().siblings().removeClass('active');
        $(this).parent().siblings().find(".active").removeClass('active');
        $(this).parent().siblings().find(".answer").slideUp(300);
        $(this).parent().siblings().find(".answer").removeClass("open");

        $(this).addClass('active');
        $(this).parent(".acc").addClass('active');
        $(this).next().addClass("open").slideDown(300);
      }
    });
/**
     * @author Anirban Gupta (Huron)
     * @NApiVersion 2.1
     * @NScriptType UserEventScript
     * @NModuleScope SameAccount
     * @NAmdConfig /SuiteScripts/Library/requireConfig.json
     */
/**
     * Module Description
     * Script to adjust Date and Time to be entered from the User's end if the User's Timezone and Server's Timezone does not match.
     *
     *  Version   Date           Author              Comments
     *  1.0       18 Jan 2023    Anirban Gupta       Script Created.
     *
 */

define(['N/runtime', 'N/format', 'N/config', 'moment', 'moment-timezone'], function (runtime, format, config, moment, momentTz) {
    /**
     * Function definition to be triggered before record is submitted.
     *
     * @param {Object} context - Context
     * @Since 2015.2
     */
    function beforeSubmit(context) {
        log.audit('UE Type', context.type);
        log.audit('Execution Context', runtime.executionContext);
        let userObj = runtime.getCurrentUser();
        log.audit('User', 'User Internal ID:' + userObj.id);

        if (isSupportedUserEventType(context) && isSupportedContext()) {
            try {
                let userTimezone = userObj.getPreference({
                    name: 'timezone'
                });
                log.debug('Timezone', 'User preference for timezone: ' + userTimezone);

                let serverConfigurationRecord = config.load({
                    type: config.Type.COMPANY_INFORMATION
                });

                /* Fetching Server Timezone */
                let serverTimeZone = serverConfigurationRecord.getValue('timezone');
                log.debug('TimeZone', 'Server timezone: ' + serverTimeZone);

                /* If User's Timezone is not the same as the server's Timezone - we are manipulating the Date/Time to be set */
                if (userTimezone !== serverTimeZone) {
                    let startdate = context.newRecord.getValue('startdate');
                    let originalTime = format.parse({
                        value: startdate,
                        type: format.Type.DATETIME,
                        timezone: userTimezone
                    });
                    log.debug('Original Time', 'Original Time: ' + originalTime);
                    let originalDateInMomentFormat = parseInt(originalTime.getFullYear()) + '-' + (originalTime.getMonth() + 1) + '-' + parseInt(originalTime.getDate());

                    /* Calculating difference between Server's Timezone and User's Timezone */
                    let timeDifferenceInMinutes = momentTz(originalDateInMomentFormat).tz(userTimezone).utcOffset() - momentTz(originalDateInMomentFormat).tz(serverTimeZone).utcOffset();

                    /* Sometimes an entire day's minutes (1440) is added to the difference when we are calculating offset between a non-DST timezone and a DST timezone on the DST shift day, hence we are recalculating to get the correct difference */
                    while (timeDifferenceInMinutes > 1440) {
                        timeDifferenceInMinutes -= 1440;
                    }
                    while (timeDifferenceInMinutes < -1440) {
                        timeDifferenceInMinutes += 1440;
                    }

                    /* Adding the difference between the Server's Timezone and User's Timezone to the Date/Time set by the User */
                    let adjustedUserDateTime = new Date(momentTz(originalDateInMomentFormat).add(timeDifferenceInMinutes, 'minutes').tz(userTimezone).toISOString());

                    /* Preparing Date */
                    let adjustedUserDate = (adjustedUserDateTime.getMonth() + 1) + '/' + parseInt(adjustedUserDateTime.getDate()) + '/' + parseInt(adjustedUserDateTime.getFullYear());
                    let formattedAdjustedDate = format.parse({ value: adjustedUserDate, type: format.Type.DATE });
                    log.debug('Adjusted User Date', adjustedUserDate);

                    /* Preparing Time */
                    let adjustedUserTime = moment(adjustedUserDateTime).format("hh:mm a");
                    log.debug('Adjusted User Time', adjustedUserTime);

                    context.newRecord.setValue('startdate', formattedAdjustedDate);
                    context.newRecord.setText('starttime', adjustedUserTime);

                    log.audit('Adjusted Date', 'Adjusted Date And Time is:' + adjustedUserDateTime);
                }
            } catch (error) {
                log.debug("Error", error.name + ' ' + error.message + ' ' + error.stack);
            }
        }
    }

    let isSupportedUserEventType = (context) => {
        let UserEventType = context.UserEventType;
        return [UserEventType.CREATE, UserEventType.EDIT, UserEventType.XEDIT].indexOf(context.type) > -1;
    };

    // Does not support Webstore and RESTlet
    let isSupportedContext = () => {
        let ContextType = runtime.ContextType;

        return [
            ContextType.CLIENT,
            ContextType.CSV_IMPORT,
            ContextType.USEREVENT,
            ContextType.USER_INTERFACE,
            ContextType.WORKFLOW].indexOf(runtime.executionContext) > -1;
    };

    return {
        beforeSubmit: beforeSubmit
    };
});
/**
     * @author Anirban Gupta (Huron)
     * @NApiVersion 2.1
     * @NScriptType UserEventScript
     * @NModuleScope SameAccount
     * @NAmdConfig /SuiteScripts/Library/requireConfig.json
     */
/**
     * Module Description
     * Script to adjust Date and Time to be entered from the User's end if the User's Timezone and Server's Timezone does not match.
     *
     *  Version   Date           Author              Comments
     *  1.0       18 Jan 2023    Anirban Gupta       Script Created.
     *
 */

define(['N/runtime', 'N/format', 'N/config', 'moment', 'moment-timezone'], function (runtime, format, config, moment, momentTz) {
    /**
     * Function definition to be triggered before record is submitted.
     *
     * @param {Object} context - Context
     * @Since 2015.2
     */
    function beforeSubmit(context) {
        log.audit('UE Type', context.type);
        log.audit('Execution Context', runtime.executionContext);
        let userObj = runtime.getCurrentUser();
        log.audit('User', 'User Internal ID:' + userObj.id);

        if (isSupportedUserEventType(context) && isSupportedContext()) {
            try {
                let userTimezone = userObj.getPreference({
                    name: 'timezone'
                });
                log.debug('Timezone', 'User preference for timezone: ' + userTimezone);

                let serverConfigurationRecord = config.load({
                    type: config.Type.COMPANY_INFORMATION
                });

                /* Fetching Server Timezone */
                let serverTimeZone = serverConfigurationRecord.getValue('timezone');
                log.debug('TimeZone', 'Server timezone: ' + serverTimeZone);

                /* If User's Timezone is not the same as the server's Timezone - we are manipulating the Date/Time to be set */
                if (userTimezone !== serverTimeZone) {
                    let startdate = context.newRecord.getValue('startdate');
                    let originalTime = format.parse({
                        value: startdate,
                        type: format.Type.DATETIME,
                        timezone: userTimezone
                    });
                    log.debug('Original Time', 'Original Time: ' + originalTime);
                    let originalDateInMomentFormat = parseInt(originalTime.getFullYear()) + '-' + (originalTime.getMonth() + 1) + '-' + parseInt(originalTime.getDate());

                    /* Calculating difference between Server's Timezone and User's Timezone */
                    let timeDifferenceInMinutes = momentTz(originalDateInMomentFormat).tz(userTimezone).utcOffset() - momentTz(originalDateInMomentFormat).tz(serverTimeZone).utcOffset();

                    /* Sometimes an entire day's minutes (1440) is added to the difference when we are calculating offset between a non-DST timezone and a DST timezone on the DST shift day, hence we are recalculating to get the correct difference */
                    while (timeDifferenceInMinutes > 1440) {
                        timeDifferenceInMinutes -= 1440;
                    }
                    while (timeDifferenceInMinutes < -1440) {
                        timeDifferenceInMinutes += 1440;
                    }

                    /* Adding the difference between the Server's Timezone and User's Timezone to the Date/Time set by the User */
                    let adjustedUserDateTime = new Date(momentTz(originalDateInMomentFormat).add(timeDifferenceInMinutes, 'minutes').tz(userTimezone).toISOString());

                    /* Preparing Date */
                    let adjustedUserDate = (adjustedUserDateTime.getMonth() + 1) + '/' + parseInt(adjustedUserDateTime.getDate()) + '/' + parseInt(adjustedUserDateTime.getFullYear());
                    let formattedAdjustedDate = format.parse({ value: adjustedUserDate, type: format.Type.DATE });
                    log.debug('Adjusted User Date', adjustedUserDate);

                    /* Preparing Time */
                    let adjustedUserTime = moment(adjustedUserDateTime).format("hh:mm a");
                    log.debug('Adjusted User Time', adjustedUserTime);

                    context.newRecord.setValue('startdate', formattedAdjustedDate);
                    context.newRecord.setText('starttime', adjustedUserTime);

                    log.audit('Adjusted Date', 'Adjusted Date And Time is:' + adjustedUserDateTime);
                }
            } catch (error) {
                log.debug("Error", error.name + ' ' + error.message + ' ' + error.stack);
            }
        }
    }

    let isSupportedUserEventType = (context) => {
        let UserEventType = context.UserEventType;
        return [UserEventType.CREATE, UserEventType.EDIT, UserEventType.XEDIT].indexOf(context.type) > -1;
    };

    // Does not support Webstore and RESTlet
    let isSupportedContext = () => {
        let ContextType = runtime.ContextType;

        return [
            ContextType.CLIENT,
            ContextType.CSV_IMPORT,
            ContextType.USEREVENT,
            ContextType.USER_INTERFACE,
            ContextType.WORKFLOW].indexOf(runtime.executionContext) > -1;
    };

    return {
        beforeSubmit: beforeSubmit
    };
});
(GMT-05:00) Eastern Time (US & Canada)

Date time will always get in this format in MAP/REDUCE.
i.e what ever the timezone is in the netsuite user account , when map reduce run it will convert the Date time into EST(Eastern timezone ) and then show the result.

________________________________________________________________________________
Currently Anirban logic is:
That whatever the Date is set in start date , manipulate that date (by the help of time ) that when it gets converted into Eastern Time , it gives exact same date(which user tried to set at first place) with time.
i.e Manipulated DATE may look different,as per user set.But when get into map/reduce it will give the correct date as set by user.
catch (error) {
                log.debug("Error", error.name + error.message + error.stack);
            }
        function handleClick(e) {
            console.log(e);
            console.log(e.currentTarget);
            // Empty variables
            let fieldID = '';
            let fieldAndType = '';
            // Find the index with the li element
            e.path.find(function (el) {
                if (el.nodeName === 'LI') {
                    fieldID = el.getAttribute('data-id');
                    fieldAndType = el.getAttribute('data-content');
                    el.setAttribute("disabled", "disabled");
                }
            });
            // split data content to get the field and type
            var field = fieldAndType.split('-')[0].trim();
            var type = fieldAndType.split('-')[1].trim();

            // Based on field type create the input and append it to the form
            var optionalField = '';
            if (type == {{\App\Enums\ProfileOptionalFieldsTypeEnum::Text()->value }}) {
                var optionalField = '<div class="col-span-6 sm:col-span-3 lg:col-span-4"> <label for="'+field+'" class="block text-sm font-medium text-gray-700">' + field + '</label>'
                    + '<input type="text" name="' + field + '" id="' + field + '" autocomplete="given-name" class="mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md"></div>';

            } else if (type == {{\App\Enums\ProfileOptionalFieldsTypeEnum::TextArea()->value }}) {
                var optionalField = '<div class="col-span-6 sm:col-span-3 lg:col-span-4"> <label for="'+field+'" class="block text-sm font-medium text-gray-700">' + field + '</label>'
                    + '<textarea type="text" name="' + field + '" id="' + field + '" rows="10" cols="85" class="tinymce" autocomplete="given-name" class="mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md"></textarea></div>';
            }
            // append to div optionalFields
            document.getElementById('optionalFields').innerHTML += optionalField;


        }
npm install typescript --save-dev
npm install @types/node --save-dev
npx tsc --init --rootDir src --outDir lib --esModuleInterop --resolveJsonModule --lib es6,dom --module commonjs
const arrayOne = [ 
  { value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "Jamsheer" },
  { value: "644838b3-604d-4899-8b78-09e4799f586f", display: "Muhammed" },
  { value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "Ravi" },
  { value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "Ajmal" },
  { value: "a63a6f77-c637-454e-abf2-dfb9b543af6c", display: "Ryan" },
];
          
const arrayTwo = [
  { value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "Jamsheer"},
  { value: "644838b3-604d-4899-8b78-09e4799f586f", display: "Muhammed"},
  { value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "Ravi"},
  { value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "Ajmal"},
];

const results = arrayOne.filter(({ value: id1 }) => !arrayTwo.some(({ value: id2 }) => id2 === id1));

console.log(results);
    const toTop = () => window.scrollTo(0, 0);
    toTop();
const data = [
  { group: 'A', name: 'SD' }, 
  { group: 'B', name: 'FI' }, 
  { group: 'A', name: 'MM' },
  { group: 'B', name: 'CO'}
];
const unique = [...new Set(data.map(item => item.group))]; // [ 'A', 'B']
                    let filteredDatatableData = this.datatableDataToFilter.filter(function(item) {
                        const arrSome = lstCustomerResponseTO.some(v => v.person_id === item.personId);
                        return arrSome ? true : false;
                    });


----------------------------------------------------------------------------------------

var datatableData = [{"name":"Teste1","personId":"01"},{"name":"Teste1","personId":"02"},{"name":"Teste1","personId":"03"}];
var lstCustomerResponseTO = [{"name":"Teste1","personId":"01"},{"name":"Teste1","personId":"03"}];
let filteredDatatableData = datatableData.filter(function(item) {
    const arrSome = lstCustomerResponseTO.some(v => v.personId === item.personId);
    return arrSome;
});

console.log(filteredDatatableData)
const object = { a: 1, b: 2, c: 3 };

for (const property in object) {
  console.log(`${property}: ${object[property]}`);
}

// Expected output:
// "a: 1"
// "b: 2"
// "c: 3"
const counter = (function () {
  let privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }

  return {
    increment() {
      changeBy(1);
    },

    decrement() {
      changeBy(-1);
    },

    value() {
      return privateCounter;
    },
  };
})();

console.log(counter.value()); // 0.

counter.increment();
counter.increment();
console.log(counter.value()); // 2.

counter.decrement();
console.log(counter.value()); // 1.
function makeSizer(size) {
  return function() {
    document.body.style.fontSize = size + 'px';
  };
}

document.getElementById('size-12').onclick = makeSizer(12);
document.getElementById('size-14').onclick = makeSizer(14);
document.getElementById('size-16').onclick = makeSizer(16);
const dayOfYear = date =>
  Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);

dayOfYear(new Date()); // 272
var myDate = moment.utc('/Date(1673371207)/');
console.log(myDate.fomat('DD-MM-YYYY'));
var myDate = moment.utc('/Date(1673371207)/');
console.log(myDate.fomat('DD-MM-YYYY'));
function myDog(){
  var breed = "pug";
  console.log(breed);
}

myDog(); // output => pug
console.log(breed); //output => reference error
const textAreaResized = () => {
  const handler = (e) => {
    const target = e.currentTarget;
    target.style.height = "auto";
    target.style.height = `${target.scrollHeight}px`;
  };

  return <textarea onChange={handler} />;
};
    function getDebuggableWindows(host, port) {
        if (!host) {
            host = "127.0.0.1";
        }
        if (!port) {
            port = 9222;
        }
        var def = new $.Deferred();
        var request = new XMLHttpRequest();
        request.open("GET", "http://" + host + ":" + port + "/json");
        request.onload = function onLoad() {
            var sockets = JSON.parse(request.response);
            def.resolve(sockets);
        };
        request.onerror = function onError() {
            def.reject(request.response);
        };

        request.send(null);

        return def.promise();
    }
function popShift(arr) {
  let popped = arr.pop();
  let shifted = arr.shift();
  return [shifted, popped];
}

// do not change code below this line
console.log(popShift(["challenge", "is", "not", "complete"]));
function mixedNumbers(arr) {
  // change code below this line
  arr.unshift("I", 2, "three");
  arr.push(7, "VIII", 9);
  // change code above this line
  return arr;
}

// do not change code below this line
console.log(mixedNumbers(["IV", 5, "six"]));
Start Date	is on or before 01/03/2023	 
Task End Date (Custom)	is on or after 01/03/2023

IT will verifiy that 01/03/2023  lies between start and end date.

breakdown:
start date <=01/03/2023    i.e   jo date compare krna h wo piche hoga or equal <-----start date
End Date >=01/03/2023  i.e End Date ------> jo date compare krna h wo aghe hoga or equal.

so finally, :-  End Date ------>   jo date compare krna h  <-----start date
const cars = [{
  'make': 'audi',
  'model': 'r8',
  'year': '2012'
}, {
  'make': 'audi',
  'model': 'rs5',
  'year': '2013'
}, {
  'make': 'ford',
  'model': 'mustang',
  'year': '2012'
}, {
  'make': 'ford',
  'model': 'fusion',
  'year': '2015'
}, {
  'make': 'kia',
  'model': 'optima',
  'year': '2012'
}];

const grouped = _.groupBy(cars, car => car.make);

console.log(grouped);
var grouped = _.mapValues(_.groupBy(cars, 'make'),
                          clist => clist.map(car => _.omit(car, 'make')));

console.log(grouped);
var acFilter = savedsearchArray.filter(function (obj) {
                return obj.id == accountName;
              });



//##########################################################################################
// Online Javascript Editor for free
// Write, Edit and Run your Javascript code using JS Online Compiler


var savedsearchArray=[{"id":"1","name":"fz","vehicle":"bmw"},{"id":"2"}]

//returns only perticular json object , having that ID.
var acFilter = savedsearchArray.filter(function (obj) {
                return obj.id == 1;
              });
console.log("Welcome to Programiz!",acFilter);
UserDrinks.update({}, { $rename: { "creator" : "user" } }, { multi: true }, callback)
*, *::before, *::after{
	box-sizing: border-box;
}

*{
	margin: 0,
	padding: 0,
}

html{
	color-scheme: dark light;
}

body{
	min-height: 100vh;
}

img, picture, video, svg{
	display: block;
	max-width: 100%;
}

input, textarea, select, button {
	font: inherit;
}
#1 Login to Github account
#2 Create new Git repository by going to https://github/new
#3 Fill in "Repository Name" field with name of name new repositroy
#4 Optionally fill in the "Description" field
#4 Optionaly select one or more of the "Add a Readme.md", "Add .gitignore", "choose a license" options
#5 Click "Create repository" Button
#6 Get url of new repository - click "Code" button on outer repository page that comes up and then click copy icon at end of https: repository url
#7 Open terminal window and change to the directory the project will be in.
#8 In the terminal "git clone " and past the copied repository url and execute it.
#9 cd into the project directory crated by the clone
#10 Open the directory in Visual Studio Code by entering code .
#11 In VSC create a file name index.html
#12 Edit the created file and type 'doc' and take the emmet expansion
#13 The cursor moves to a empty line after the body tag
#14 Enter an h1 tag with some textual content i.e. <h1>hello world</h1>
#15 Enter a p tab filled with lorem text
#16 duplicate the line with a ctrl-c and multiple ctrl-v's
#17 git status
#18 git ad .
#19 git commit -m "initial commit"
#20 git remote -v
#21 git push origin main
#22 git checkout -b styling		!!! Currently just local
#23 add styles.css to vsc and in index.html add link to styles.css
#24 set contents of styles.css to
body{
  margin:0;
  background:pink;
  text-align: center;
}
git add .
git commit -m styling
git push origin styling

on github repository page go to settings - page and set which branch is being to be displayed as a github page.


#900
https://www.freecodecamp.org/news/git-cheat-sheet-and-best-practices-c6ce5321f52/
https://docs.github.com/en/get-started/quickstart/github-flow

git clone <url>
git init
git remote add origin <URL>
git remote set-url origin <url>


Number.prototype.noExponents = function() {
  var data = String(this).split(/[eE]/);
  if (data.length == 1) return data[0];

  var z = '',
    sign = this < 0 ? '-' : '',
    str = data[0].replace('.', ''),
    mag = Number(data[1]) + 1;

  if (mag < 0) {
    z = sign + '0.';
    while (mag++) z += '0';
    return z + str.replace(/^\-/, '');
  }
  mag -= str.length;
  while (mag--) z += '0';
  return str + z;
}
var n = 4.65661287307739E-10;
console.log(n.noExponents()) /*  returned value: (String)    0.000000000465661287307739  */
n = 9.935818877444285e+23
console.log(n.noExponents()) /*  returned value: (String)    993581887744428500000000  */
let targetStoreEle = document.querySelectorAll('.l-store--tab');

targetStoreEle.forEach(targetEl => {
    targetEl.addEventListener('click', function () {
        targetEl.classList.toggle('isActive');
        if (!targetEl.nextElementSibling.classList.contains('isActive')) {
            targetEl.nextElementSibling.classList.add('isActive');
            targetEl.nextElementSibling.style.height = 'auto';

            var height = targetEl.nextElementSibling.clientHeight + 'px';

            targetEl.nextElementSibling.style.height = '0px';

            setTimeout(function () {
                targetEl.nextElementSibling.style.height = height;
            }, 0);
        } else {
            targetEl.nextElementSibling.style.height = '0px';

            targetEl.nextElementSibling.addEventListener('transitionend', function () {
                targetEl.nextElementSibling.classList.remove('isActive');
            }, {
                once: true
            });
        }
    });
});
9. Classes
JavaScript classes are templates that consist of methods, variables, and inheritance.

/* Create Class
The following snippet will create a new class that will consist of methods and variables.
*/

class Fruit {

    constructor(name, color) {
        this._name = name;
        this._color = color;
    }

    eat() {
        console.log('You ate the ' + this.name + '.');
    }

    get name() {
        return this._name;
    }

    set name(name) {
        this._name = name;
    }

    get color() {
        return this._color;
    }

    set color(color) {
        this._color = color;
    }   

}
/* Create a new instance: */
let apple = new Fruit('Apple', 'Green');

/* Execute a method: */
apple.eat(); // Output: You ate the Apple.

/* Get property: */
console.log(apple.color); // Output: Green

/* Set property: */
apple.color = 'red';
console.log(apple.color); // Output: red

/* Create a child class: */
class Orange extends Fruit {

    constructor() {
        super('Orange', 'Orange');
    }

    throw() {
        console.log('You threw the ' + this.name + '.');
    }

}

/* Create a new instance of the child class: */
let orange = new Orange();
orange.throw(); // Output: You threw the Orange.
console.log(orange.color); // Output: Orange
  const dataExpiracao = new Date('2023-01-03');
  let dateToday = new Date()
  const offset = dateToday.getTimezoneOffset()
  dateToday = new Date(dateToday.getTime() - (offset*60*1000))
  var dateNow = dateToday.toISOString().split('T')[0]
  console.log(dateNow)
  var currentDate = new Date(dateNow);
  console.log(currentDate)
  console.log(dataExpiracao)

  const diffTime = Math.abs(currentDate - dataExpiracao);
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 
  console.log(diffTime + " milliseconds");
  console.log(diffDays + " days");
function getParameterByName(name) {
   var url = window.location.href;
   name = name.replace(/[\[\]]/g, "\\$&");
   var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)");
   results = regex.exec(url);
   if (!results) return null;
   if (!results[2]) return '';
   return decodeURIComponent(results[2].replace(/\+/g, " "));
}

let data =getParameterByName("filter");
var n = 21;
function square(num) {
  return num * num;
}

square(square());
let name1={
  firstname: "Eloln", 
  lastname: "Musk",
  printFullName: function() {
    console.log(this.firstname + " " + this.lastname);
  }
}
let name1={
  firstname: "Eloln", 
  lastname: "Musk",
  printFullName: function() {
    console.log(this.firstname + " " + this.lastname);
  }
}

 
const LOCAL_STORAGE_KEY = "task-list"

function TodoList() {
  const [todoList, setTodoList] = useState(() => {
    return JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) || []
  });
    
  useEffect(() => {
    localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(todoList));
  }, [todoList]);

  ...
const numArray = [20, 30, 34, 12, 3, 12, 2, 4, 5, 9, 4, 34, 1];

const numberSort = (array) => {
  let temp;
  for (let i = 0; i < array.length; i++) {
    for (let j = 0; j < array.length; j++) {
      if (array[i] > array[j]) {
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
      }
    }
  }
  return array;
};

const result = numberSort(numArray);
console.log(result);
 9C9299

Gain Unlimited Access to:
Raymond M.

38 Years Old

Location:

Phone:

Full Name
Address History
Age & DOB
Sexual Offenses
Possible Relatives
Social Information
Criminal History
Phone Numbers
Marriage Records
Misdemeanors
Unclaimed Money
Much More!
// COUNT UNIQUE NUMBERS
// [1, 2, 2, 2, 3, 4, 4, 5, 6, 7, 8, 8]
// output -> 8
// conditions
// i = 0, j = 1
// array[i] !== array[j]
// 1. i++
// 2. array[i] = array[j]

const countUnique = (arr) => {
  if (arr.length > 0) {
    let i = 0;
    for (let j = 1; j < arr.length; j++) {
      if (arr[i] !== arr[j]) {
        i++; 
        arr[i] = arr[j];
      }
    }
    return i + 1;
  } else {
    throw new Error("Array is empty!");
  }
};

const result = countUnique([1, 2, 2, 2, 3, 4, 4, 5, 6, 7, 8, 8]);
console.log(result); // 8
// STRING ANAGRAM
// "hello" -> "llheo"

// condition
// length check (for both string)
// String "hello"
// { h: 1, e: 1, l: 2, o: 1}

const isAnagram = (str1, str2) => {
  if (str1.length !== str2.length) {
    return false;
  }

  let counter = {};
  for (let letter of str1) {
    counter[letter] = (counter[letter] || 0) + 1;
  }

  for (let letter of str2) {
    if (!counter[letter]) {
      return false;
    }
    counter[letter] -= 1;
  }

  return true;
};

const result = isAnagram("hello", "llheo");
console.log(result); // true
const sumZeroPair = (arr) => {
  let left = 0, // -4
    right = arr.length - 1; // 4

  while (left < right) {
    let sum = arr[left] + arr[right]; // 0
    if (sum === 0) return [arr[left], arr[right]]; // true
    else if (sum > 0) right--;
    else left++;
  }
};

const res = sumZeroPair([-5, -4, -3, -2, 0, 2, 4, 6, 8]);
console.log(res);
var table = $('#example').DataTable({
  order: [[1, 'asc'], [0, 'asc']]
})  
<div class="page__wrapper">
	<header></header>
  	<main></main>
  	<footer></footer>
</div>

// css style
.page__wrapper {
	width: 100%;
	max-width: 1064px;
	margin: 0 auto;
	padding: 24px 20px;
}
// set ne style in the global style sheet
.swiper-button-prev,
.swiper-button-next {
  width: 20px;
  height: 20px;
  aspect-ratio: 1 / 1;
  padding: 25px;
  //background-color: rgba($black, 0.5);
  border: none;
  border-radius: 50px;
  top: unset !important;
  bottom: -80px;
  outline: none;
  cursor: pointer;
}

.swiper-button-next {
  right: unset !important;
  margin-left: calc(60px + $half-gap);
  background-image: url("../public/arrows-16px-1-tail-right.svg");
  background-repeat: no-repeat;
  background-position: center;

  &::after {
    display: none;
  }

  &.white {
    background-color: rgba($white, 0.5);
  }

  &.black {
    background-color: rgba($black, 0.5);
  }
}

.swiper-button-prev {
  left: 0 !important;
  background-image: url("../public/arrows-16px-1-tail-right.svg");
  background-repeat: no-repeat;
  background-position: center;
  transform: rotate(180deg);

  &::after {
    display: none;
  }

  &.white {
    background-color: rgba($white, 0.5);
  }

  &.black {
    background-color: rgba($black, 0.5);
  }
}
import React, { useEffect } from "react";
import { Text, View, StyleSheet, BackHandler, Alert } from "react-native";
import { useBackHandler } from "@react-native-community/hooks"

const App = () => {

  // Callback function for back action
  const backActionHandler = () => {
    Alert.alert("Alert!", "Are you sure you want to exit app?", [
      {
        text: "Cancel",
        onPress: () => null,
        style: "cancel"
      },
      { text: "YES", onPress: () => BackHandler.exitApp() }
    ]);
    return true;
  };

  // hook which handles event listeners under the hood
  useBackHandler(backActionHandler)

  return (
    <View style={styles.container}>
      <Text style={styles.text}>Click Back button!</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center"
  },
  text: {
    fontSize: 18,
    fontWeight: "bold"
  }
});

export default App;
(function($){
    $(document).ready(function(e){
      var store_url = "https://footballsupplements.com/"; // replaced with your shopify store url
      var product_id = "free-multivitamin"; // replaced with your product id
      var full_url = store_url + '/products/' + product_id + '.json';
      
      $.ajax({
        url: full_url,
        success: function(data) {
          //console.log("product id:" + data.product.id);
          //console.log("product title:" + data.product.title);
          // ... to do 
          // all your process with product data logic
          console.log(data);
        }
      });
      
      });
    })(jQuery);
function protectOnEdit(event) {
  var ss = SpreadsheetApp.getActive();
  var range = ss.getRange('Statutory Comp Jan-23to Dec-23!D6:E10');
  var timeZone = Session.getScriptTimeZone();
  var stringDate = Utilities.formatDate(new Date(), timeZone, '13/12/22 15:10');
  var description = 'Protected on ' + stringDate;
  var protection = range.protect().setDescription(description);

  // below code taken directly from Google's documentation

  var me = Session.getEffectiveUser();

  protection.addEditor(me);
  protection.removeEditors(protection.getEditors());
  if (protection.canDomainEdit()) {
    protection.setDomainEdit(false);
  }
}
moment('2010-10-20').isBefore('2010-10-21'); // true
// my slick slider as constant object
const mySlider = $('.testimonail-wrapper').on('init', function(slick) {
 
  // on init run our multi slide adaptive height function
  multiSlideAdaptiveHeight(this);
 
}).on('beforeChange', function(slick, currentSlide, nextSlide) {
 
  // on beforeChange run our multi slide adaptive height function
  multiSlideAdaptiveHeight(this);
 
}).slick(options);
 
 
// our multi slide adaptive height function passing slider object
function multiSlideAdaptiveHeight(slider) {
 
  // set our vars
  let activeSlides = [];
  let tallestSlide = 0;
 
  // very short delay in order for us get the correct active slides
  setTimeout(function() {
 
    // loop through each active slide for our current slider
    $('.slick-track .slick-active', slider).each(function(item) {
 
      // add current active slide height to our active slides array
      activeSlides[item] = $(this).outerHeight();
 
    });
 
    // for each of the active slides heights
    activeSlides.forEach(function(item) {
 
      // if current active slide height is greater than tallest slide height
      if (item > tallestSlide) {
 
        // override tallest slide height to current active slide height
        tallestSlide = item;
 
      }
 
    });
 
    // set the current slider slick list height to current active tallest slide height
    $('.slick-list', slider).height(tallestSlide);
 
  }, 10);
 
}
 
 
// when window is resized
$(window).on('resize', function() {
 
  // run our multi slide adaptive height function incase current slider active slides change height responsively
  multiSlideAdaptiveHeight(mySlider);
 
});
<form action="/action_page.php">
  <label for="pswrd">Password:</label>
  <input
    type="password"
    id="pswrd"
    name="pswrd"
    pattern="[a-z0-9]{1,15}"
    title="Password should be digits (0 to 9) or alphabets (a to z)."
  />

  <button type="submit">Submit</button>
</form>
Node *node = NULL; 
List *list = NULL; 
 
void insert(void *node); 
void drop(void *node); 
void clear(); 
int getSize(); 
void print(); 
void* get(int index); 
 
List *ListConstruction(){ 
   list = (List*)malloc(sizeof(List)); 
   node = (Node*)malloc(sizeof(Node)); 
   list->head = node; 
   list->insert = insert;// 将 insert 函数实现注册在 list 实体上
   list->drop = drop; 
   list->clear = clear; 
   list->size = 0; 
   list->getSize = getSize; 
   list->get = get; 
   list->print = print; 
   list->_this = list;// 用 _this 指针将 list 本身保存起来
 
   return (List*)list; 
}
#ifndef _ILIST_H 
 #define     _ILIST_H 
 
 // 定义链表中的节点结构
 typedef struct node{ 
    void *data; 
    struct node *next; 
 }Node; 
 
 // 定义链表结构
 typedef struct list{ 
    struct list *_this; 
    Node *head; 
    int size; 
    void (*insert)(void *node);// 函数指针
    void (*drop)(void *node); 
    void (*clear)(); 
    int (*getSize)(); 
    void* (*get)(int index); 
    void (*print)(); 
 }List; 
 
 void insert(void *node); 
 void drop(void *node); 
 void clear(); 
 int getSize(); 
 void* get(int index); 
 void print(); 
 
 #endif      /* _ILIST_H */
<!-- Called of font style  file -->

​

<link href='https://fonts.googleapis.com/css?family=Allerta' rel='stylesheet'>

​

​

    <h2>Wellcome to Rofa Music store</h2>

    <div class="container-audio">

        <audio controls  loop autoplay>

                   <source src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/9473/new_year_dubstep_minimix.ogg" type="audio/ogg">

                   Your browser dose not Support the audio Tag

               </audio>

    </div>

    <div class="container-audio">

        <div class="colum1">

            <div class="row"></div>

        </div>

        <div class="colum1">

            <div class="row"></div>

        </div>

        <div class="colum1">
let userName = '';
userName ? console.log(`Hello, ${userName}!`) : console.log('Hello!');
let eightBall = '';
console.log(eightBall);
let userQuestion = 3;

let randomNumber = Math.floor(Math.random() * 8);
if (userQuestion === 0) {
    console.log('Outlook not so good');
} else if (userQuestion === 1) {
    console.log('Do not count on it');
} else if (userQuestion === 2) {
    console.log('Signs point to yes');
} else if (userQuestion === 3) {
    console.log('Reply hazy try again');
} else if (userQuestion === 4) {
    console.log('Cannot predict now');
} else if (userQuestion === 5) {
    console.log('It is certain!');
} else if (userQuestion === 6) {
    console.log('It is decidedly so');
} else if (userQuestion === 7) {
  console.log('My sources say no');
} else{console.log('Ask me a question to get started.')};
// temporarily disabled 
    // function getJournalDaily() {
    //     const url = "/student/habit-daily";

    //     const loading = `
    //     <tr class="loading-dot bg-white-2">
    //         <td colspan="8">
    //             <div class="d-flex align-items-center">
    //                 <div>
    //                     <div class="snippet col-1" data-title=".dot-flashing">
    //                         <div class="stage">
    //                             <div class="dot-flashing"></div>
    //                         </div>
    //                     </div>
    //                 </div>
    //                 <p class="grey-6 ml-4">Memuat pembiasaan harian...</p>
    //             </div>
    //         </td>
    //     </tr>`;

    //     $.ajax({
    //         method: 'get',
    //         dataType: 'json',
    //         data: {
    //             currentEmptyHabit,
    //         },
    //         url: url,
    //         success: function(response) {
    //             let emptyDate = moment(response.emptyDateHabit[currentEmptyHabit]);
    //             let today = moment(moment().format('YYYY-MM-DD'));
    //             let dateTimeAgo = today.diff(emptyDate, 'days');
    //             let startOfWeek = moment(response.emptyDateHabit[currentEmptyHabit]).startOf('isoWeek').format('YYYY-MM-DD');
    //             let endOfWeek = moment(response.emptyDateHabit[currentEmptyHabit]).endOf('isoWeek').format('YYYY-MM-DD');
    //             if (response.emptyDateHabit == []) {

    //                 let infoBoxHabbitDone = (`
    //                         <div class="info-box-success mt-4">
    //                             <div>
    //                                 <x-icon classicon="fill-dark-green" type="done" />
    //                             </div>
    //                             <div class="ml-4">
    //                                 Alhamdulillah... semua jurnal <b>sudah selesai</b> diisi.
    //                             </div>
    //                         </div>
    //                     `);
    //                 $('#infobox-habbit').html(infoBoxHabbitDone);
    //                 $('.icon-status').html(`<x-icon classicon="fill-green-3" type="done" />`);
    //             } else {
    //                 if (dateTimeAgo === 1) {
    //                     let habitType = '';
    //                     if (response.habitProgress.undone.SALAT_ZIKIR.length != 0) {
    //                         habitType = 'SALAT_ZIKIR';
    //                     } else if (response.habitProgress.undone.DAILY.length != 0) {
    //                         habitType = 'DAILY';
    //                     } else if (response.habitProgress.undone.WEEKLY.length != 0) {
    //                         habitType = 'WEEKLY';
    //                     }

    //                     let infoBoxYesterday = (`
    //                         <div class="info-box-group mt-4">
    //                             <div class="info-box-danger">
    //                                 <div>
    //                                     <x-icon classicon="fill-dark-red" type="due" />
    //                                 </div>
    //                                 <div class="ml-4">
    //                                     Kamu belum selesai mengisi jurnal <b>kemarin</b> (${moment(response.emptyDateHabit[currentEmptyHabit]).format("dddd, DD MMMM YYYY")}).
    //                                     Ayo tuntaskan sebelum lupa. Semangaaat!
    //                                 </div>
    //                             </div>
    //                             <div class="info-box-button">
    //                                 <div id="fill-journal-daily" class="info-box-button-item font-15 line-h20 font-w600 blue cursor-pointer" data-currentdate="${response.emptyDateHabit[currentEmptyHabit]}" data-startdate="${startOfWeek}" data-enddate="${endOfWeek}" data-habitType="${habitType}">
    //                                     Isi Jurnal
    //                                 </div>
    //                                 <div class="info-box-button-item grey-3 cursor-pointer" type="button" onClick="getJournalDaily()" ${currentEmptyHabit == (response.emptyDateHabit.length - 1) ? 'disabled' : ''}>
    //                                     Lewati
    //                                 </div>
    //                             </div>
    //                         </div>
    //                     `);

    //                     $('#infobox-habbit').html(infoBoxYesterday);
    //                 } else if (dateTimeAgo === 0) {
    //                     let infoBoxToday = (`
    //                         <div class="info-box-primary mt-4">
    //                             <div>
    //                                 <x-icon classicon="fill-dark-blue" type="pin" />
    //                             </div>
    //                             <div class="ml-4">
    //                                 Ayo selesaikan mengisi <b>jurnal hari ini</b> (${moment(response.emptyDateHabit[currentEmptyHabit]).format("dddd, DD MMMM YYYY")})!
    //                             </div>
    //                         </div>
    //                         `);

    //                     $('#infobox-habbit').html(infoBoxToday);
    //                     if (response.habitProgress.progress == 0) {
    //                         $('.icon-status').html(`<x-icon classicon="fill-red-3" type="unknown" />`);
    //                     } else {
    //                         $('.salat-zikir-dashboard').removeClass('d-none');
    //                         if (response.habitProgress.progress == 47) {
    //                             $('#progress-salat-zikir').css('width', `100` + '%');
    //                         } else {
    //                             $('#progress-salat-zikir').css('width', `${response.habitProgress.progress * 2}` + '%');
    //                         }
    //                         $('#progress-salat-zikir').attr('aria-valuenow', `${response.habitProgress.progress}`);
    //                         $('#progress-salat-zikir').attr('aria-valuemax', response.habitProgress.max);
    //                     }
    //                 } else if (dateTimeAgo > 0 && dateTimeAgo != 1) {

    //                     let habitType = '';
    //                     if (response.habitProgress.undone.SALAT_ZIKIR.length != 0) {
    //                         habitType = 'SALAT_ZIKIR';
    //                     } else if (response.habitProgress.undone.DAILY.length != 0) {
    //                         habitType = 'DAILY';
    //                     } else if (response.habitProgress.undone.WEEKLY.length != 0) {
    //                         habitType = 'WEEKLY';
    //                     }

    //                     let infoBoxDayAgo = (`
    //                     <div class="info-box-group mt-4">
    //                         <div class="info-box-danger">
    //                             <div>
    //                                 <x-icon classicon="fill-dark-red" type="due" />
    //                             </div>
    //                             <div class="ml-4">
    //                                 Kamu belum selesai mengisi jurnal <b>${dateTimeAgo} hari yang lalu</b> (${moment(response.emptyDateHabit[currentEmptyHabit]).format("dddd, DD MMMM YYYY")}).
    //                                 Ayo tuntaskan sebelum lupa. Semangaaat!
    //                             </div>
    //                         </div>
    //                         <div class="info-box-button">
    //                             <div id="fill-journal-daily" class="info-box-button-item font-15 line-h20 font-w600 blue cursor-pointer" data-currentdate="${response.emptyDateHabit[currentEmptyHabit]}" data-startdate="${startOfWeek}" data-enddate="${endOfWeek}" data-habitType="${habitType}">
    //                                 Isi Jurnal
    //                             </div>
    //                             <div class="info-box-button-item grey-3 cursor-pointer" type="button" onClick="getJournalDaily()" ${currentEmptyHabit == (response.emptyDateHabit.length - 1) ? 'disabled' : ''}>
    //                                 Lewati
    //                             </div>
    //                         </div>
    //                     </div>
    //                     `);
    //                     $('#infobox-habbit').html(infoBoxDayAgo);
    //                 }
    //             }

    //             currentEmptyHabit += 1;

    //         },
    //         error: function(error) {}
    //     });
    // }

    // function getJournalWeekly() {
    //     const url = "/student/habit-weekly";

    //     const loading = `
    //     <tr class="loading-dot bg-white-2">
    //         <td colspan="8">
    //             <div class="d-flex align-items-center">
    //                 <div>
    //                     <div class="snippet col-1" data-title=".dot-flashing">
    //                         <div class="stage">
    //                             <div class="dot-flashing"></div>
    //                         </div>
    //                     </div>
    //                 </div>
    //                 <p class="grey-6 ml-4">Memuat pembiasaan harian...</p>
    //             </div>
    //         </td>
    //     </tr>`;

    //     $.ajax({
    //         method: 'get',
    //         dataType: 'json',
    //         url: url,
    //         success: function(response) {
    //             let dataDeedNull = 0;
    //             response.draftHabituationReport.forEach((index, key) => {
    //                 if (index.deeds == null) {
    //                     dataDeedNull += 1;
    //                 }
    //             });


    //             if (dataDeedNull > 0) {
    //                 let infoBoxDayAgo = (`
    //                 <div class="info-box-group mt-4">
    //                     <div class="info-box-danger">
    //                         <div>
    //                             <x-icon classicon="fill-dark-red" type="due" />
    //                         </div>
    //                         <div class="ml-4">
    //                             Kamu belum selesai mengisi jurnal <b>minggu lalu</b> (${moment(response.startOfWeek).format("DD MMMM YYYY")} - ${moment(response.endOfWeek).format("DD MMMM YYYY")}). Ayo tuntaskan sebelum lupa. Semangaaat!
    //                         </div>
    //                     </div>
    //                     <div class="info-box-button">
    //                         <div id="fill-journal-weekly" class="info-box-button-item font-15 line-h20 font-w600 blue cursor-pointer" data-startdate="${response.startOfWeek}" data-enddate="${response.endOfWeek}">
    //                             Isi Jurnal
    //                         </div>
    //                         <div class="info-box-button-item grey-3 cursor-pointer" type="button" onClick="getJournalDaily()">
    //                             Lewati
    //                         </div>
    //                     </div>
    //                 </div>
    //                 `);
    //                 $('#infobox-habbit').html(infoBoxDayAgo);
    //             } else {
    //                 getJournalDaily();
    //             }
    //         },
    //         error: function(error) {}
    //     });
    // }
const { data, count } = supabase
  .from('countries')
  .select('*', { count: 'exact' })
import sqlite3
import os


def merge_databases(db1, db2):
    con3 = sqlite3.connect(db1)

    con3.execute("ATTACH '" + db2 +  "' as dba")

    con3.execute("BEGIN")
    for row in con3.execute("SELECT * FROM dba.sqlite_master WHERE type='table'"):
        combine = "INSERT OR IGNORE INTO "+ row[1] + " SELECT * FROM dba." + row[1]
        print(combine)
        con3.execute(combine)
    con3.commit()
    con3.execute("detach database dba")


def read_files(directory):
    fname = []
    for root,d_names,f_names in os.walk(directory):
        for f in f_names:
            c_name = os.path.join(root, f)
            filename, file_extension = os.path.splitext(c_name)
            if (file_extension == '.sqlitedb'):
                fname.append(c_name)

    return fname

def batch_merge(directory):
    db_files = read_files(directory)
    for db_file in db_files:
        merge_databases(db_files[0], db_file)

if __name__ == '__main__':
    batch_merge('/directory/to/database/files')
const s = "My cow always gives milk, thier cow also gives milk";
const matches = s.matchAll(/cow (.*?) milk/g);
console.log(Array.from(matches, x => x[1]));
let arr = [
    { name: "string 1", value: "this", other: "that" },
    { name: "string 2", value: "this", other: "that" },
  ];

  console.log("arr: ", arr);
function foo() {}

function bar() {
  foo();
  foo();
  return 42;
}
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const { hash } = require('../helpers/bcrypt')

const userSchema = new Schema({

email: {
    type: String,
    required: [true, 'email is required'],
    match: [/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/, 'Invalid email format'],
    validate: {
        validator: function(v){
            return this.model('User').findOne({ email: v }).then(user => !user)
        },
        message: props => `${props.value} is already used by another user`
    },
},
password: {
    type: String,
    required: [true, 'password is required']
}

})

userSchema.pre('save', function(done){
    this.password = hash(this.password)
    done()
})


module.exports = mongoose.model('User', userSchema)
function getParameterByName(key,url) {
  name = key.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  results = regex.exec(url);
  if (results) {
    results = decodeURIComponent(results[1].replace(/\+/g, " "));
  }
  else {
    results = false;
  }
  return results;
}
var port = chrome.runtime.connect({name: "knockknock"});
port.postMessage({joke: "Knock knock"});
port.onMessage.addListener(function(msg) {
  if (msg.question === "Who's there?")
    port.postMessage({answer: "Madame"});
  else if (msg.question === "Madame who?")
    port.postMessage({answer: "Madame... Bovary"});
});
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting === "hello")
      sendResponse({farewell: "goodbye"});
  }
);
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
  console.log(response.farewell);
});
// The ID of the extension we want to talk to.
var laserExtensionId = "abcdefghijklmnoabcdefhijklmnoabc";

// Make a simple request:
chrome.runtime.sendMessage(laserExtensionId, {getTargetData: true},
  function(response) {
    if (targetInRange(response.targetData))
      chrome.runtime.sendMessage(laserExtensionId, {activateLasers: true});
  }
);

// Start a long-running conversation:
var port = chrome.runtime.connect(laserExtensionId);
port.postMessage(...);
function getFileExtension(path) {
  var lastSlash = path.lastIndexOf("/"),
      extension, baseName, parts;
  
  if (lastSlash === path.length - 1) {
    baseName = path.slice(path.lastIndexOf("/", path.length - 2) + 1, -1);
  } else {
    baseName = path.slice(lastSlash + 1);
  }
  
  idx = baseName.lastIndexOf(".");
  
  if (idx === -1) {
    return "";
  }
  
  return baseName.substr(idx + 1);
}
const ReactDOMServer = require('react-dom/server');

const clientHtml = ReactDOMServer.renderToString(
<StrictMode>
    <App />
</StrictMode>
)
Save Snippet
const ReactDOMServer = require('react-dom/server');

const clientHtml = ReactDOMServer.renderToString(
<StrictMode>
    <App />
</StrictMode>
)
Save Snippet
const ReactDOMServer = require('react-dom/server');

const clientHtml = ReactDOMServer.renderToString(
<StrictMode>
    <App />
</StrictMode>
)
Save Snippet
//Installation
//Install the Rollbar rollbar.js package using npm:
// npm install --save rollbar


// include and initialize the rollbar library with your access token
var Rollbar = require('rollbar')
var rollbar = new Rollbar({
  accessToken: '<ACCESS_TOKEN>',
  captureUncaught: true,
  captureUnhandledRejections: true,
})

// record a generic message and send it to Rollbar
rollbar.log('Hello world!')
import React, { useState, useEffect } from 'react';
import throttle from 'lodash/fp/throttle';

export interface useScrollSpyParams {
  activeSectionDefault?: string; //The key of the section that should be active by default
  offsetPx?: number;
  sectionElementRefs: { [key: string]: React.RefObject<HTMLElement> }; //The key of each element should be uniq!
  throttleMs?: number;
  scrollingElement?: React.RefObject<HTMLElement>;
}

export const useScrollSpy = ({
  activeSectionDefault = '',
  offsetPx = 0,
  scrollingElement,
  sectionElementRefs = {},
  throttleMs = 100,
}: useScrollSpyParams) => {
  const [activeSection, setActiveSection] = useState(activeSectionDefault);

  const scrollIntoView = (sectionKey: string) => {
    const sectionElement = sectionElementRefs[sectionKey].current;
    const scrollingContainer = scrollingElement?.current || window;
    if (sectionElement && scrollingContainer) {
      scrollingContainer.scrollTo({
        top: sectionElement.getBoundingClientRect().top + offsetPx - 60,
        behavior: 'smooth',
      });
    }
  };

  const handle = throttle(throttleMs, () => {
    let currentSectionId = activeSection;

    Object.entries(sectionElementRefs).forEach(([sectionKey, ref]) => {
      const section = ref.current;
      if (!section || !(section instanceof Element)) return;
      // GetBoundingClientRect returns values relative to viewport
      if (section.getBoundingClientRect().top + offsetPx < 0) {
        currentSectionId = sectionKey;
        return;
      }
      return;
    });
    setActiveSection(currentSectionId);
  });

  useEffect(() => {
    const scrollable = scrollingElement?.current ?? window;
    scrollable.addEventListener('scroll', handle);

    // Run initially
    handle();

    return () => {
      scrollable.removeEventListener('scroll', handle);
    };
  }, [sectionElementRefs, offsetPx, scrollingElement, handle]);
  return { activeSection, scrollIntoView };
};
// Object destructuring
const person = {
  name: 'John',
  age: 32,
  city: 'New York',
  country: 'USA'
};

const { name, age } = person;

// Object destructuring with alias

const { name: firstName, age: years } = person;

// Array destructuring
const fruits = ['apple', 'banana', 'orange'];
const [first, second, third] = fruits;
function dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);

      while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
      }

      return new File([u8arr], filename, { type: mime });
  }
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data:gap: http://www.visitsingapore.com   https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="css/index.css">
<link rel="stylesheet" href="css/jquery.mobile-1.4.5.css">
<script src="lib/jquery-3.2.1.min.js"></script>

<script type="text/javascript" src="scripts/key.js"></script>
<script>$.ajax({
        url: ' http://www.visitsingapore.com/api.listing.en.json',
        type: 'GET',
        beforeSend: function (xhr) {
            xhr.setRequestHeader('email ID', '-------@gmail.com');
            xhr.setRequestHeader('token ID', '-------');
        },
        data: {},
        success: function (qwe12) {
            var TrueResult2 = JSON.stringify(qwe12);
            document.write(TrueResult2);
        },
        error: function () { },
    });</script>
Save Code
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data:gap: http://www.visitsingapore.com   https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="css/index.css">
<link rel="stylesheet" href="css/jquery.mobile-1.4.5.css">
<script src="lib/jquery-3.2.1.min.js"></script>

<script type="text/javascript" src="scripts/key.js"></script>
<script>$.ajax({
        url: ' http://www.visitsingapore.com/api.listing.en.json',
        type: 'GET',
        beforeSend: function (xhr) {
            xhr.setRequestHeader('email ID', '-------@gmail.com');
            xhr.setRequestHeader('token ID', '-------');
        },
        data: {},
        success: function (qwe12) {
            var TrueResult2 = JSON.stringify(qwe12);
            document.write(TrueResult2);
        },
        error: function () { },
    });</script>
Save Code
 import React from "react";
    
  class App extends React.Component {

  head() {
    return (
      <head>
        <meta charSet="utf-8" />
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1, shrink-to-fit=no"
        />
        <meta name="theme-color" content="#000000" />
        <title>React App</title>
      </head>
    );
  }

  body() {
    return (
      <body>
        <div className="App">
          <h1>Client says Hello World</h1>
        </div>
      </body>
    );
  }

  render() {
    return (
      <React.Fragment>
        {this.head()}
        {this.body()}
      </React.Fragment>
    )
  }
}
export default App;
Save Code
 import React from "react";
    
  class App extends React.Component {

  head() {
    return (
      <head>
        <meta charSet="utf-8" />
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1, shrink-to-fit=no"
        />
        <meta name="theme-color" content="#000000" />
        <title>React App</title>
      </head>
    );
  }

  body() {
    return (
      <body>
        <div className="App">
          <h1>Client says Hello World</h1>
        </div>
      </body>
    );
  }

  render() {
    return (
      <React.Fragment>
        {this.head()}
        {this.body()}
      </React.Fragment>
    )
  }
}
export default App;
Save Code
// Load content onload if it exists in localStorage
window.onload = function() {
	if(localStorage.getItem('content')) {
		document.querySelector('.content').innerHTML = localStorage.getItem('content');
  }
}

let editBtn = document.querySelector('#edit_content');
let content = document.querySelector('.content');

editBtn.addEventListener('click', () => {
  // Toggle contentEditable on button click
	content.contentEditable = !content.isContentEditable;
  
  // If disabled, save text
  if(content.contentEditable === 'false') {
  	localStorage.setItem('content', content.innerHTML);
  }
});
Grab up to 30% off on our blockchain fork development Services limited time Offer ends in November 25.

For the development of many business sectors, blockchain forks are essential. However, depending on the position, the process requires the use of technology. This is why we're going to look at some of the ways that cryptocurrencies can be developed, including forking existing blockchains to create new ones.

Hivelance, a leading blockchain fork development company, creates a customizable Blockchain Fork Development on various blockchain networks such as Ethereum, Tron, and Binance Smart Chain (BSC), allowing innovators to launch their businesses faster.

visit our site for know more-

https://www.hivelance.com/blockchain-forking
Black Friday sale : Grab up to 30% off on our NFT Token development Services limited time Offer ends in November 25.

Hivelance is a reputable NFT Token development business that works with clients from all over the world and across many industry sectors. We have developed secure, efficient, and revenue-generating NFT development solutions. Hivelance is a leading NFT token development company that offering a  top-notch innovative NFT token development solutions for various businesses across multiple industries. Being the best token development company we create and launch the different types of tokens according to the client’s requirement. We make engaging non-fungible token with transparency, high-end security, and faster delivery.

visit our website for more info-

https://www.hivelance.com/nft-token-development
Grab up to 30% off on our ERC20 Token development Services limited time Offer ends in November 25.

The ERC20 Token contract is the smart contract code logic that executes the fungible token activity. When a contract is put into practise on Ethereum, it can be exchanged for any tokens with a similar value. The ERC20 token standard is used for crypto staking, voting, and the exchange of digital cash as a result. Anyone can generate ERC20 tokens and import them into Ethereum virtual machines.

Hivelance provides ERC20 token development service.  We offer an alot of options as part of our ERC20 Token development package, such as code generation, logo design, an audit of the ERC token contract, deployment to the EVM, ongoing development, security audits at regular intervals, and more. We have supported various ICO projects and helped them scale up their fundraising efforts.

https://www.hivelance.com/erc20-token-development
//Use localStorage for that. It's persistent over sessions.

//Writing :
localStorage['myKey'] = 'somestring'; // only strings

//Reading :
var myVar = localStorage['myKey'] || 'defaultValue';

//If you need to store complex structures, you might serialize them in JSON. For example :

//Reading :
var stored = localStorage['myKey'];
if (stored) myVar = JSON.parse(stored);
else myVar = {a:'test', b: [1, 2, 3]};

//Writing :
localStorage['myKey'] = JSON.stringify(myVar);

//Note that you may use more than one key. They'll all be retrieved by all pages on the same domain.

//Unless you want to be compatible with IE7, you have no reason to use the obsolete and small cookies.
var materials = [
    new THREE.MeshBasicMaterial( {color:'#b02030'} ),
    new THREE.MeshLambertMaterial( {color:'#b02030'} ), 
    new THREE.MeshPhongMaterial( {color:'#b02030', shininess: 100 } ),
    new THREE.MeshNormalMaterial(),
    // ...
];
var materialToShow = 0;
function degreesToRadians(degrees) {
  return (degrees * Math.PI) / 180
}

function distanceInKmBetweenEarthCoordinates(lat1, lon1, lat2, lon2) {
  const earthRadiusKm = 6371

  const dLat = degreesToRadians(lat2 - lat1)
  const dLon = degreesToRadians(lon2 - lon1)

  lat1 = degreesToRadians(lat1)
  lat2 = degreesToRadians(lat2)

  let a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2)
  let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
  return earthRadiusKm * c
}

console.log(
  distanceInKmBetweenEarthCoordinates(
    6.5361348,
    3.3913253,
    6.5362509,
    3.3913711
  )
)
const findLocation = () => {
  const status = document.querySelectorAll('.status')

  const success = (position) => {
    console.log(position)
  }

  const error = () => {
    status.textContent = 'unable to get location'
  }

  navigator.geolocation.getCurrentPosition(success, error, {
    maximumAge: '10000',
    enableHighAccuracy: true,
  })
}

window.addEventListener('load', findLocation)
const text = "codetogo saved me tons of time";

text.replace(/ /g, "-");
//HTML
<ul className='card'>
   <li>
    <img src={avatar_url} alt={login} />
      <div>
      <h4>{login}</h4>
 		<a href={html_url}>profile</a>
 	 </div>
  </li>
</ul>


.card {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 2rem;
  margin: 3rem auto;
}

.card li {
  width: 100%;
  display: flex;
  align-items: center;
  background: var(--clr-white);
  padding: 1rem 2rem;
  border-radius: var(--radius);
  text-align: left;
}
document.addEventListener('click', event => {
  if (event.target.matches('button')) {
    event.target.focus()
  }
})
switch (value)
{
  case 0:
    result = ZERO_DIGIT;
    break;

  case 1:
  case 3:
  case 5:
  case 7:
  case 9:
     result = ODD_DIGIT;
     break;

  case 2:
  case 4:
  case 6:
  case 8:
     result = EVEN_DIGIT;
     break;
}
var propertiesToTest = ["prop1", "prop2", "prop3"];
if (propertiesToTest.every(function(x) { return x in a; })) 
    console.log("a has these properties:'prop1, prop2 and prop3'");
$(window).scroll(function(){
    if ($(this).scrollTop() > 50) {
       $('#dynamic').addClass('newClass');
    } else {
       $('#dynamic').removeClass('newClass');
    }
});
$('nav.topmenu li a').filter(function(){
    return this.href === location.href;
  }).addClass('active');
jQuery Replace

x.replace(/(\r\n|\n|\r)/gm, ""); //replaces line breaks \n

x.replace(/[A-Za-z]/g, "") //replaces all letters

x.trim() // removes whitespaces
function checkFlag() {
    if(flag === false) {
       window.setTimeout(checkFlag, 100); /* this checks the flag every 100 milliseconds*/
    } else {
      /* do something*/
    }
}
checkFlag();

//Si quieres enviar parametros tambien
window.setTimeout( () => { checkFlag(params); }, 100);
// Loading the dependencies. We don't need pretty
// because we shall not log html to the terminal
const axios = require("axios");
const cheerio = require("cheerio");
const fs = require("fs");

// URL of the page we want to scrape
const url = "https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3";

// Async function which scrapes the data
async function scrapeData() {
  try {
    // Fetch HTML of the page we want to scrape
    const { data } = await axios.get(url);
    // Load HTML we fetched in the previous line
    const $ = cheerio.load(data);
    // Select all the list items in plainlist class
    const listItems = $(".plainlist ul li");
    // Stores data for all countries
    const countries = [];
    // Use .each method to loop through the li we selected
    listItems.each((idx, el) => {
      // Object holding data for each country/jurisdiction
      const country = { name: "", iso3: "" };
      // Select the text content of a and span elements
      // Store the textcontent in the above object
      country.name = $(el).children("a").text();
      country.iso3 = $(el).children("span").text();
      // Populate countries array with country data
      countries.push(country);
    });
    // Logs countries array to the console
    console.dir(countries);
    // Write countries array in countries.json file
    fs.writeFile("coutries.json", JSON.stringify(countries, null, 2), (err) => {
      if (err) {
        console.error(err);
        return;
      }
      console.log("Successfully written data to file");
    });
  } catch (err) {
    console.error(err);
  }
}
// Invoke the above function
scrapeData();
const Huzaifa = "this is for the purpose of the demo and not permanent"

function huzaifa (){
  
  reutrn  25
  
  
}
//Feature Input select2
(function ($) {

    var Defaults = $.fn.select2.amd.require('select2/defaults');

    $.extend(Defaults.defaults, {
        searchInputPlaceholder: ''
    });

    var SearchDropdown = $.fn.select2.amd.require('select2/dropdown/search');

    var _renderSearchDropdown = SearchDropdown.prototype.render;

    SearchDropdown.prototype.render = function (decorated) {

        // invoke parent method
        var $rendered = _renderSearchDropdown.apply(this, Array.prototype.slice.apply(arguments));

        this.$search.attr('placeholder', this.options.get('searchInputPlaceholder'));
        $(document).on('select2:open', (e) => {
            var id = e.target.id
            document.querySelector('.select2-search__field[aria-controls=select2-' + id + '-results').focus();
        });

        return $rendered;
    };

})(window.jQuery);
//End Feature Input select2
class Noodle {
  
  double lengthInCentimeters;
  double widthInCentimeters;
  String shape;
  String ingredients;
  String texture = "brittle";
  
  Noodle(double lenInCent, double wthInCent, String shp, String ingr) {
    
    this.lengthInCentimeters = lenInCent;
    this.widthInCentimeters = wthInCent;
    this.shape = shp;
    this.ingredients = ingr;
    
  }
  
  public void cook() {
    
    this.texture = "cooked";
    
  }
  
  public static void main(String[] args) {
    
    Pho phoChay = new Pho();
    System.out.println(phoChay.shape);
    
  }
  
}

// next file

class Pho extends Noodle {
  
  Pho() {
    
    super(30.0, 0.64, "flat", "rice flour");
    
  }
  
}
class Noodle {
  
  double lengthInCentimeters;
  String shape;
  String texture = "brittle";
  
  public void cook() {
    
    this.texture = "cooked";
    
  }
  
  public static void main(String[] args) {
    Spaghetti spaghettiPomodoro = new Spaghetti(); 
    System.out.println(spaghettiPomodoro.texture);
  }
  
}
//next file

class Spaghetti extends Noodle{
  
}
interface CounterProps {
  num: number;
  setNum: React.Dispatch<React.SetStateAction<number>>;
}

const Counter: React.FC<CounterProps> = ({ num, setNum }) => {
  const handleClick = () => {
    setNum(num + 1);
  };

  return (
    // jsx codes...
  );
};
public class ATM{
  // Static variables
  public static int totalMoney = 0;
  public static int numATMs = 0;

  // Instance variables
  public int money;

  public ATM(int inputMoney){
    this.money = inputMoney;
    numATMs += 1;
    totalMoney += inputMoney;
  }

  public void withdrawMoney(int amountToWithdraw){
    if(amountToWithdraw <= this.money){
      this.money -= amountToWithdraw;
      totalMoney -= amountToWithdraw;
    }
  }

  // Write your averageMoney() method here

  public static void averageMoney(){
    System.out.println(totalMoney / numATMs);
    System.out.println(this.money);
  }

  public static void main(String[] args){

    System.out.println("Total number of ATMs: " + ATM.numATMs); 
    ATM firstATM = new ATM(1000);
    ATM secondATM = new ATM(500);
    System.out.println("Total number of ATMs: " + ATM.numATMs); 

    System.out.println("Total amount of money in all ATMs: " + ATM.totalMoney);  
    firstATM.withdrawMoney(500);
    secondATM.withdrawMoney(200);
    System.out.println("Total amount of money in all ATMs: " + ATM.totalMoney);    

    // Call averageMoney() here
    ATM.averageMoney();
  }

}
public class ATM{
  // Static variables
  public static int totalMoney = 0;
  public static int numATMs = 0;

  // Instance variables
  public int money;

  public ATM(int inputMoney){
    this.money = inputMoney;

    // Steps 1 and 2: Edit numATMs and total money here
    numATMs += 1;
    totalMoney += inputMoney;
  }

  public void withdrawMoney(int amountToWithdraw){
    if(amountToWithdraw <= this.money){
      this.money -= amountToWithdraw;
      // Step 3: Edit totalMoney here
      totalMoney -= amountToWithdraw;
    }
  }

  public static void main(String[] args){

    System.out.println("Total number of ATMs: " + ATM.numATMs); 
    ATM firstATM = new ATM(1000);
    ATM secondATM = new ATM(500);
    System.out.println("Total number of ATMs: " + ATM.numATMs); 

    System.out.println("Total amount of money in all ATMs: " + ATM.totalMoney);  
    firstATM.withdrawMoney(500);
    secondATM.withdrawMoney(200);
    System.out.println("Total amount of money in all ATMs: " + ATM.totalMoney);    



  }

}
public class ATM{

  // Step 2: Create your static variables here
public static int totalMoney = 0;
public static int numATMs = 0;
  // Instance variables
  public int money;

  public ATM(int inputMoney){
    this.money = inputMoney;
  }

  public void withdrawMoney(int amountToWithdraw){
    if(amountToWithdraw <= this.money){
      this.money -= amountToWithdraw;
    }
  }

  public static void main(String[] args){
    // Step 1: Create your two ATMs here
  ATM firstATM = new ATM(1000);
  ATM secondATM = new ATM(500);
    // Step 3: Print your static variable in three different ways here
    System.out.println(ATM.totalMoney);
    System.out.println(firstATM.totalMoney);
    System.out.println(secondATM.totalMoney);
  }

}
public class Bank{
  private CheckingAccount accountOne;
  private CheckingAccount accountTwo;

  public Bank(){
    this.accountOne = new CheckingAccount("Zeus", 100, "1");
    this.accountTwo = new CheckingAccount("Hades", 200, "2");
  }

  public static void main(String[] args){
    Bank bankOfGods = new Bank();
    bankOfGods.accountOne.getAccountInformation();
    bankOfGods.accountOne.calculateNextMonthInterest();
  }

}

//next page
public class CheckingAccount{
  private String name;
  private int balance;
  private String id;
  private double interestRate;

  public CheckingAccount(String inputName, int inputBalance, String inputId){
    this.name = inputName;
    this.balance = inputBalance;
    this.id = inputId;
    this.interestRate = 0.02;
  }

  public void getAccountInformation(){
    System.out.println("Money in account: " + this.getBalance());
    System.out.println("Next Month's Interest: " + this.calculateNextMonthInterest());

  }

  private int getBalance(){
    return this.balance;
  }

  // Write the calculateNextMonthInterest() here
  private double calculateNextMonthInterest(){
    return this.interestRate * this.balance;
  }

}
public class Person{
  public int age;
  public int wisdom;
  public int fitness;

  public Person(int inputAge){
    this.age = inputAge;
    this.wisdom = inputAge * 5;
    this.fitness = 100 - inputAge;
  }

  public void setAge(int newAge){
    this.age = newAge;
  }

  public void setWisdom(int newWisdom){
    this.wisdom = newWisdom;
  }

  public void setFitness(int newFitness){
    this.fitness = newFitness;
  }

  public void hasBirthday(){
    //Complete this method
    this.setAge(this.age + 1);
    this.setWisdom(this.wisdom + 5);
    this.setFitness(this.fitness - 3);
  }

  public static void main(String[] args){
    Person emily = new Person(20);
    emily.hasBirthday();
    System.out.println("New age is: " + emily.age);
    System.out.println("New wisdom is: " + emily.wisdom);
    System.out.println("New fitness is: " + emily.fitness);
  }
}
public class SavingsAccount{

  public String owner;
  public int balanceDollar;
  public double balanceEuro;

  public SavingsAccount(String owner, int balanceDollar){
    // Complete the constructor
    this.owner = owner;
    this.balanceDollar = balanceDollar;
    this.balanceEuro = balanceDollar * 0.85;

  }

  public void addMoney(int balanceDollar){
    // Complete this method
    System.out.println("Adding " + balanceDollar + " dollars to the account.");
    this.balanceDollar += balanceDollar;
    System.out.println("The new balance is " + this.balanceDollar + " dollars.");
  }

  public static void main(String[] args){
    SavingsAccount zeusSavingsAccount = new SavingsAccount("Zeus", 1000);

    // Make a call to addMoney() to test your method
    zeusSavingsAccount.addMoney(2000);

  }

}
public class Bank{
  private CheckingAccount accountOne;
  private CheckingAccount accountTwo;

  public Bank(){
    accountOne = new CheckingAccount("Zeus", 100, "1");
    accountTwo = new CheckingAccount("Hades", 200, "2");
  }

  public static void main(String[] args){
    Bank bankOfGods = new Bank();
    bankOfGods.accountOne.setBalance(5000);
    System.out.println(bankOfGods.accountOne.getBalance());
  }

}

//other file with private classes
public class CheckingAccount{
  private String name;
  private int balance;
  private String id;

  public CheckingAccount(String inputName, int inputBalance, String inputId){
    name = inputName;
    balance = inputBalance;
    id = inputId;
  }

  //Write new methods here:
    public int getBalance() {
    return balance;
  }

    public void setBalance(int newBalance) {
    balance = newBalance;
  }



}
function elMax(){
let max = Math.max(4,987,8,9,4,87,85,26);
return max;
}
elMax()
let a = prompt('sonni kirit'), b = prompt('sonni kirit'), sum = 0;
function summ(a, b){
return sum = a + b;
}
summ(a-0,b-0)
const loading = `<div class="spinner spinner-border text-white" role="status">
                <span class="sr-only">Loading...</span>
            </div> Loading`

beforeSend: function () {
    $("#btn-submit").html(loading);
    $("#btn-submit").attr('disabled', true);
},
success: function (response) {
  $("#btn-submit").removeAttr('disabled');
  $("#btn-submit").html("Proses");
}
$(document).on("click", '#detail-score', function() {
    localStorage.setItem("typeStage", 'Diagnostik');
    localStorage.setItem("titleStage", $(this).data('titlestage'));
    window.location.href = '/teacher/games-coordinator/akm/diagnostic/unit/' + roundId;
});
const hexToRgb = hex =>
  hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i
             ,(m, r, g, b) => '#' + r + r + g + g + b + b)
    .substring(1).match(/.{2}/g)
    .map(x => parseInt(x, 16))

console.log(hexToRgb("#0033ff")) // [0, 51, 255]
console.log(hexToRgb("#03f")) // [0, 51, 255]
public class DNA {
 
  public static void main(String[] args) {
 
    //  -. .-.   .-. .-.   .
    //    \   \ /   \   \ / 
    //   / \   \   / \   \  
    //  ~   `-~ `-`   `-~ `-
 String dna1 = "ATGCGATACGCTTGA";
 String dna2 = "ATGCGATACGTGA";
 String dna3 = "ATTAATATGTACTGA";
 
 String dna = dna3;
 //System.out.println(dna.length());

int start = dna.indexOf("ATG");
int end = dna.indexOf("TGA");


 if (start != -1 && end != -1 && (end - start) % 3 == 0){
   System.out.println("Condition 1, 2 and 3 are satisfied.");

   String protein = dna.substring(start, end+3);
   //+3 is because int end cuts off at where TGA begins
   System.out.println("Protein: " + protein);
 }else{
   System.out.println("No protein.");
 }
  }
 
}
public class Hashtag {
  
  public static void main(String[] args) {
    
    String hashtag = "#100DaysOfCode";
    
    // Make the hashtag lowercase:
    
    System.out.println(hashtag.toLowerCase());

    System.out.println(hashtag.toUpperCase());
    
  }
  
}
public class Poetry {
  
	public static void main(String[] args) {
      
    String line = "The Heav'ns and all the Constellations rung";     
    // Change the arguments:
    System.out.println(line.substring(4, 11));
    System.out.println(line.substring(24));
  }
  
}
public class Initials {
  
	public static void main(String[] args) {
    
    // Add a first name and a last name:
    String firstName = "Cash";  
    String lastName = "Carti";
    
    // What are the initials?
    System.out.println(firstName.charAt(0));
    System.out.println(lastName.charAt(0));
  }
  
}
public class MorseCode {
  
  public static void main(String[] args) {
    
    String code = ".... .. / .. .----. -- / ... --- -. -. -.-- / .- -. -.. / .. / .-.. .. -.- . / - --- / . .- - / .-. .- -- . -.";

    // Write the code:
    
    System.out.println(code.indexOf(". .- -"));
  }
  
}
public class Password {
  
  public static void main(String[] args) {
    
    String password = "IgotTheKEYS";
    
    // Write the code:
    System.out.println(password.equals("Mango"));
    System.out.println(password.equals("IgotTheKEYS"));
    System.out.println(password.equals("igotthekeys"));
    //compares two strings without considering upper/lower cases.
    System.out.println(password.equalsIgnoreCase("igotthekeys"));
  }
  
}
public class CombineNames {
  
	public static void main(String[] args) {
    
    // Add your first names:
    String firstName = "Cash";  
    String lastName = "Carti";

    // What's the full name?
  System.out.println(firstName.concat(" " + lastName));
  }
  
}
public class TweetCounter {
  


	public static void main(String[] args) {
    
    String tweet = "Liz Lemon, ninjas are kind of cool... I just dont know any personally. Get on that.";  

    // What's the character count?
    
    System.out.println(tweet.length());


  }
  
}
//create a button (layout component) in the object class

//example you want to create a slug based on a field name 'title' (text input)
//to save in the field 'url' (text input)
//click on the button will automatically create the slug

//copy and paste the following code in the button handler
((btn)=>{

//get button id
const id = btn.id
//get button element
const button = document.getElementById(id);
//define the current DataObject as workspace in order to find the elements  
const workspace = '_data_object_name'; //ex. News
  
//find the root element of the record
const root = button.closest('div.pimcore_class_' + workspace);

//find the source input field by name with the value to slugify (in this example 'title')
const source = root.querySelector('input[name="title"]');
//find the targe input field by name with the slugified value (in this example 'url')  
const target = root.querySelector('input[name="url"]');

//set the target value with the slugified value
target.value = slugify(source.value);

function slugify(str)
{
    str = str.replace(/^\s+|\s+$/g, '');

    // Make the string lowercase
    str = str.toLowerCase();

    // Remove accents, swap ñ for n, etc
    var from = "ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆÍÌÎÏŇÑÓÖÒÔÕØŘŔŠŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšťúůüùûýÿžþÞĐđ߯a·/_,:;";
    var to   = "AAAAAACCCDEEEEEEEEIIIINNOOOOOORRSTUUUUUYYZaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbBDdBAa------";
    for (var i=0, l=from.length ; i<l ; i++) {
        str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
    }

    // Remove invalid chars
    str = str.replace(/[^a-z0-9 -]/g, '') 
    // Collapse whitespace and replace by -
    .replace(/\s+/g, '-') 
    // Collapse dashes
    .replace(/-+/g, '-'); 

    return str;
}
});
// Import statement:
import java.util.ArrayList;
class PrimeDirective {
  
  // Add your methods here:
  public static boolean isPrime(int number){
    if(number>1){
      for(int i=2; i < number; i++){
        if (number % i == 0){
          return false;
        }
      }return true;
    }else{
      return false;
    }
  }

  public ArrayList<Integer> onlyPrimes(int[] numbers){
    ArrayList<Integer> primes = new ArrayList<Integer>();
    for(int i : numbers){
      if(isPrime(i) == true){
        primes.add(i);
      }
    }
    return primes;
  }
  
  public static void main(String[] args) {

    PrimeDirective pd = new PrimeDirective();
    int[] numbers = {2,3,47,6, 29, 28, 33, 11, 100, 101, 43, 89};

    System.out.println(isPrime(7));
    System.out.println(isPrime(28));
    System.out.println(isPrime(2));
    System.out.println(isPrime(0));

System.out.println(pd.onlyPrimes(numbers));


  }  

}
public class FizzBuzz{

  public static void main(String[] args){

for (int i = 1; i<= 100; i++){

  if((i %3 == 0) && (i %5 == 0)){
    System.out.println("FizzBuzz");
  }else if (i %5 == 0){
     System.out.println("Buzz");
  } else if(i %3 == 0){
    System.out.println("Fizz");
  }else{
  System.out.println(i);
  }
    
     
  }
}


  }
const puppeteer = require('puppeteer-extra')
const pluginStealth = require('puppeteer-extra-plugin-stealth')
puppeteer.use(pluginStealth())


async function main() {
    const browser = await puppeteer.launch({
        headless: false,
        defaultViewport: null,
        executablePath: 'C:\\c-dev\\chrome.exe'
    })
    const [page] = await browser.pages()
    await page.goto('https://www.monotaro.id/s000009132.html', {timeout: 0, waitUntil: 'domcontentloaded'})
    await page.waitForSelector('#product-attribute-specs-table', {timeout: 0})
    const berat = await page.evaluate(() => {
        let b = 0
        const selector_head = '#product-attribute-specs-table tbody tr:nth-child({}) th'
        const selector_body = '#product-attribute-specs-table tbody tr:nth-child({}) td'
        let i = 1
        document.querySelectorAll('#product-attribute-specs-table tbody tr').forEach(el => {
            const data = {
                name: document.querySelector(selector_head.replace('{}', i)).innerText,
                value: document.querySelector(selector_body.replace('{}', i)).innerText
            }
            if(data.name == 'Berat (Kg)') b = data.value.match(/^[0-9]*\.?[0-9]*$/)[0]
            i+=1
        })
        return b
    })
    console.log(berat)
}

main()
Answer
I installed the last version of vue-cli which have a "public" folder. I also installed "vue-3d-model" by hujiulong and now it's working fine! :D

I don't know what was the issue, maybe Vue have restricted permission without a public folder ?
import java.util.ArrayList;

class Lunch {
 
  public static ArrayList<String> removeAnts(ArrayList<String> lunchBox) {
    // Add your code below
  
    for (int i = 0; i < lunchBox.size(); i++) {
      if (lunchBox.get(i) == "ant"){
        lunchBox.remove(lunchBox.get(i));
        i--;    
      }
    }

   /*
    // Using a while loop
    int i = 0; 
    while (i < lunchBox.size()) {
      if (lunchBox.get(i) == "ant"){
        lunchBox.remove(lunchBox.get(i));
      } else {
        i++;
      }
    }
   */

    return lunchBox;
  }
 
  
  public static void main(String[] args) {
    ArrayList<String> lunchContainer = new ArrayList<String>();
    lunchContainer.add("apple");
    lunchContainer.add("ant");
    lunchContainer.add("ant");
    lunchContainer.add("sandwich");
    lunchContainer.add("ant");
    lunchContainer = removeAnts(lunchContainer);
    System.out.println(lunchContainer);

  }
}
import java.util.ArrayList;

class MostExpensive {
  
  public static void main(String[] args) {
    
    ArrayList<Double> expenses = new ArrayList<Double>();
    expenses.add(74.46);
    expenses.add(63.99);
    expenses.add(10.57);
    expenses.add(81.37);
    
    double mostExpensive = 0;
    
    // Iterate over expenses
    for (double expense : expenses) {
      
      if (expense > mostExpensive) {
        mostExpensive = expense;
      }
      
    }
    
    System.out.println(mostExpensive);
    
  }
  
}
const colors = [
  { 'red': '#f00' },
  { 'green': '#0f0' },
  { 'blue': '#00f' }
];

$.each(colors, function() {
  $.each(this, function(name, value) {
    console.log(`${name} = ${value}`);
  });
});

This example outputs:

red = #f00
green = #0f0
blue = #00f




const numbers = [1, 2, 3, 4, 5];
$.each(numbers, function(index, value){
  console.log(`${index}: ${value}`);
});



This snippet outputs:

0:1
1:2
2:3
3:4
4:5


FUNCION EACH CON CLASES


<div class="productDescription">Red</div>
<div>Pink</div>
<div class="productDescription">Orange</div>
<div class="generalDescription">Teal</div>
<div class="productDescription">Green</div>

$.each($('.productDescription'), function(index, value) {
  console.log(index + ':' + $(value).text());
});


In this case, the output is:

0:Red
1:Orange
2:Green



No tenemos que incluir índice y valor. Estos son solo parámetros que ayudan a determinar en qué elemento DOM estamos iterando actualmente. Además, en este escenario también podemos utilizar el eachmétodo más conveniente. Podemos escribirlo así:

$('.productDescription').each(function() {
  console.log($(this).text());
});
Ahorrar
Y obtendremos esto en la consola:

Red
Orange
Green




<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>each demo</title>
  <style>
  ul {
    font-size: 18px;
    margin: 0;
  }
  span {
    color: blue;
    text-decoration: underline;
    cursor: pointer;
  }
  .example {
    font-style: italic;
  }

  </style>
  <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
 
To do list: <span>(click here to change)</span>
<ul>
  <li>Eat</li>
  <li>Sleep</li>
  <li>Be merry</li>
</ul>
 
<script>
$( "span" ).click(function() {
  $( "li" ).each(function() {
    $( this ).toggleClass( "example" );
  });
});
</script>
 
</body>
</html>




La función each() en jQuery itera a través de objetos y matrices. Las matrices que tienen la propiedad de longitud se recorren desde el índice 0 hasta la longitud-1 y mientras que las matrices como los objetos se recorren a través de sus nombres de propiedades.

Sintaxis:

$.each('matriz u objeto', función(índice, valor){
  // Tu codigo
})


<!DOCTYPE html>
<html lang="en">
  
<head>
    <!-- using jquery library -->
    <script src=
"https://code.jquery.com/jquery-git.js">
    </script>
</head>
  
<body>
  <script>
    let arr = [10, 20, 30, 40, 50];
    $.each(arr, function (index, value) {
        document.write(index + ": " + value + "<br>");
    });
  </script>
</body>
  
</html>



FUNCION EACH() UTILIZADA CON ELEMENTO DEL DOM

<!DOCTYPE html>
<html lang="en">

<head>
	<!-- using jquery library -->
	<script src=
"https://code.jquery.com/jquery-git.js">
	</script>
</head>

<body>
	<p>para-1</p>
	<p>para-2</p>
	<p>para-3</p>
	<p>para-4</p>
	<p>para-5</p>
	<script>
		$("p").each(function (index) {
			console.log(index
				+ ": " + $(this).text());
		});
	</script>
</body>

</html>

class Numbers {
  public static void main(String[] args) {
    for (int i = 0; i < 100; i++) {
      // Add your code below
if (i % 5 != 0) {
    continue;
  }
  System.out.println(i);

      
    }
  }
}
    
import java.util.ArrayList;

class CalculateTotal {
  
  public static void main(String[] args) {
    
    ArrayList<Double> expenses = new ArrayList<Double>();
    expenses.add(74.46);
    expenses.add(63.99);
    expenses.add(10.57);
    expenses.add(81.37);
    
    double total = 0;
    
    // Iterate over expenses
    for (int i = 0; i < expenses.size(); i++) {
      
      total += expenses.get(i);
      
    }
    
    System.out.println(total);
    
  }
  
}
class Coffee {
  
  public static void main(String[] args) {
    
    for (int cupsOfCoffee = 1; cupsOfCoffee <= 100; cupsOfCoffee++) {
      
      System.out.println("Fry drinks cup of coffee #" + cupsOfCoffee);
       
    }
    
  }
  
}
class Coffee {
  
  public static void main(String[] args) {
    
    // initialize cupsOfCoffee
    int cupsOfCoffee = 1;
    // add while loop with counter
    while(cupsOfCoffee <= 100){
      cupsOfCoffee++;
      System.out.println("Fry drinks cup of coffee #"+cupsOfCoffee);
    }
        
    
  }
  
}
// Importing the Random library
import java.util.Random;

class LuckyFive {
  
  public static void main(String[] args) {
    
    // Creating a random number generator
    Random randomGenerator = new Random();
    
    // Generate a number between 1 and 6
    int dieRoll = randomGenerator.nextInt(6) + 1;

    // Repeat while roll isn't 5
    while (dieRoll != 5) {
 System.out.println(dieRoll);
  dieRoll =5;

}
    
  }
  
}
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("URLs");
sheet.appendRow(ficUrls.flat());
function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}
import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [state, setState] = useState({
    email: "",
    password: ""
  });

  const handleInputChange = (event) => {
    const { name, value } = event.target;
    setState((prevProps) => ({
      ...prevProps,
      [name]: value
    }));
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log(state);
  };

  return (
    <div className="App">
      <form onSubmit={handleSubmit}>
        <div className="form-control">
          <label>Email</label>
          <input
            type="text"
            name="email"
            value={state.email}
            onChange={handleInputChange}
          />
        </div>
        <div className="form-control">
          <label>Password</label>
          <input
            type="password"
            name="password"
            value={state.password}
            onChange={handleInputChange}
          />
        </div>
        <div className="form-control">
          <label></label>
          <button type="submit">Login</button>
        </div>
      </form>
    </div>
  );
}
fetch('api link')
.then(res => res.join())
.then(data => console.log(data))

//data is your api data so you can map over it etc 
const express = require('express');
const cors = require('cors');

// env
const port = process.env.PORT || 3000;

// server
const app = express();

app.use(cors());

// routes
app.get('/', (req, res) => {
    res.send('Hello World!');
});

// start
app.listen(port, () => {
    console.log(`Example app listening on port ${port}`);
});



///////////////////////////////////////////
// https
/*
npm install -g mkcert
mkcert create-ca
mkcert create-cert

const https = require("https");
const fs = require("fs");

const options = {
    key: fs.readFileSync("./config/cert.key"),
    cert: fs.readFileSync("./config/cert.crt"),
};
https.createServer(options, app).listen(8080, () => {
    console.log(`HTTPS server started on port 8080`);
});

*/
//regular way
function reverseString(text) {
    return text.split("").reverse().join("")
}

reverseString('reversedString')

document.designMode = 'on'
const test = [
    { nation: { name: "Germany", iso: "DE", rankingPoints: 293949 } },
    { nation: { name: "Hungary", iso: "HU", rankingPoints: 564161 } },
    { nation: { name: "Serbia", iso: "SR", rankingPoints: 231651 } }
];    

const sorted = test.sort((a, b) => a.nation.rankingPoints - b.nation.rankingPoints);

// Using forEach:

var dict = {}
sorted.forEach((el, index) => dict[el.nation.iso] = sorted.length - index);

// Using reduce:

dict = sorted.reduce(
    (dict, el, index) => (dict[el.nation.iso] = sorted.length - index, dict),
    {}
);

console.log(dict)
console.log("dict['DE'] = ", dict['DE'])
this.filters = this.filters.reduce((result, filter) => {
    result[filter.name] = filter.value;
    return result;
},{});
//-^----------- here
"styles": [
  "styles.css",
  "../node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
  "../node_modules/jquery/dist/jquery.slim.min.js",
  "../node_modules/bootstrap/dist/js/bootstrap.min.js",
  "../node_modules/popper.js/dist/umd/popper.min.js"
],
let list = [
  {
    id: "27",
    order_number: "21251",
    tel: 13911111,
    weight: "10kg"
  },
  {
    id: "245",
    order_number: "223",
    tel: 31,
    weight: "10kg"
  },
  {
    id: "123",
    order_number: "312312321",
    tel: 3213123,
    weight: "10kg"
  }
];
let new_list = list.map(function(obj) {
  return {
    id: obj.id,
    order_number: obj.order_number,
    weight: obj.weight
  }
});

console.log(list);
console.log(new_list)
After the Ethereum Merge Event, Ethereum has become more admired in the crypto industry. Meantime, the price of ethereum has skyrocketed. Do you wanna create an ethereum standard token? https://bit.ly/3TlCuwx 

Being the trusted Ethereum Token Development Company that rendering excellent Token Development Services on multiple ethereum standards such as ERC20, ERC1155, ERC223, ERC721, ERC777, ERC827, ERC 998, and ERC1400 to enhance your tokenomics business and platform.

For Instant Connect, 
Whatsapp +91 9384587998 || Telegram @maticzofficial

if(SDB.App.exists('body:not(.fl-builder-edit) #cc-counter')){
76
                    var a = 0;
77
                    $(window).scroll(function() {
78
​
79
                      var oTop = $('#cc-counter').offset().top - window.innerHeight;
80
                      if (a == 0 && $(window).scrollTop() > oTop) {
81
                        $('.counter-value').each(function() {
82
                          var $this = $(this),
83
                            countTo = $this.attr('data-count');
84
                          $({
85
                            countNum: $this.text()
86
                          }).animate({
87
                              countNum: countTo
88
                            },
89
​
90
                            {
91
​
92
                              duration: 2000,
93
                              easing: 'swing',
94
                              step: function() {
95
                                $this.text(Math.floor(this.countNum));
96
                              },
import { useHistory } from "react-router-dom";

function HomeButton() {
  const history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}
    <div className="layout">
      {
        React.Children.map(children, (child) => {
          return React.cloneElement(child, {
            props1: 1,
            props2: 2,
          });
        })
      }
    </div>
// assignment/get-api

// Problem 1 Create an API for GET /movies that returns a list of movies. Define an array of movies in your code and return the value in response.
const movies = [
  "Top Gun: Maverick",
  "Doctor Strange in the Multiverse of Madness",
  "Jurassic World Dominion",
  "The Batman",
  "Minions: The Rise of Gru",
  "Thor: Love and Thunder",
  "Sonic the Hedgehog 2",
  "Elvis",
  "Uncharted Sony",
];
const color = [
  "#fcba03",
  "#62fc03",
  "#03fce3",
  "#035efc",
  "#8003fc",
  "#f403fc",
  "#fc034e",
  "#03fc3d",
  "#fceb03",
];
router.get("/movies", (req, res) => {
  res.write(`<div style="color:blue;text-align:center;" >`);
  movies.forEach((each, i) => {
    res.write(`<h1 style="color:${color[i]};" >${each}<h1/>`);
  });
  res.write(`<div/>`);
  res.end();
});

//Problem=2 Create an API GET /movies/:indexNumber (For example GET /movies/1 is a valid request and it should return the movie in your array at index 1). You can define an array of movies again in your api

router.get("/movies/:ind", (req, res) => {
  const i = Number(req.params.ind);
  if (i < movies.length && typeof i === "number") {
    res.write(`<h1 style="color:${color[i]};" >${movies[i]}<h1/>`);
  } else {
    res.send("Not a valid request");
  }
});

//Problem 4== Write another api called GET /films. Instead of an array of strings define an array of movie objects this time. Each movie object should have values - id, name.

const filemsArr = [];
for (let i = 0; i < movies.length; ++i) {
  filemsArr.push({
    id: i + 1,
    Movie: movies[i],
    Color: color[i],
  });
} 

router.get("/films", (req, res) => {
  res.write(`<div style="color:blue;text-align:center;" >`);
  filemsArr.forEach((each) => {
    res.write(
      `<h1 style="color:${each.Color};" >${each.id}--> ${each.Movie}<h1/>`
    );
  });
  res.write(`<div/>`);
  res.end();
});

//Problem 5 == Write api GET /films/:filmId where filmId is the value received in request path params. Use this value to return a movie object with this id. In case there is no such movie present in the array, return a suitable message in the response body.

router.get("/films/:id", (req, res) => {
  const i = Number(req.params.id);
  if (i < movies.length && typeof i === "number") {
    res.write(
      `<h1 style="color:${filemsArr[i].Color};" > id: ${filemsArr[i].id} ==> ${filemsArr[i].Movie}<h1/>`
    );
  } else {
    res.send("No movie exists with this id");
  }
});
//JavaScript
$(document).ready(function() {
  var playing = false;

  // Add file names.
  $('.audio-button').each(function() {
    var $button = $(this);    
    var $audio = $button.find('audio');
    
    $($('<span>').text($audio.attr('src'))).insertBefore($audio);
  });

  // Add click listener.
  $('.audio-button').click(function() {
    var $button = $(this);    
    var audio = $button.find('audio')[0]; // <-- Interact with this!
    
    // Toggle play/pause
    if (playing !== true) {
      audio.play();
    } else {
      audio.pause();
    }

    // Flip state
    $button.toggleClass('playing');
    playing = !playing
  });
});


// CSS
.fa.audio-button {
  position:      relative;
  display:       block;
  width:         12em;
  height:        2.25em;
  margin-bottom: 0.125em;
  text-align:    left;
}

.fa.audio-button:after {
  position:      absolute;
  right:         0.8em;
  content:       "\f04b";
}

.fa.audio-button.playing:after {
  content:"\f04c";
}

// HTML
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="fa audio-button">
  <audio src="media/test.mp3"></audio>
</button>
<button class="fa audio-button">
  <audio src="media/test2.mp3"></audio>
</button>
<button class="fa audio-button">
  <audio src="media/test3.mp3"></audio>
</button>
<button class="fa audio-button">
  <audio src="media/test4.mp3"></audio>
</button>
const prices = [2.80, 6.10, 1.50, 1.00, 8.99, 2.99]

function totalCost(prices){
    return prices.reduce((sum, item) => sum + item, 0)
}
function product(array){
    return array.reduce((total, num) => total*num, 1)
}
const pricePerKg = 1.50
const numberOfKg = 10
const conversionRate = 1.16
const conversion = [1.50, 10, 1.16]

const USprice = product([pricePerKg,numberOfKg,conversionRate])
// Bx Slider 

function custom_scripts()
{
    wp_register_script('bxslider', 'https://cdn.jsdelivr.net/bxslider/4.1.1/jquery.bxslider.min.js', array(), false, true);
    wp_enqueue_script('bxslider');
}

add_action('wp_enqueue_scripts', 'custom_scripts');

function bxslider_init() { ?>
    <script>
    (function($){
        $(document).ready(function() {
                $(".image-ticker").show();
                $('.image-ticker').bxSlider({
                    minSlides: 1,
                    maxSlides: 8,
                    slideWidth: 189,
                    slideMargin: 0,
                    ticker: true,
                    speed: 50000
                });
            });
        })(jQuery)   
    </script>
<?php }

add_action ('wp_footer', 'bxslider_init');
const members = [
{gender: 'M', name: 'John'},
{gender: 'M', name: 'Tim'},
{gender: 'F', name: 'Jenny'},
{gender: 'F', name: 'Alice'}
]
findTim = (name) => {
 for(let member of members) {
  if(member.name === name && member.gender === 'M') {
return member.name
} 
// shorthand
member = members.find(member => member.gender === 'M' && member.name === 'Tim');
const person = {
 name: null,
    age: null,
    message: null,
}


<h3>{person?.name ?? 'default Name'}</h3>
<h3>{person?.age ?? 'default age'}</h3>
<h4>{person?.message ?? 'default message'}</h4>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>

<script type="text/javascript">
google.load("elements", "1", {packages: "transliteration"});
</script> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
function OnLoad() {                
    var options = {
        sourceLanguage:
        google.elements.transliteration.LanguageCode.ENGLISH,
        destinationLanguage:
        [google.elements.transliteration.LanguageCode.HINDI],
        shortcutKey: 'ctrl+g',
        transliterationEnabled: true
    };

    var control = new google.elements.transliteration.TransliterationControl(options);
    control.makeTransliteratable(["txtHindi"]);
    var keyVal = 32; // Space key
    $("#txtEnglish").on('keydown', function(event) {
        if(event.keyCode === 32) {
            var engText = $("#txtEnglish").val() + " ";
            var engTextArray = engText.split(" ");
            $("#txtHindi").val($("#txtHindi").val() + engTextArray[engTextArray.length-2]);

            document.getElementById("txtHindi").focus();
            $("#txtHindi").trigger ( {
                type: 'keypress', keyCode: keyVal, which: keyVal, charCode: keyVal
            } );
        }
    });

    $("#txtHindi").bind ("keyup",  function (event) {
        setTimeout(function(){ $("#txtEnglish").val($("#txtEnglish").val() + " "); document.getElementById("txtEnglish").focus()},0);
    });
} //end onLoad function

google.setOnLoadCallback(OnLoad);
</script> 

</head>
    <body>
       English Text: <input size="40" type="text" id="txtEnglish"/> <br/>
       Hindi Text`enter code here` : <input size="40" type="text" id="txtHindi"/> 
</body>
</html>
var equationsPossible = function (equations) {
    const Obj = {};
    for (let i = 97, j = 1; i < 124; ++i){
        const char = String.fromCharCode(i);
        Obj[char] = j++;
    }
    equations.forEach(ele => {
        if (ele[1] === '=') {
            if (Obj[ele[0]] != Obj[ele[3]]) {
                const a = Obj[ele[0]]
                const b = Obj[ele[3]]
                for (const key in Obj) {
                    if (Obj[key] === a) {
                        Obj[key] = b;
                    }
                }
            }
        }
    });
    console.log(Obj);
    for (let i = 0; i < equations.length; ++i){
        if (equations[i][1] === '!') {
           if (Obj[equations[i][0]] === Obj[equations[i][3]]) {
             return false;
           } 
        }
    }
    return true;
};
var threeSumClosest = function (nums, target) {
    /// [4, 0, 5, -5, 3, 3, 0, -4, -5], -2)
    
    let sum = Number.MAX_SAFE_INTEGER;
    let min_diff = Number.MAX_SAFE_INTEGER;
    nums.sort((a, b) => a - b);
    // -5, -5, -4, 0, 0, 3, 3, 4, 5  O(n^2)
    
    for (let i = 0, j = 1, k = nums.length - 1; i < nums.length - 2; ++i){
        while (j < k) {
            const currSum = nums[i] + nums[j] + nums[k];
            const diff = Math.abs(target - currSum);
            if (diff < min_diff) {
                min_diff = diff;
                sum = currSum;
            }
            if (target === currSum) {
                return target;
            } else if (currSum < target) {
                j++;
            } else {
                k--;
            }
        }
        j = i + 2;
        k = nums.length - 1;
    }
    return sum;
};
const reducer = (accumulator, currentValue) => accumulator + currentValue;
[2, 4, 6, 8].reduce(reducer)
// expected output: 20
  let currentYear = (new Date()).getFullYear();
  // year
  const options = [];
  for (let i = 1950; i <= currentYear; i++) {
    options.push(i);
  }

jsx //

<select className='border p-2 border-l-pink-700 mr-2' defaultValue={currentYear} onChange={handleYear} name="year" id="year">
            {
              options.map(option => {
                return <option key={option} value={option}>{option}</option>
              })
            }
          </select>
<script>
    var dob = new Date("12/11/2012");
    //calculate month difference from current date in time
    var month_diff = Date.now() - dob.getTime();
    
    //convert the calculated difference in date format
    var age_dt = new Date(month_diff); 
    
    //extract year from date    
    var year = age_dt.getUTCFullYear();
    
    //now calculate the age of the user
    var age = Math.abs(year - 1970);
    
    //display the calculated age
    document.write("Age of the date entered: " + age + " years");
</script>
https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
const formToJSON_deconstructed = (elements) => {
  // This is the function that is called on each element of the array.
  const reducerFunction = (data, element) => {
    // Add the current field to the object.
    data[element.name] = element.value;

    // For the demo only: show each step in the reducer’s progress.
    console.log(JSON.stringify(data));

    return data;
  };

  // This is used as the initial value of `data` in `reducerFunction()`.
  const reducerInitialValue = {};

  // To help visualize what happens, log the inital value.
  console.log('Initial `data` value:', JSON.stringify(reducerInitialValue));

  // Now we reduce by `call`-ing `Array.prototype.reduce()` on `elements`.
  const formData = [].reduce.call(
    elements,
    reducerFunction,
    reducerInitialValue,
  );

  // The result is then returned for use elsewhere.
  return formData;
};
function cloneGoogleSheet() {
  var destFolder = DriveApp.getFolderById("your_drive_folder_id"); 
  DriveApp.getFileById("your_drive_source_file_id").makeCopy("particular_file_name", destFolder); 
}
//HTML
<section>
  <div>
  	<p>
  		Some Text
    </p>
  </div>
</section>

<button id="toggle-button">Click Me</button>

//CSS
div {
    overflow:hidden;
    transition:height 0.3s ease-out;
    height:auto;
  }

//JS
function collapseSection(element) {
  // get the height of the element's inner content, regardless of its actual size
  var sectionHeight = element.scrollHeight;
  
  // temporarily disable all css transitions
  var elementTransition = element.style.transition;
  element.style.transition = '';
  
  // on the next frame (as soon as the previous style change has taken effect),
  // explicitly set the element's height to its current pixel height, so we 
  // aren't transitioning out of 'auto'
  requestAnimationFrame(function() {
    element.style.height = sectionHeight + 'px';
    element.style.transition = elementTransition;
    
    // on the next frame (as soon as the previous style change has taken effect),
    // have the element transition to height: 0
    requestAnimationFrame(function() {
      element.style.height = 0 + 'px';
    });
  });
  
  // mark the section as "currently collapsed"
  element.setAttribute('data-collapsed', 'true');
}

function expandSection(element) {
  // get the height of the element's inner content, regardless of its actual size
  var sectionHeight = element.scrollHeight;
  
  // have the element transition to the height of its inner content
  element.style.height = sectionHeight + 'px';

  // when the next css transition finishes (which should be the one we just triggered)
  element.addEventListener('transitionend', function(e) {
    // remove this event listener so it only gets triggered once
    element.removeEventListener('transitionend', arguments.callee);
    
    // remove "height" from the element's inline styles, so it can return to its initial value
    element.style.height = null;
  });
  
  // mark the section as "currently not collapsed"
  element.setAttribute('data-collapsed', 'false');
}


document.querySelector('#toggle-button').addEventListener('click', function(e) {
  var section = document.querySelector('div');
  var isCollapsed = section.getAttribute('data-collapsed') === 'true';
    
  if(isCollapsed) {
    expandSection(section)
    section.setAttribute('data-collapsed', 'false')
  } else {
    collapseSection(section)
  }
});
<ul id="birds">
  <li>Orange-winged parrot</li>
  <li class="endangered">Philippine eagle</li>
  <li>Great white pelican</li>
</ul>



<script>
    
const birds = document.querySelectorAll('li');

for (const bird of birds) {
  if (bird.matches('.endangered')) {
    console.log(`The ${bird.textContent} is endangered!`);
  }
}

    </script>
const numbers = [1, 2, 3, 4, 5, 7, 3, 2, 2, 5];
const updated = [...new Set(numbers)]; // result [1, 2, 3, 4, 5, 7]
    let selectColor = '';
    let selectCategory = '';

    const getColor = (metadata) => {
        if (metadata !== undefined) {
            if (metadata.length > 1) {
                selectColor = 'orange';
            } else {
                switch (metadata[0]) {
                    case 'stageEarlyChildhood':
                        selectColor = 'pink';
                        break;
                    case 'stagePrimarySchool':
                        selectColor = 'green';
                        break;
                    case 'stageSecondarySchool':
                        selectColor = 'red';
                        break;
                    case 'stageLearnerNoviceDriver':
                        selectColor = 'blue';
                        break;
                    default:
                        selectColor = 'orange';
                        break;
                }
            }
        }
    };
getColor(object.somevalue.that.has.an.array);
// ./
npx react-native bundle --platform android --dev false --entry-file index.js --verbose --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

// ./android/
./gradlew assembleDebug
/*Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives.*/

function invert(array) {
   return array.map(each=>{
     return each * -1;
   })
}
/*I'm new to coding and now I want to get the sum of two arrays... Actually the sum of all their elements. I'll appreciate for your help.

P.S. Each array includes only integer numbers. Output is a number too.
*/
function arrayPlusArray(arr1, arr2) {
  return [...arr1, ...arr2].reduce((sum, element)=>{
    return sum+= element;
  }, 0)
}
/*if the string contains equal number of uppercase and lowercase letters, convert the string to lowercase.*/

function solve(s){
    //..
  let upperCount = 0;
  for(let i = 0; i < s.length; ++i){
    if(s[i] != s[i].toLowerCase()){
      upperCount++;
      if(upperCount > s.length / 2){
        return s.toUpperCase();
      }
    }
  }
  return s.toLowerCase();
}
/*In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?*/

int makeNegative(int num)
{
  return (num>0)? num*-1:num;
}
/*Your team is writing a fancy new text editor and you've been tasked with implementing the line numbering.

Write a function which takes a list of strings and returns each line prepended by the correct number.

The numbering starts at 1. The format is n: string. Notice the colon and space in between.*/

var number=function(array){
  return array.map((element, index)=>{
    return index + 1 + ": " + element;
  })
}
/*You have an array of non-negative integers. You need to calculate the difference between the 1st biggest number and the 2nd biggest number of the array.*/

function diffBig2(arr) {
  let maxNum = Math.max(arr[0], arr[1]);
    let secondMax = Math.min(arr[0], arr[1]);
    for (let j = 1,i = 2; i < arr.length; ++i, ++j){
        if (arr[i] > maxNum) {
            secondMax = maxNum;
            maxNum = arr[i];
        } else if (arr[i] > secondMax) {
            secondMax = arr[i];
        }
    }
    return maxNum - secondMax;
}
/*JavaScript Arrays support a filter function (starting in JavaScript 1.6). Use the filter functionality to complete the function given. */

function getEvenNumbers(numbersArray){
  return numbersArray.filter(element=>{
    return element%2 === 0
  })
}
/*Description:

Simple, given a string of words, return the length of the shortest word(s).

String will never be empty and you do not need to account for different data types.
*/

function findShort(s){
  let strArr = s.split(" ");
  let minLength = strArr[0].length;
  for(let i = 1; i < strArr.length; ++i){
    minLength = Math.min(minLength, strArr[i].length);
  }
  return minLength;
}
/*
In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.
*/
function highAndLow(numbers){
  // 2147483648
  // ...
  let lo = 2147483648;
  let hi = -2147483648;
  numbers.split(" ").forEach(each=>{
    let num = Number(each);
    lo = Math.min(lo, num);
    hi = Math.max(hi, num);
  })
  return hi.toString() + " " + lo.toString();
}
/*Description:
Filter the number

Oh, no! The number has been mixed up with the text. Your goal is to retrieve the number from the text, can you return the number back to its original state?
Task

Your task is to return a number from a string.
Details

You will be given a string of numbers and letters mixed up, you have to return all the numbers in that string in the order they occur.
*/

var FilterString = function (value) {
  let numberStr = "";
    for (let i = 0; i < value.length; ++i) {
    if (!isNaN(Number(value[i]))) {
        numberStr+= value[i];
    }
  }
  return Number(numberStr);
};
/*Make a function that will return a greeting statement that uses an input; your program should return, "Hello, <name> how are you doing today?".

[Make sure you type the exact thing I wrote or the program may not execute properly]
*/

function greet(name){
  return `Hello, ${name} how are you doing today?`
}
/*
Make multiple functions that will return the sum, difference, modulus, product, quotient, and the exponent respectively.

Please use the following function names:

addition = add

multiply = multiply

division = divide (both integer and float divisions are accepted)

modulus = mod

exponential = exponent

subtraction = subt

Note: All math operations will be: a (operation) b

*/
function add(a,b){
    return a + b;
}

function divide(a,b){
    return a / b;
}

function multiply(a,b){
    return a * b;
}

function mod(a,b){
    return a % b;
}
   
function exponent(a,b){
    return a ** b;
}
    
function subt(a,b){
    return a - b;
}
/*Given a string, write a function that returns the string with a question mark ("?") appends to the end, unless the original string ends with a question mark, in which case, returns the original string.*/

function ensureQuestion(s) {
  return s[s.length-1] === '?'? s : s + '?';
}
/*Given a string, you have to return a string in which each character (case-sensitive) is repeated once.*/

function doubleChar(str) {
  let newStr = "";
  for(let i = 0; i < str.length; ++i){
    newStr+= str[i] + str[i];
  }
  return newStr;
}
// Q. Write a function that checks if a given string (case insensitive) is a palindrome.

function isPalindrome(x) {
  x = x.toLowerCase();
  for(let i = 0, j = x.length - 1; i < x.length; ++i, --j){
    if(x[i] != x[j]){
      return false
    }
  }
  return true;
}
let user = {
  name: "John",
  age: 30
};

// loop over keys-and-values
for (let [key, value] of Object.entries(user)) {
  alert(`${key}:${value}`); // name:John, then age:30
}
chrome.webRequest.onBeforeRequest.addListener(
  function(details) {
    return {cancel: details.url.indexOf("://www.evil.com/") != -1};
  },
  {urls: ["<all_urls>"]},
  ["blocking"]
);
// write your own find and findIndex function

const arrNums = [20, 10, 2, 30, 60, 100, 1, 4, 5];

// find method
const temp = 100;
const findNum = (num) => {
  return num === temp;
};

// find method return the number if availabe else return undefine
if (arrNums.find(findNum)) {
  console.log("found");
} else {
  console.log("Not Found");
}

// findIndexOf method
// find index method return the index of this no if present else return -1
arrNums.findIndex(findNum);

// (Hint: using for loop and if else)

// ======================================================== //

const practiceData = [
  [14, 21, 23, 64],
  [33, 46, 51, 65],
];
const newArr = practiceData.map((each) => {
  return each.map((each) => {
    return each + 1;
  });
});
console.log(newArr);
/**
 * requirement one
 * increment each number by one and output the resultant array using a higher order method and for loop
 * HINT: use nesting
 * solution =  [[15,22,24,65], [34,47,52,66]]
 *
 *
 * requirement two
 * from the above array, create an array of array of even numbers using a higher order method and for loop
 * solution = [[14,64], [46]]
 */

const evenArray = practiceData.map((each) => {
  return each.filter((each) => {
    return each % 2 === 0;
  });
});

console.log(evenArray);

// ======================================================== //

const array = [23, 45, 467, 789, 34, 989, 56];

// problem => return an array such that numbers at odd idex are multiplied by 2
// and numbers at even index are multiplied by 10
const oddEven = array.map((each, index) => {
  return index % 2 ? each * 2 : each * 10;
});

console.log(oddEven);
// ======================================================== //

const carBrands = ["honda", "toyota", "maruti", "tata"];
const carModel = ["city", "innova", "alto", "nano"];

const carObject = {};
for (let i = 0; i < carBrands.length; ++i) {
  carObject[carBrands[i]] = carModel[i];
}
console.log(carObject);
//  using a higher order method, create a carObject variable such that
/**
 *
 * {
 * honda:city,
 * toyota:innova,
 * maruti:alto,
 * tata:nano
 * }
 */

// ======================================================== //

/**
  *  Flattening
 Use the reduce method 
 to “flatten” an array of arrays into a single array that has all the elements of the original arrays.
 
 // result =  [1, 2, 3, 4, 5, 6]
 * 
 * 
 */

const arrays = [[1, 2, 3], [4, 5], [6]];
const newSingleArray = arrays.reduce((old, newA) => {
  return old.concat(newA);
});
console.log(newSingleArray);
// ======================================================== //

/**
 * const countries = ['Finland', 'Denmark', 'Sweden', 'Norway', 'Iceland']
 * return an array with all words converted into uppercase using higher order function
 * const countries = ['FINLAND', 'DENMARK', 'SWEDEN', 'NORWAY', 'ICELAND']
 *
 *
 *
 */
const countries = ["Finland", "Denmark", "Sweden", "Norway", "Iceland"];

const countriesCapt = countries.map((country) => {
  return country.toUpperCase();
});
console.log(countriesCapt);
// ======================================================== //