Snippets Collections
CREATE TABLE team_kingkong.tpap_cybercell_fraud_base2 AS
select upi_txn_id_switch,
    txn_date_switch,
    txn_amount_switch,
    payer_vpa_switch,
    payee_vpa_switch,
    payer_mcc_switch,
    payee_mcc_switch,
    payer_handle,
    payee_handle,
    scope_cust_id,
    merchant_bene_type,
    category,
    payer_mobile_no,
    upi_subtype,
    reporting_date,
    ingestion_date,
    'Cybercell' as source
    from
        (select * from
            (select DISTINCT transaction_id as txnid,
            cast(txn_amount as double) as txn_amount,
            DATE(reporting_date) as reporting_date,
            DATE(dl_last_updated) AS ingestion_date,
            row_number() over(partition by transaction_id) as txn_id_duplicate
            FROM frauds.ppsl_cybercell_snapshot_v3
            where DATE(dl_last_updated) >= DATE'2024-12-01'
            and transaction_id NOT IN ('', ' ', 'NA', 'N.A', '0') and transaction_id is not null) 
        where txn_id_duplicate = 1) b
    inner join
        (select distinct json_extract_scalar(payresultcontext, '$.payMethodResultList[0].extendInfo.payeeVpa') AS payee_vpa,
        transactionid,
        IF(rrncode IS NOT NULL, rrncode, banktxnid) as rrn_pg
        FROM risk_maquette_data_async.pplus_payment_result_prod_async_snapshot_v3
        Where DATE(dl_last_updated) >= DATE'2024-12-01' -- DATE_ADD(CURRENT_DATE, -90)
        and date(gmt_occur_derived) >= DATE'2024-12-01' -- DATE_ADD(CURRENT_DATE, -90)
        and payresult in ('payment_success') and upper(paymethod) in ('UPI')) c
    on b.txnid = c.transactionid
    INNER join
        (
            SELECT * FROM
            (select DISTINCT b.created_on as txn_date_switch
            ,a.txn_id as upi_txn_id_switch
            , a.vpa as payer_vpa_switch
            , b.vpa as  payee_vpa_switch
            , a.amount as txn_amount_switch
            ,a.mcc as payer_mcc_switch
            , b.mcc as payee_mcc_switch
            ,a.handle as payer_handle
            , b.handle as payee_handle
            ,a.scope_cust_id
            ,a.mobile_no as payer_mobile_no
            ,(case when (lower(b.vpa) like '%@paytm%' or lower(b.vpa) like '%@pt%') then 'paytm merchant/bene' else 'others' end) merchant_bene_type
        from switch.txn_participants_snapshot_v3 a
        inner join switch.txn_participants_snapshot_v3 b on a.txn_id = b.txn_id
        where DATE(a.dl_last_updated) >= DATE'2024-12-01' -- DATE_ADD(CURRENT_DATE, -90)
        and b.dl_last_updated >= DATE'2024-12-01' -- DATE_ADD(CURRENT_DATE, -90)
        and a.created_on >= DATE'2024-12-01' -- DATE_ADD(CURRENT_DATE, -90)
        and a.participant_type in ('PAYER') and b.participant_type in ('PAYEE')
        and (lower(a.vpa) like'%@paytm%' or lower(a.vpa) like '%@pt%')) x
    inner join
        (select DISTINCT txn_id, category, rrn
        from switch.txn_info_snapshot_v3
        where DATE(dl_last_updated) >= DATE'2024-12-01' -- DATE_ADD(CURRENT_DATE, -90)
        and DATE(created_on) >= DATE'2024-12-01' -- DATE_ADD(CURRENT_DATE, -90)
        and upper(status) in ('SUCCESS')) f
    on x.upi_txn_id_switch = f.txn_id
    )y
on y.rrn = c.rrn_pg and y.payee_vpa_switch = c.payee_vpa
LEFT JOIN
    (SELECT DISTINCT txnid
    , regexp_replace(cast(json_extract(request, '$.evaluationType') as varchar), '"', '') AS upi_subtype
    , CAST(json_extract_scalar(request, '$.requestPayload.amount') AS DOUBLE) as amount
    , json_extract_scalar(request, '$.requestPayload.payeeVpa') as payeeVpa
    FROM tpap_hss.upi_switchv2_dwh_risk_data_snapshot_v3
    WHERE DATE(dl_last_updated) >= DATE'2024-12-01' 
    AND json_extract_scalar(response, '$.action_recommended') = 'PASS'
    AND json_extract_scalar(request, '$.source') = 'UPI'
    AND (lower(json_extract_scalar(request, '$.requestPayload.payerVpa')) LIKE '%@paytm%'
    or lower(json_extract_scalar(request, '$.requestPayload.payerVpa')) like '%@pt%'))d
on y.upi_txn_id_switch = d.txnid AND y.txn_amount_switch = d.amount AND c.payee_vpa = d.payeeVpa
;
CREATE TABLE team_kingkong.tpap_efrm_fraud_base AS
select DISTINCT
upi_txn_id_switch,
txn_date_switch,
txn_amount_switch,
payer_vpa_switch,
payee_vpa_switch,
payer_mcc_switch,
payee_mcc_switch,
payer_handle,
payee_handle,
scope_cust_id,
merchant_bene_type,
category,
payer_mobile_no,
upi_subtype,
'NA' AS reporting_date,
ingestion_date,
'EFRM' as source
from
       (select txn_id as upi_txn_id
        , DATE(MIN(dl_last_updated)) AS ingestion_date
        , cast(regexp_replace(txn_amount, ',', '') as double) as txn_amount
        -- , payee_vpa
        from frauds.efrm_data_snapshot_v3
        where dl_last_updated >= DATE'2024-12-01'
        GROUP BY 1,3) a
    inner join
        (select DISTINCT DATE(b.created_on) as txn_date_switch,
        a.txn_id as upi_txn_id_switch
        , a.vpa as payer_vpa_switch
        , b.vpa as  payee_vpa_switch
        , CAST(a.amount AS DOUBLE) as txn_amount_switch
        ,a.mcc as payer_mcc_switch
        , b.mcc as payee_mcc_switch
        ,a.handle as payer_handle
        , b.handle as payee_handle
        ,a.scope_cust_id
        ,a.mobile_no as payer_mobile_no
        ,(case when (lower(b.vpa) like '%@paytm%' or lower(b.vpa) like '%@pt%') then 'paytm merchant/bene' else 'others' end) merchant_bene_type
        from switch.txn_participants_snapshot_v3 a
            inner join
        switch.txn_participants_snapshot_v3 b
        on a.txn_id = b.txn_id
        where DATE(a.dl_last_updated) >= DATE'2024-12-01'
        and DATE(b.dl_last_updated) >= DATE'2024-12-01'
        and DATE(a.created_on) >= DATE'2024-12-01'
        and a.participant_type in ('PAYER')
        and b.participant_type in ('PAYEE')
        and (lower(a.vpa) like'%@paytm%' or lower(a.vpa) like '%@pt%')) c
    on a.upi_txn_id = c.upi_txn_id_switch AND a.txn_amount = c.txn_amount_switch --AND a.payee_vpa = c.payee_vpa_switch
    inner join
        (select DISTINCT txn_id, category, CAST(amount AS DOUBLE) AS amount
        from switch.txn_info_snapshot_v3
        where dl_last_updated >= DATE'2024-12-01'
        and created_on >= DATE'2024-12-01' 
        and upper(status) in ('SUCCESS')) e
    on a.upi_txn_id = e.txn_id AND a.txn_amount = e.amount
    LEFT JOIN
        (SELECT DISTINCT txnid
        , regexp_replace(cast(json_extract(request, '$.evaluationType') as varchar), '"', '') AS upi_subtype
        , CAST(json_extract_scalar(request, '$.requestPayload.amount') AS DOUBLE) as amount
        , json_extract_scalar(request, '$.requestPayload.payeeVpa') as payeeVpa
        FROM tpap_hss.upi_switchv2_dwh_risk_data_snapshot_v3
        WHERE DATE(dl_last_updated) >= DATE'2024-12-01' 
        AND json_extract_scalar(response, '$.action_recommended') = 'PASS'
        AND json_extract_scalar(request, '$.source') = 'UPI'
        AND (lower(json_extract_scalar(request, '$.requestPayload.payerVpa')) LIKE '%@paytm%'
        or lower(json_extract_scalar(request, '$.requestPayload.payerVpa')) like '%@pt%'))b
    on a.upi_txn_id = b.txnid AND a.txn_amount = b.amount --AND a.payee_vpa = b.payeeVpa
    ;
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":sunshine: Boost Days - What's On This Week :sunshine:"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n\n Good morning Melbourne,\n\n Hope you all had a relaxing long weekend! Please see what's on for the week below."
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": "Xero Café :coffee:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n :new-thing: *This week we are offering some delicious sweet treats from Via Porta Bakehouse:* \n\n :raspberry: Raspberry & Burnt Financier :cookie:Raisin & Oat Cookies \n\n :milo: *Weekly Café Special:* _Milo Mocha_"
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": " Wednesday, 30th April :calendar-date-12:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": " \n\n :lunch: *Light Lunch*: Provided by *Kartel Catering* from *12pm* in the L3 Kitchen & Wominjeka Breakout Space."
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": "Thursday, 1st May :calendar-date-13:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":breakfast: *Breakfast*: Provided by *Kartel Catering* from *8:30am-10:30am* in the Wominjeka Breakout Space. \n\n :roadshow: *Tableau Roadshow* from 9am in the Fitzgerald Training Room and the Wominjeka Breakout Space!\n :lunch: *Light Lunch* from 12.30pm in the L3 Kitchen & Wominjeka Breakout Space. \n\n "
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": "Friday, 2nd May :calendar-date-2:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "*Social Happy Hour* from 4pm-5.30pm :pizza: :friday_yayday::wine_glass:  "
			}
		},
		{
			"type": "divider"
		}
	]
}
<style>

.elementor-field-type-upload.elementor-field-group.elementor-column.elementor-field-group-file_upload.elementor-col-100 label.elementor-field-label{
    color: #505050;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}


	.elementor-field-type-upload.elementor-field-group.elementor-column.elementor-field-group-file_upload.elementor-col-100 label.elementor-field-label:after{
    content: url(https://wordpress-1405257-5222437.cloudwaysapps.com/wp-content/uploads/2025/02/clapboard-upload-1.png);
}


/* Styling for the upload area */
.elementor-field-type-upload {
    border: 1px dashed #69727d;
    padding: 10px 20px !important;
    text-align: center;
    background-color: #F4F7FF;
    cursor: pointer;
    border-radius: 10px;
    margin: 5px;
}

.elementor-field-type-upload:hover {
    background-color: #79c14f24;
}

.elementor-field-type-upload input[type="file"] {
    display: none;
}


/* Styling for the uploaded files grid */
.uploaded-files-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); /* Ensure multiple columns */
    gap: 10px;
    margin-top: 20px;
    border-radius: 10PX;
    width: 100%; /* Ensure the grid takes up full width of its container */
}

/* Ensures that individual items in the grid are aligned correctly */
.uploaded-file-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 8px;
    background-color: #fff;
    position: relative;
}


/* Styling for the file icons */
.uploaded-file-item img {
    width: 50px;
    height: 50px;
    margin-bottom: 10px;
    object-fit: cover;
}

/* Limit text under file to two lines */
.uploaded-file-item span {
    font-size: 12px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 80px;
    display: block;
    text-align: center;
}

/* Button to delete a file */
.delete-file-btn {
    height: 20px !important;
    width: 20px !important;
    padding: 0;
    color: white;
    background: #ef0d0d;
    border-radius: 100px;
    border: none;
		line-height: 0;
    position: relative;
		right: -70px;
    top: -18px;
}



/* Styling for the progress wrapper */
.progress-wrapper {
    width: 100%;
    margin-top: 10px;
}

/* Styling for the success icon */
.success-icon {
    width: 30px;
    height: 30px;
    max-width: 30px;
    max-height: 30px;
    margin-top: 10px;
    display: block;
    margin-left: auto;
    margin-right: auto;
    object-fit: contain!important;
    opacity: 0;  /* Initially hidden */
}

/* Styling for the progress wrapper */
.progress-wrapper {
    width: 100%;
    margin-top: 10px;
}

/* Styling for the progress bar */
progress {
    width: 100%;
    height: 10px;
    border-radius: 5px;
    background-color: #f0f0f0;
    border: 1px solid #ccc;
}

/* Optional: styling for the progress bar when it's filling */
progress::-webkit-progress-bar {
    background-color: #f0f0f0;
}

progress::-webkit-progress-value {
    background-color: #14A2DD;
}

</style>


<script>
document.addEventListener('DOMContentLoaded', function() {
  // Global array to store all selected files
  let allFiles = [];
  // Global array to track file names that have been displayed in the UI
  let displayedFiles = [];

  // Initialize the upload area and file input field
  const uploadArea = document.querySelector('.elementor-field-type-upload');
  const fileInput = document.querySelector('#form-field-file_upload');
  const fileList = document.createElement('div');
  fileList.classList.add('uploaded-files-grid');
  // uploadArea.appendChild(fileList);

  // Drag and drop event listeners
  uploadArea.addEventListener('dragover', (e) => {
    e.preventDefault();
    uploadArea.style.backgroundColor = '#79c14f24';
  });
  uploadArea.addEventListener('dragleave', () => {
    uploadArea.style.backgroundColor = '#f9f9f9';
  });
  uploadArea.addEventListener('drop', (e) => {
    e.preventDefault();
    uploadArea.style.backgroundColor = '#f9f9f9';
    handleFiles(e.dataTransfer.files);
  });

  // Input change event listener
  fileInput.addEventListener('change', () => {
    handleFiles(fileInput.files);
  });

  // Function to handle files from both input and drop events
  function handleFiles(files) {
    const newFiles = Array.from(files);
    const filesToUpload = newFiles.filter(file => {
      return !allFiles.some(existingFile => existingFile.name === file.name);
    });

    // If there are new files and fileList is not already appended, then append it
    if (filesToUpload.length > 0 && !uploadArea.contains(fileList)) {
      uploadArea.appendChild(fileList);
    }

    // Continue processing the files (update global array, update UI, etc.)
    allFiles = allFiles.concat(filesToUpload);

    const dataTransfer = new DataTransfer();
    allFiles.forEach(file => dataTransfer.items.add(file));
    fileInput.files = dataTransfer.files;

    filesToUpload.forEach(file => {
      if (displayedFiles.includes(file.name)) return;
      displayedFiles.push(file.name);

      const fileItem = document.createElement('div');
      fileItem.classList.add('uploaded-file-item');

      const deleteBtn = document.createElement('button');
      deleteBtn.textContent = '×';
      deleteBtn.classList.add('delete-file-btn');
      deleteBtn.onclick = () => {
        removeFile(file, fileItem);
      };
      fileItem.appendChild(deleteBtn);

      const fileIcon = document.createElement('img');
      fileIcon.src = getFileIcon(file);
      fileItem.appendChild(fileIcon);

      const fileName = document.createElement('span');
      fileName.textContent = file.name;
      fileItem.appendChild(fileName);

      const progressWrapper = document.createElement('div');
      progressWrapper.classList.add('progress-wrapper');

      const progressBar = document.createElement('progress');
      progressBar.value = 0;
      progressBar.max = 100;
      progressWrapper.appendChild(progressBar);

      fileItem.appendChild(progressWrapper);

      simulateFileUpload(file, progressBar, fileItem, progressWrapper);

      fileList.appendChild(fileItem);
    });
		uploadArea.style.border = "1px dashed #14A2DD";
  }
	
  function simulateFileUpload(file, progressBar, fileItem, progressWrapper) {
    let uploaded = 0;
    const uploadSpeed = Math.random() * 20 + 10;
    const interval = setInterval(() => {
      uploaded += 2;
      progressBar.value = uploaded;
      if (uploaded >= 100) {
        clearInterval(interval);
        showSuccessIcon(fileItem, progressWrapper);
      }
    }, uploadSpeed);
  }

  function showSuccessIcon(fileItem, progressWrapper) {
    const successIcon = document.createElement('img');
    successIcon.src = 'https://img.icons8.com/color/50/000000/checked.png';
    successIcon.classList.add('success-icon');
    progressWrapper.style.display = 'none';
    fileItem.appendChild(successIcon);
    successIcon.style.opacity = 0;
    setTimeout(() => {
      successIcon.style.transition = 'opacity 0.5s';
      successIcon.style.opacity = 1;
    }, 10);
  }

  function getFileIcon(file) {
    if (file.type.includes('pdf')) {
      return 'https://img.icons8.com/color/50/000000/pdf.png';
    } else if (file.type.includes('word')) {
      return 'https://img.icons8.com/color/50/000000/word.png';
    } else if (file.name.toLowerCase().endsWith('.mp4') || file.name.toLowerCase().endsWith('.mov') || file.name.toLowerCase().endsWith('.avi')) {
      return 'https://img.icons8.com/color/50/000000/video.png';
    } else if (file.name.toLowerCase().endsWith('.wav')) {
      return 'https://img.icons8.com/color/50/000000/video.png';
    } else if (file.name.toLowerCase().endsWith('.xls') || file.name.toLowerCase().endsWith('.xlsx') || file.name.toLowerCase().endsWith('.csv')) {
      return 'https://img.icons8.com/color/50/000000/ms-excel.png';
    } else if (file.type.includes('image')) {
      return URL.createObjectURL(file);
    } else {
      return 'https://img.icons8.com/color/50/000000/file.png';
    }
  }

  function removeFile(file, fileItem) {
    // Remove file from the global array
    allFiles = allFiles.filter(f => f.name !== file.name);
    displayedFiles = displayedFiles.filter(name => name !== file.name);

    // Update the file input accordingly
    const dataTransfer = new DataTransfer();
    allFiles.forEach(f => dataTransfer.items.add(f));
    fileInput.files = dataTransfer.files;

    // Remove the file element from the UI
    fileItem.remove();

    // If fileList is empty, remove it from the DOM
    if (fileList.children.length === 0 && uploadArea.contains(fileList)) {
      uploadArea.removeChild(fileList);
    }
		if (allFiles.length === 0) {
    uploadArea.style.border = "1px dashed #ccc";
		}
  }
});


</script>
const fs = require('fs');

// Create a folder named "myFolder"
if (!fs.existsSync('myFolder')) {
  fs.mkdirSync('myFolder');
  console.log('Folder created');
}

// Create a text file
fs.writeFileSync('myFolder/file.txt', 'Hello from Node.js!');

// Create a JSON file
const data = {
  name: 'John',
  age: 25
};
fs.writeFileSync('myFolder/data.json', JSON.stringify(data));

console.log('Files created!');

5d


const fs = require('fs');

// Create a file with some data
fs.writeFileSync('input.txt', 'This is streaming data example.');

// Read from input.txt and write to output.txt using streams
const readStream = fs.createReadStream('input.txt');
const writeStream = fs.createWriteStream('output.txt');

readStream.pipe(writeStream);

console.log('Streaming done!');
src/
├── App.js
├── components/
│   ├── UserList.js
│   ├── AddUser.js
│   ├── EditUser.js
└── services/
    └── api.js

import axios from "axios";

export default axios.create({
  baseURL: "http://localhost:5000/api/users" // adjust to your backend
});


#install
npx create-react-app user-management
cd user-management
npm install axios react-router-dom

#app.js

import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import UserList from './components/UserList';
import AddUser from './components/AddUser';
import EditUser from './components/EditUser';

function App() {
  return (
    <Router>
      <nav>
        <Link to="/">Users</Link> | <Link to="/add">Add User</Link>
      </nav>
      <Routes>
        <Route path="/" element={<UserList />} />
        <Route path="/add" element={<AddUser />} />
        <Route path="/edit/:id" element={<EditUser />} />
      </Routes>
    </Router>
  );
}

export default App;

userList.js

import React, { useEffect, useState } from 'react';
import axios from '../services/api';
import { Link } from 'react-router-dom';

function UserList() {
  const [users, setUsers] = useState({});

  useEffect(() => {
    axios.get('/').then((res) => {
      setUsers(res.data || {});
    });
  }, []);

  const deleteUser = (id) => {
    axios.delete(`/${id}`).then(() => {
      const updated = { ...users };
      delete updated[id];
      setUsers(updated);
    });
  };

  return (
    <div>
      <h2>Users</h2>
      {Object.entries(users).map(([id, user]) => (
        <div key={id}>
          <p>{user.name} - {user.email}</p>
          <Link to={`/edit/${id}`}>Edit</Link>
          <button onClick={() => deleteUser(id)}>Delete</button>
        </div>
      ))}
    </div>
  );
}

export default UserList;

#AddUser.js

import React, { useState } from 'react';
import axios from '../services/api';
import { useNavigate } from 'react-router-dom';

function AddUser() {
  const [user, setUser] = useState({ name: '', email: '' });
  const navigate = useNavigate();

  const handleChange = (e) => {
    setUser({ ...user, [e.target.name]: e.target.value });
  };

  const addUser = () => {
    axios.post('/', user).then(() => {
      navigate('/');
    });
  };

  return (
    <div>
      <h2>Add User</h2>
      <input name="name" value={user.name} onChange={handleChange} placeholder="Name" />
      <input name="email" value={user.email} onChange={handleChange} placeholder="Email" />
      <button onClick={addUser}>Add</button>
    </div>
  );
}

export default AddUser;

#EditUser.js

import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import axios from '../services/api';

function EditUser() {
  const { id } = useParams();
  const [user, setUser] = useState({ name: '', email: '' });
  const navigate = useNavigate();

  useEffect(() => {
    axios.get(`/${id}`).then((res) => {
      setUser(res.data);
    });
  }, [id]);

  const updateUser = () => {
    axios.put(`/${id}`, user).then(() => {
      navigate('/');
    });
  };

  const handleChange = (e) => {
    setUser({ ...user, [e.target.name]: e.target.value });
  };

  return (
    <div>
      <h2>Edit User</h2>
      <input name="name" value={user.name} onChange={handleChange} />
      <input name="email" value={user.email} onChange={handleChange} />
      <button onClick={updateUser}>Update</button>
    </div>
  );
}

export default EditUser;

#install
npm install
npm start
#install

npm install react-router-dom
npm start


#app.js

import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';

function App() {
  const user = "Alice";

  return (
    <Router>
      <div>
        <h1>React Routing Example</h1>
        <nav>
          <Link to="/">Home</Link> |{" "}
          <Link to="/about">About</Link> |{" "}
          <Link to="/contact">Contact</Link>
        </nav>

        <Routes>
          <Route path="/" element={<Home user={user} />} />
          <Route path="/about" element={<About />} />
          <Route path="/contact" element={<Contact email="alice@example.com" />} />
        </Routes>
      </div>
    </Router>
  );
}

export default App;

#home.js
import React from 'react';

function Home({ user }) {
  return (
    <div>
      <h2>Home</h2>
      <p>Welcome, {user}!</p>
    </div>
  );
}

export default Home;

#about.js

import React from 'react';

function About() {
  return (
    <div>
      <h2>About</h2>
      <p>This app demonstrates React Router for navigation.</p>
    </div>
  );
}

export default About;

#contact.js

import React from 'react';

function Contact({ email }) {
  return (
    <div>
      <h2>Contact</h2>
      <p>Contact us at: {email}</p>
    </div>
  );
}

export default Contact;
#app.js

import React, { useState } from 'react';
import Home from './Home';
import About from './About';
import Contact from './Contact';

function App() {
  const [userName, setUserName] = useState("Alice");

  return (
    <div>
      <h1>Welcome to My React App</h1>
      <Home name={userName} />
      <About />
      <Contact email="alice@example.com" />
    </div>
  );
}

export default App;

#home.js

import React from 'react';

function Home(props) {
  return (
    <div>
      <h2>Home</h2>
      <p>Hello, {props.name}! Welcome to the Home page.</p>
    </div>
  );
}

export default Home;

#About.js

import React from 'react';

function About() {
  return (
    <div>
      <h2>About</h2>
      <p>This is a sample React application using components, props, and state.</p>
    </div>
  );
}

export default About;

#contact.js
import React, { useState } from 'react';

function Contact(props) {
  const [message, setMessage] = useState("");

  const handleInput = (e) => {
    setMessage(e.target.value);
  };

  return (
    <div>
      <h2>Contact</h2>
      <p>Email us at: {props.email}</p>
      <input type="text" placeholder="Your message" value={message} onChange={handleInput} />
      <p>Your message: {message}</p>
    </div>
  );
}

export default Contact;
#install
npx create-react-app task13
cd task13


#App.js

// App.js
import React from 'react';
import FunctionalComponent from './FunctionalComponent';
import ClassComponent from './ClassComponent';

function App() {
  return (
    <div>
      <h1>Task 13a: React Functional and Class Components</h1>
      <FunctionalComponent />
      <ClassComponent />
    </div>
  );
}

export default App;

#Class Component

// ClassComponent.js
import React, { Component } from 'react';

class ClassComponent extends Component {
  constructor() {
    super();
    this.state = { count: 0 };
  }

  componentDidMount() {
    console.log('Component Mounted');
  }

  componentDidUpdate() {
    console.log('Component Updated');
  }

  componentWillUnmount() {
    console.log('Component Will Unmount');
  }

  render() {
    return (
      <div>
        <h2>Class Component</h2>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Increase
        </button>
      </div>
    );
  }
}

export default ClassComponent;

#fc

// FunctionalComponent.js
import React, { useState, useEffect } from 'react';

function FunctionalComponent() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log('Component mounted or updated');

    return () => {
      console.log('Component unmounted');
    };
  }, [count]);

  return (
    <div>
      <h2>Functional Component</h2>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
}

export default FunctionalComponent;
SELECT a.Email__c
FROM (
        SELECT b.Email__c
        FROM [EP_Event_List_for_Upload_to_CRMi] b
        WHERE 1 = 1
        AND LOWER(
            RIGHT (
                b.Email__c,
                LEN(b.Email__c) - CHARINDEX('@', b.Email__c)
            )
        ) IN (
            SELECT LOWER(x.Domain)
            FROM ent.[Dealer Domains] x
    )
) a
 
UNION ALL
SELECT a.Email__c
FROM (
    SELECT b.Email__c
    FROM [EP_Event_List_for_Upload_to_CRMi] b
    WHERE 1 = 1
    AND LOWER(
        RIGHT (
            b.Email__c,
            LEN(b.Email__c) - CHARINDEX('@', b.Email__c)
            )
        ) IN (
            SELECT LOWER(x.Domain)
            FROM ent.[Cat_Agency_Domains] x
    )
) a
 
UNION ALL
SELECT a.Email__c
FROM (
    SELECT b.Email__c
    FROM [EP_Event_List_for_Upload_to_CRMi] b
    WHERE 1 = 1
    AND LOWER(
        RIGHT (
            b.Email__c,
            LEN(b.Email__c) - CHARINDEX('@', b.Email__c)
            )
        ) IN (
            SELECT LOWER(x.Domain)
            FROM ent.[Competitor Domains] x
    )
) a
npm install express body-parser dotenv firebase
void SalesOrder.SO_Acknowledgment_Whatsapp(int soid)
{
	//soid = 143536000022873024;
	info soid;
	salesdetails = Sales_Order[ID == soid];
	//mobileno = Customers[ID == salesdetails.Customer_Name].Phone_Number1;
	getsoack = Sales_Order_Acknowledgement[Sales_Order_No == soid] sort by ID desc;
	mobileno = getsoack.Phone_No;
	grandtotal = 0;
	if(salesdetails.count() > 0 && salesdetails.Sales_Type == "Direct Order")
	{
		grandtotal = ifnull(salesdetails.Grand_Total.round(2),"");
		somap = Map();
		somap.put("sonumber",ifnull(salesdetails.Sale_Order_No,""));
		somap.put("sodate",ifnull(salesdetails.Sale_Order_Date,""));
		somap.put("grandtotal",ifnull(grandtotal,""));
		somap.put("expshipdate",ifnull(salesdetails.Expected_Shipment_Date,""));
		somap.put("custname",ifnull(getsoack.Contact_Name,""));
		//	mesg="Thank you for your order with Carrier Wheels Pvt. Ltd.!  We've received your order" + ifnull(salesdetails.Sale_Order_No,"")  + " , placed on " + ifnull(salesdetails.Sale_Order_Date,"") + ", amounting to " +ifnull(grandtotal,"")+ " .  The estimated delivery is "+ ifnull(salesdetails.Expected_Shipment_Date,"") + ". Please find the sales order attached for your reference. For any questions, feel free to contact us at " + " +91 7456973939. "+ " Thanks again for choosing Carrier Wheels Pvt. Ltd.! ";
		//info mesg;
		whatsapp_manager.WhatsappMsg_ERP_Salesorder_Acknowledgment(mobileno.tostring(),somap);
		sendmail
		[
			from :"erp@carrierwheels.com"
			to :"parthasarathy.m@synprosoft.com"
			subject :"sales order acknowledgement  " + mobileno
			message :"sales order acknowledgement email" + mobileno + "--- " + somap
		]
	}
}

//Button code
void SalesOrder.Send_Whatsapp_SO_Acknowledment(int ID)
{
	openUrl("#Form:Sales_Order_Acknowledgement?Sales_Order_recid=" + input.ID + "&Form_Mode=Whatsapp","popup window","height=<200>,width=<200>");
}
x = invokeurl
[
	url: "https://creator.zoho.com/api/v2/rebizllc/reward-and-recognition/report/All_Nomination_Forms/" + input.ID + "/Supporting_Documents/download"
	type :GET
	connection:"creator"
];
info x;



sendmail
[
	from :"ERP Communications<support@erphub.com>"
	to :"usman@erphub.biz"
	subject :"Test"
	message :"tetst"
	Attachments :file:x
]
// ts_AfterCallNotesLWC.js
import { LightningElement, api, track, wire } from 'lwc';
import { getPicklistValues, getObjectInfo } from 'lightning/uiObjectInfoApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import createFollowupActivity from '@salesforce/apex/TS_AfterCallNotesController.createFollowupActivity';

import LEAD_OBJECT from '@salesforce/schema/Lead';
import LEAD_STATUS_FIELD from '@salesforce/schema/Lead.Status';
import CONTACT_RESULT_FIELD from '@salesforce/schema/Lead.TS_Contact_Result__c';

export default class ts_AfterCallNotesLWC extends LightningElement {
    @api recordId;

    @track formData = {
        leadStatus: '',
        contactResult: '',
        followupDateTime: null,
        followupNotes: '',
        callNotes: ''
    };

    @track showFollowupFields = false;
    @track isLoading = false;

    @track contactResultDependencyMap = {};
    @track filteredContactResultOptions = [];

    @wire(getObjectInfo, { objectApiName: LEAD_OBJECT })
    leadObjectInfo;

    @wire(getPicklistValues, { recordTypeId: '$leadObjectInfo.data.defaultRecordTypeId', fieldApiName: LEAD_STATUS_FIELD })
    leadStatusPicklistValues;

    @wire(getPicklistValues, { recordTypeId: '$leadObjectInfo.data.defaultRecordTypeId', fieldApiName: CONTACT_RESULT_FIELD })
    wiredContactResultPicklistValues({ data, error }) {
        if (data) {
            console.log('Raw Contact Result Picklist Data:', data);
            this.contactResultDependencyMap = {};
            data.values.forEach(option => {
                option.validFor.forEach(index => {
                    const controllingValue = Object.keys(data.controllerValues)
                        .find(key => data.controllerValues[key] === index);
                    if (!this.contactResultDependencyMap[controllingValue]) {
                        this.contactResultDependencyMap[controllingValue] = [];
                    }
                    this.contactResultDependencyMap[controllingValue].push({
                        label: option.label,
                        value: option.value
                    });
                });
            });
            console.log('Contact Result Dependency Map:', this.contactResultDependencyMap);
            this.filterDependentOptions(this.formData.leadStatus);
        } else if (error) {
            console.error('Error fetching Contact Result picklist:', error);
        }
    }

    handleStatusChange(event) {
        this.formData.leadStatus = event.detail.value;
        console.log('Lead Status changed to:', this.formData.leadStatus);
        this.showFollowupFields = this.formData.leadStatus === 'Follow Up';
        this.filterDependentOptions(this.formData.leadStatus);
    }

    filterDependentOptions(selectedStatus) {
        this.filteredContactResultOptions = this.contactResultDependencyMap[selectedStatus] || [];
        this.formData.contactResult = '';
        console.log('Filtered Contact Result Options:', this.filteredContactResultOptions);
    }

    handleContactResultChange(event) {
        this.formData.contactResult = event.detail.value;
    }

    handleFollowupDateTimeChange(event) {
        this.formData.followupDateTime = event.detail.value;
    }

    handleFollowupNotesChange(event) {
        this.formData.followupNotes = event.detail.value;
    }

    handleCallNotesChange(event) {
        this.formData.callNotes = event.detail.value;
    }

    get leadStatusOptions() {
        return this.leadStatusPicklistValues?.data?.values || [];
    }

    get contactResultOptions() {
        return this.filteredContactResultOptions;
    }

    validateForm() {
        const allValid = [...this.template.querySelectorAll('lightning-input, lightning-textarea, lightning-combobox, lightning-input-field')]
            .reduce((validSoFar, inputField) => {
                if (!this.showFollowupFields &&
                    (inputField.name === 'followupDateTime' || inputField.name === 'followupNotes')) {
                    return validSoFar;
                }
                inputField.reportValidity();
                return validSoFar && inputField.checkValidity();
            }, true);

        return allValid;
    }

    handleSave() {
        if (!this.validateForm()) {
            return;
        }

        this.isLoading = true;

        const afterCallData = {
            leadId: this.recordId,
            leadStatus: this.formData.leadStatus,
            contactResult: this.formData.contactResult,
            followupDateTime: this.formData.followupDateTime,
            followupNotes: this.formData.followupNotes,
            callNotes: this.formData.callNotes
        };

        console.log('After Call Data:', afterCallData);

        createFollowupActivity({ afterCallData: afterCallData })
            .then(() => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'After call notes saved successfully',
                        variant: 'success'
                    })
                );
                this.resetForm();
            })
            .catch(error => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error',
                        message: error.body.message || 'An error occurred while saving the data',
                        variant: 'error'
                    })
                );
            })
            .finally(() => {
                this.isLoading = false;
            });
    }

    resetForm() {
        this.formData = {
            leadStatus: '',
            contactResult: '',
            followupDateTime: null,
            followupNotes: '',
            callNotes: ''
        };
        this.filteredContactResultOptions = [];
        this.showFollowupFields = false;
    }

    handleCancel() {
        this.resetForm();
    }
}
import os
import tkinter as tk
from tkinter import filedialog, messagebox

def seleccionar_directorio():
    ruta = filedialog.askdirectory()
    if ruta:
        entrada_ruta.delete(0, tk.END)
        entrada_ruta.insert(0, ruta)

def crear_carpetas():
    nombre = entrada_nombre.get().strip()
    ruta_base = entrada_ruta.get().strip()

    if not nombre or not ruta_base:
        messagebox.showwarning("Campos incompletos", "Por favor, completa todos los campos.")
        return

    formatos = ["dxv", "h264"]
    resoluciones = ["1080p", "2160p"]
    carpetas_creadas = []

    for formato in formatos:
        for resolucion in resoluciones:
            nombre_carpeta = f"{nombre}-{formato}-{resolucion}"
            ruta_completa = os.path.join(ruta_base, nombre_carpeta)
            os.makedirs(ruta_completa, exist_ok=True)
            carpetas_creadas.append(nombre_carpeta)

    messagebox.showinfo("Éxito", f"Se crearon las siguientes carpetas:\n" + "\n".join(carpetas_creadas))

# Interfaz gráfica
root = tk.Tk()
root.title("Crear carpetas")

tk.Label(root, text="Nombre base:").grid(row=0, column=0, sticky="e")
entrada_nombre = tk.Entry(root, width=40)
entrada_nombre.grid(row=0, column=1, padx=5, pady=5)

tk.Label(root, text="Ruta destino:").grid(row=1, column=0, sticky="e")
entrada_ruta = tk.Entry(root, width=40)
entrada_ruta.grid(row=1, column=1, padx=5, pady=5)
tk.Button(root, text="Seleccionar", command=seleccionar_directorio).grid(row=1, column=2, padx=5)

tk.Button(root, text="Crear carpetas", command=crear_carpetas).grid(row=2, column=1, pady=10)

root.mainloop()
#scroll-top-link.avia-svg-icon svg:first-child {
    margin-inline: auto;
}
.inner-posts .read-more-link a {
    display: inline-flex !important;
    align-items: center;
}
-- Replace these with your desired date range
SET @start_date = '2025-01-05';
SET @end_date = '2025-01-11';

SELECT COUNT(DISTINCT student_id) AS total_unique_students
FROM (
    -- Students who submitted a quiz
    SELECT qs.student_id
    FROM quiz_summary qs
    JOIN user u ON u.id = qs.student_id
    WHERE u.type = 'student'
      AND qs.submit = 1
      AND qs.submit_at BETWEEN @start_date AND @end_date

    UNION

    -- Students who participated in a direct tutor session
    SELECT ts.student_id
    FROM tutor_session ts
    JOIN user u ON u.id = ts.student_id
    WHERE u.type = 'student'
      AND ts.status = 'completed'
      AND ts.created_at BETWEEN @start_date AND @end_date

    UNION

    -- Students who participated via tutor session participant table
    SELECT tsp.participant_id AS student_id
    FROM tutor_session_participant tsp
    JOIN tutor_session ts ON ts.id = tsp.session_id
    JOIN user u ON u.id = tsp.participant_id
    WHERE u.type = 'student'
      AND ts.status = 'completed'
      AND ts.created_at BETWEEN @start_date AND @end_date

    UNION

    -- Students who watched a video (file_log)
    SELECT fl.user_id AS student_id
    FROM file_log fl
    JOIN user u ON u.id = fl.user_id
    WHERE u.type = 'student'
      AND fl.type = 'video'
      AND fl.created_at BETWEEN @start_date AND @end_date

    UNION

    -- Students who triggered feature_user_logger
    SELECT ful.user_id AS student_id
    FROM feature_user_logger ful
    JOIN user u ON u.id = ful.user_id
    WHERE u.type = 'student'
      AND ful.created_at BETWEEN @start_date AND @end_date
) AS combined_activities;
https://chatgpt.com/share/6807c7ed-b1d4-8011-95aa-a861e6bb9f22
1. Create express server that has authorized endpoint using JWT (JSON Web Token) library. 
2. Create express server that connects to Mongo DB database to authenticate the user and generate 
the authorized token to access the protected endpoints. 


const mongoose = require("mongoose");

//models/User.js

const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  createdAt: { type: Date, default: Date.now }
});

module.exports = mongoose.model("User", userSchema);




//middleware/auth.js)

const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');
dotenv.config();

module.exports = function (req, res, next) {
  const token = req.header('Authorization')?.split(' ')[1];
  if (!token) return res.status(401).json({ message: 'Access Denied: No Token Provided' });

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded;
    next();
  } catch (err) {
    res.status(400).json({ message: 'Invalid Token' });
  }
};





//routes/auth.js

const express = require('express');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const auth = require('../middleware/auth');
const dotenv = require('dotenv');

dotenv.config();
const router = express.Router();

// Register
router.post('/register', async (req, res) => {
  const { username, password } = req.body;
  try {
    const user = new User({ username, password });
    await user.save();
    res.status(201).json({ message: 'User registered' });
  } catch (err) {
    res.status(400).json({ message: 'User already exists' });
  }
});

// Login
router.post('/login', async (req, res) => {
  const { username, password } = req.body;
  const user = await User.findOne({ username });

  if (!user || !(await user.comparePassword(password)))
    return res.status(401).json({ message: 'Invalid credentials' });

  const token = jwt.sign({ id: user._id, username: user.username }, process.env.JWT_SECRET, {
    expiresIn: '1h',
  });

  res.json({ token });
});

// Protected route
router.get('/protected', auth, (req, res) => {
  res.json({ message: Hello ${req.user.username}, you accessed a protected route! });
});

module.exports = router;






//server.js
const express = require('express');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const authRoutes = require('./routes/auth');

dotenv.config();
const app = express();
app.use(express.json());

// Connect to MongoDB
mongoose.connect(process.env.MONGO_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
}).then(() => console.log('MongoDB Connected'))
  .catch(err => console.error('MongoDB Connection Error:', err));

// Routes
app.use('/api', authRoutes);

// Start server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(Server running on port ${PORT}));
/* Tables */

CREATE TABLE "POKEMON" (
    "ID_POKEMON" NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER  NOCYCLE  NOKEEP  NOSCALE  NOT NULL ENABLE, 
    "NAME_POKEMON" VARCHAR2(50 CHAR), 
    "URL_POKEMON" VARCHAR2(50 CHAR), 
	"POKEMON_TYPE" NUMBER, 
    CONSTRAINT "POKEMON_PK" PRIMARY KEY ("ID_POKEMON") USING INDEX  ENABLE
);

CREATE TABLE "POKEMON_IMAGES" (
    "ID_POKEMON_IMAGES" NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER  NOCYCLE  NOKEEP  NOSCALE  NOT NULL ENABLE, 
    "ID_POKEMON" NUMBER, 
    "POKEMON_NORMAL_URL" VARCHAR2(150 CHAR), 
    "POKEMON_SHINY_URL" VARCHAR2(150 CHAR), 
    CONSTRAINT "POKEMON_IMAGES_PK" PRIMARY KEY ("ID_POKEMON_IMAGES") USING INDEX  ENABLE
);

CREATE TABLE "POKEMON_TYPES" (
    ID_POKEMON_TYPE" NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER  NOCYCLE  NOKEEP  NOSCALE  NOT NULL ENABLE, 
    "NAME_POKEMON_TYPES" VARCHAR2(50 CHAR), 
    "URL_POKEMON_TYPES" VARCHAR2(100 CHAR), 
    CONSTRAINT "POKEMON_TYPES_PK" PRIMARY KEY ("ID_POKEMON_TYPE") USING INDEX  ENABLE
);

/* FK */

ALTER TABLE "POKEMON_IMAGES" ADD CONSTRAINT "POKEMON_IMAGES_FK" FOREIGN KEY ("ID_POKEMON") REFERENCES "POKEMON" ("ID_POKEMON") ENABLE;

ALTER TABLE "POKEMON" ADD CONSTRAINT "POKEMON_TYPE_FK" FOREIGN KEY ("POKEMON_TYPE") REFERENCES "POKEMON_TYPES" ("ID_POKEMON_TYPE") ENABLE;
Task 10: Authentication and Authorization using Node.js, Express, MongoDB, and JWT.

✅ Step-by-Step Guide:

1. Setup Project
mkdir jwt-auth-app
cd jwt-auth-app
npm init -y
npm install express mongoose jsonwebtoken bcryptjs dotenv

2. File Structure
jwt-auth-app/
├── .env
├── server.js
├── models/
│   └── User.js
├── middleware/
│   └── auth.js
└── routes/
    └── auth.js

3. .env File

PORT=5000
MONGO_URI=mongodb://localhost:27017/jwt-auth-db
JWT_SECRET=your_jwt_secret_key

4. MongoDB User Model (models/User.js)
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

const UserSchema = new mongoose.Schema({
  username: { type: String, required: true, unique: true },
  password: { type: String, required: true },
});

UserSchema.pre('save', async function (next) {
  if (!this.isModified('password')) return next();
  this.password = await bcrypt.hash(this.password, 10);
  next();
});

UserSchema.methods.comparePassword = function (password) {
  return bcrypt.compare(password, this.password);
};

module.exports = mongoose.model('User', UserSchema);

5. Auth Middleware (middleware/auth.js)

const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');
dotenv.config();

module.exports = function (req, res, next) {
  const token = req.header('Authorization')?.split(' ')[1];
  if (!token) return res.status(401).json({ message: 'Access Denied: No Token Provided' });

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded;
    next();
  } catch (err) {
    res.status(400).json({ message: 'Invalid Token' });
  }
};

6. Auth Routes (routes/auth.js)

const express = require('express');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const auth = require('../middleware/auth');
const dotenv = require('dotenv');

dotenv.config();
const router = express.Router();

// Register
router.post('/register', async (req, res) => {
  const { username, password } = req.body;
  try {
    const user = new User({ username, password });
    await user.save();
    res.status(201).json({ message: 'User registered' });
  } catch (err) {
    res.status(400).json({ message: 'User already exists' });
  }
});

// Login
router.post('/login', async (req, res) => {
  const { username, password } = req.body;
  const user = await User.findOne({ username });

  if (!user || !(await user.comparePassword(password)))
    return res.status(401).json({ message: 'Invalid credentials' });

  const token = jwt.sign({ id: user._id, username: user.username }, process.env.JWT_SECRET, {
    expiresIn: '1h',
  });

  res.json({ token });
});

// Protected route
router.get('/protected', auth, (req, res) => {
  res.json({ message: `Hello ${req.user.username}, you accessed a protected route!` });
});

module.exports = router;

7. Server Setup (server.js)
const express = require('express');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const authRoutes = require('./routes/auth');

dotenv.config();
const app = express();
app.use(express.json());

// Connect to MongoDB
mongoose.connect(process.env.MONGO_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
}).then(() => console.log('MongoDB Connected'))
  .catch(err => console.error('MongoDB Connection Error:', err));

// Routes
app.use('/api', authRoutes);

// Start server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

🧪 Test Your Server
1. Register: POST /api/register

{
  "username": "testuser",
  "password": "password123"
}

2. Login: POST /api/login
Response will include a token.

3. Protected Route: GET /api/protected
Add Authorization: Bearer <token> in headers.
Task 9: Working with Express & MongoDB to create an Express server with CRUD endpoints for a Users collection using Mongoose.

---

✅ Step 1: Project Setup

mkdir express-mongo-users
cd express-mongo-users
npm init -y
npm install express mongoose dotenv

✅ Step 2: Folder Structure

express-mongo-users/
├── models/
│   └── User.js
├── routes/
│   └── userRoutes.js
├── .env
├── server.js

✅ Step 3: Create .env File

PORT=5000
MONGO_URI=mongodb://localhost:27017/yourdbname

> Replace yourdbname with your actual MongoDB database name.

✅ Step 4: Mongoose User Model – models/User.js

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
    unique: true,
  },
  age: Number
}, { timestamps: true });

module.exports = mongoose.model('User', userSchema);

✅ Step 5: User Routes – routes/userRoutes.js

const express = require('express');
const router = express.Router();
const User = require('../models/User');

// Create User
router.post('/', async (req, res) => {
  try {
    const user = await User.create(req.body);
    res.status(201).json(user);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

// Get All Users
router.get('/', async (req, res) => {
  const users = await User.find();
  res.json(users);
});

// Get Single User
router.get('/:id', async (req, res) => {
  try {
    const user = await User.findById(req.params.id);
    if (!user) return res.status(404).json({ error: 'User not found' });
    res.json(user);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

// Update User
router.put('/:id', async (req, res) => {
  try {
    const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
    if (!user) return res.status(404).json({ error: 'User not found' });
    res.json(user);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

// Delete User
router.delete('/:id', async (req, res) => {
  try {
    const result = await User.findByIdAndDelete(req.params.id);
    if (!result) return res.status(404).json({ error: 'User not found' });
    res.json({ message: 'User deleted successfully' });
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

module.exports = router;

✅ Step 6: Server File – server.js

const express = require('express');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const userRoutes = require('./routes/userRoutes');

dotenv.config();

const app = express();
app.use(express.json());

// Connect to MongoDB
mongoose.connect(process.env.MONGO_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true
})
.then(() => console.log('MongoDB connected'))
.catch((err) => console.error('MongoDB connection error:', err));

// Routes
app.use('/api/users', userRoutes);

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

✅ Step 7: Run the Server
node server.js

✅ Sample API Endpoints (use Postman or curl):
POST   /api/users – Create a user
GET    /api/users – Get all users
GET    /api/users/:id – Get user by ID
PUT    /api/users/:id – Update user
DELETE /api/users/:id – Delete user
const express = require('express');
const jwt = require('jsonwebtoken');

const app = express();
app.use(express.json());

const SECRET_KEY = "secret key"; // Ideally should be stored in environment variables

// Login Route to generate token
app.post('/login', (req, res) => {
    const user = {
        uname: "admin",
        age: 30
    };

    jwt.sign({ user }, SECRET_KEY, { expiresIn: '1h' }, (err, token) => {
        if (err) {
            return res.status(500).json({ message: "Error generating token" });
        }
        res.status(200).json({ token });
    });
});

// Middleware to verify token
function verifyToken(req, res, next) {
    const authHeader = req.headers['authorization'];

    if (!authHeader) {
        return res.status(403).json({ message: 'No token provided' });
    }

    const tokenParts = authHeader.split(' ');
    if (tokenParts.length !== 2 || tokenParts[0] !== 'Bearer') {
        return res.status(403).json({ message: 'Malformed token' });
    }

    const token = tokenParts[1];

    jwt.verify(token, SECRET_KEY, (err, data) => {
        if (err) {
            return res.status(403).json({ message: 'Invalid token' });
        }
        req.authData = data;
        next();
    });
}

// Protected Route
app.post('/verify', verifyToken, (req, res) => {
    res.status(200).json({ message: 'Welcome', authData: req.authData });
});

// Start Server
app.listen(3000, () => {
    console.log('Server started on port 3000');
});
Here’s how you can complete TASK 7: Working with Express step by step:

---

🔧 Step 1: Set Up the Project

mkdir user-api-ejs
cd user-api-ejs
npm init -y
npm install express ejs body-parser

---

📁 Project Structure

user-api-ejs/
├── views/
│   └── users.ejs
├── routes/
│   └── users.js
├── app.js

📦 Step 2: Create the Express Server (app.js)
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const usersRouter = require('./routes/users');

app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use('/api/users', usersRouter); // REST API
app.use('/users', usersRouter);     // For EJS view

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

---

📄 Step 3: Users API Routes (routes/users.js)

const express = require('express');
const router = express.Router();

let users = [
  { id: 1, name: 'Alice', email: 'alice@example.com' },
  { id: 2, name: 'Bob', email: 'bob@example.com' }
];

// READ all users (API)
router.get('/', (req, res) => {
  if (req.originalUrl.startsWith('/api')) {
    res.json(users);
  } else {
    res.render('users', { users });
  }
});

// CREATE a new user
router.post('/', (req, res) => {
  const { name, email } = req.body;
  const newUser = { id: users.length + 1, name, email };
  users.push(newUser);
  res.json(newUser);
});

// UPDATE a user
router.put('/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const { name, email } = req.body;
  const user = users.find(u => u.id === id);
  if (user) {
    user.name = name;
    user.email = email;
    res.json(user);
  } else {
    res.status(404).json({ message: 'User not found' });
  }
});

// DELETE a user
router.delete('/:id', (req, res) => {
  const id = parseInt(req.params.id);
  users = users.filter(u => u.id !== id);
  res.json({ message: 'User deleted' });
});

module.exports = router;

🖼️ Step 4: Create EJS Template (views/users.ejs)

<!DOCTYPE html>
<html>
<head>
  <title>Users Table</title>
  <style>
    table {
      width: 60%;
      border-collapse: collapse;
      margin: 20px auto;
    }
    th, td {
      padding: 10px;
      border: 1px solid #ddd;
      text-align: left;
    }
    th {
      background-color: #f2f2f2;
    }
  </style>
</head>
<body>
  <h2 style="text-align: center;">Users List</h2>
  <table>
    <thead>
      <tr><th>ID</th><th>Name</th><th>Email</th></tr>
    </thead>
    <tbody>
      <% users.forEach(user => { %>
        <tr>
          <td><%= user.id %></td>
          <td><%= user.name %></td>
          <td><%= user.email %></td>
        </tr>
      <% }) %>
    </tbody>
  </table>
</body>
</html>
🧪 Step 5: Test in Postman

Test these endpoints:

GET http://localhost:3000/api/users → Get all users (JSON)

POST http://localhost:3000/api/users → Add user (Body: name, email)

PUT http://localhost:3000/api/users/:id → Update user by ID

DELETE http://localhost:3000/api/users/:id → Delete user by ID

Visit http://localhost:3000/users to see the data in table form via EJS.
🔹 Part 1: Create a basic HTTP server (no Express)

This server listens on port 3000 and serves HTML, plain text, and JSON based on the request URL.

// httpServer.js
const http = require('http');
const server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end('<h1>Welcome to the Home Page</h1>');
  } else if (req.url === '/text') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('This is plain text');
  } else if (req.url === '/json') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ message: 'Hello, this is JSON response!' }));
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('404 Not Found');
  }
});

server.listen(3000, () => {
  console.log('HTTP server running at http://localhost:3000');
});

🔹 Part 2: Create an Express server
This server also listens on port 3000 and uses Express with multiple endpoints.
// expressServer.js
const express = require('express');
const app = express();
const PORT = 3000;
app.get('/', (req, res) => {
  res.send('<h1>Welcome to the Express Home Page</h1>');
});

app.get('/text', (req, res) => {
  res.type('text').send('This is a plain text response');
});

app.get('/json', (req, res) => {
  res.json({ message: 'Hello from Express JSON endpoint!' });
});

app.get('/html', (req, res) => {
  res.send(`
    <html>
      <head><title>Express HTML</title></head>
      <body><h1>This is HTML served with Express</h1></body>
    </html>
  `);
});

app.use((req, res) => {
  res.status(404).send('404 Not Found');
});

app.listen(PORT, () => {
  console.log(`Express server running at http://localhost:${PORT}`);
});

✅ Run the Servers
To run either server:
node httpServer.js     # for native HTTP server
# or
node expressServer.js  # for Express server

Make sure to install Express for the second part if you haven’t:
npm install express
const express=require('express')

const app=express()
app.use(express.json())

const mongoose=require('mongoose')



app.listen(2000,()=>{console.log("Server started on port 2000")})

mongoose.connect("mongodb://127.0.0.1:27017/fsd")
.then(()=>console.log("Connected to MongoDB"))
.catch((err)=>console.log(err))

const userSchema=new mongoose.Schema({
    name:{
        type:String,
        required:true
    },
    phone:{
        type:Number,
    },
    email:{
        type:String,
        required:true,
        unique:true
    }
})

const userModel=mongoose.model("user",userSchema)

app.post("/api/users",async(req,res)=>{

    const user=await userModel.create(req.body)

    res.status(200).json(user)
})

app.get("/users/:id",async(req,res)=>{

    const id=req.params.id
    const user=await userModel.findById(id)
    res.json(user)
})




app.put("/update/:id",async(req,res)=>{
    
    const id=req.params.id
    const user=await userModel.findByIdAndUpdate(id,req.body)

    res.json(user)
})
app.delete("/delete/:id",async(req,res)=>{
    const id=req.params.id

    const user=await userModel.findByIdAndDelete(id)

        res.json(user)
})
----------
index.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>
    <h1>Heloo this is</h1>
    
</body>
</html>
1. Create Custom / Local Modules and Export Them Using Various Module Patterns

a. CommonJS Pattern (module.exports)

mathUtils.js:

function add(a, b) {
  return a + b;
}
function subtract(a, b) {
  return a - b;
}
module.exports = { add, subtract };

app.js:
const math = require('./mathUtils');
console.log(math.add(5, 3));        // 8
console.log(math.subtract(9, 4));   // 5

b. Exports Shortcut Pattern
greet.js:
exports.sayHello = (name) => `Hello, ${name}!`;
exports.sayBye = (name) => `Bye, ${name}!`;

app.js:
const greet = require('./greet');
console.log(greet.sayHello('Sam'));  // Hello, Sam!

c. Immediately Invoked Function Expression (IIFE)
counter.js:
module.exports = (function () {
  let count = 0;
  return {
    increment: () => ++count,
    decrement: () => --count,
  };
})();

app.js:
const counter = require('./counter');
console.log(counter.increment());  // 1
console.log(counter.increment());  // 2

2. Explore the Functionality of os, path, util, and events Modules

os Module:
const os = require('os');
console.log(os.platform());
console.log(os.cpus());
console.log(os.freemem());

path Module:
const path = require('path');
console.log(path.basename(__filename));
console.log(path.join(__dirname, 'files', 'test.txt'));

util Module :
const util = require('util');
const wait = util.promisify(setTimeout);
wait(1000).then(() => console.log('1 second passed'));

events Module :
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('greet', (name) => {
  console.log(`Hello, ${name}`);
});
emitter.emit('greet', 'Alice');

3. Use the fs Module for Creating Directories and Files of Different Formats

const fs = require('fs');
const path = require('path');
// Create directory
fs.mkdirSync(path.join(__dirname, 'output'), { recursive: true });
// Create text file
fs.writeFileSync(path.join(__dirname, 'output', 'note.txt'), 'This is a text file.');
// Create JSON file
const data = { name: 'Node', type: 'runtime' };
fs.writeFileSync(path.join(__dirname, 'output', 'data.json'), JSON.stringify(data, null, 2));

4. Read and Write Streaming Data Using Readable and Writable Streams

const fs = require('fs');
const path = require('path');

// Create read and write streams
const readStream = fs.createReadStream(path.join(__dirname, 'input.txt'), 'utf-8');
const writeStream = fs.createWriteStream(path.join(__dirname, 'output', 'output.txt'));
// Pipe data from input.txt to output.txt
readStream.pipe(writeStream);

Make sure to create an input.txt file before running this.
✅ Prerequisites

1. Sign up at https://openweathermap.org/api and get your API key.
2. Use the Current Weather Data API and 5 Day / 3 Hour Forecast API.
3. Include Chart.js via CDN in your HTML.

---

🔧 HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Weather Dashboard</title>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <style>
    table, th, td {
      border: 1px solid black;
      border-collapse: collapse;
      padding: 8px;
    }
    #weather-table, #forecast-table {
      margin: 20px 0;
    }
  </style>
</head>
<body>
  <h2>Weather Information</h2>
  <input type="text" id="city" placeholder="Enter City Name">
  <button onclick="getWeather()">Get Weather</button>

  <div id="weather-table"></div>
  <div id="forecast-table"></div>
  <canvas id="forecastChart" width="600" height="300"></canvas>

  <script src="script.js"></script>
</body>
</html>

---

✏️ JavaScript (script.js)

const apiKey = 'YOUR_API_KEY'; // Replace with your OpenWeatherMap API key

async function getWeather() {
  const city = document.getElementById('city').value;
  if (!city) return alert('Please enter a city');

  await getCurrentWeather(city);
  await getWeatherForecast(city);
}

async function getCurrentWeather(city) {
  const response = await fetch(
    `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`
  );
  const data = await response.json();

  const html = `
    <table>
      <tr><th>City</th><th>Min Temp (°C)</th><th>Max Temp (°C)</th><th>Humidity (%)</th></tr>
      <tr>
        <td>${data.name}</td>
        <td>${data.main.temp_min}</td>
        <td>${data.main.temp_max}</td>
        <td>${data.main.humidity}</td>
      </tr>
    </table>
  `;
  document.getElementById('weather-table').innerHTML = html;
}

async function getWeatherForecast(city) {
  const response = await fetch(
    `https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${apiKey}&units=metric`
  );
  const data = await response.json();

  // Extract date and temperature every 8 entries (~24 hours)
  const forecasts = data.list.filter((_, index) => index % 8 === 0);

  const tableRows = forecasts.map(forecast => `
    <tr>
      <td>${forecast.dt_txt.split(' ')[0]}</td>
      <td>${forecast.main.temp}</td>
    </tr>
  `).join('');

  const table = `
    <h3>5-Day Forecast</h3>
    <table>
      <tr><th>Date</th><th>Temperature (°C)</th></tr>
      ${tableRows}
    </table>
  `;
  document.getElementById('forecast-table').innerHTML = table;

  // Plot chart
  const labels = forecasts.map(f => f.dt_txt.split(' ')[0]);
  const temperatures = forecasts.map(f => f.main.temp);
  drawChart(labels, temperatures);
}

function drawChart(labels, data) {
  const ctx = document.getElementById('forecastChart').getContext('2d');
  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: labels,
      datasets: [{
        label: 'Temperature (°C)',
        data: data,
        backgroundColor: 'rgba(54, 162, 235, 0.6)',
        borderColor: 'blue',
        borderWidth: 1
      }]
    },
    options: {
      responsive: true,
      scales: {
        y: {
          beginAtZero: false
        }
      }
    }
  });
}
1. Working with Higher-Order Functions in JavaScript
A higher-order function is a function that either takes another function as an argument or returns a function.

// Higher-order function
function greetUser(greetFn) {
    const name = "Alice";
    greetFn(name);
}
// Function to be passed
function sayHello(name) {
    console.log(`Hello, ${name}!`);
}
greetUser(sayHello);

2. Callback and Callback Hell
A callback is a function passed to another function to be executed later.

Example with Callback Hell:
function step1(callback) {
    setTimeout(() => {
        console.log("Step 1 completed");
        callback();
    }, 1000);
}

function step2(callback) {
    setTimeout(() => {
        console.log("Step 2 completed");
        callback();
    }, 1000);
}

function step3(callback) {
    setTimeout(() => {
        console.log("Step 3 completed");
        callback();
    }, 1000);
}

// Callback Hell
step1(() => {
    step2(() => {
        step3(() => {
            console.log("All steps completed (callback hell)");
        });
    });
});

3. Working with XHR (XMLHttpRequest)

const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log("XHR Response:", JSON.parse(xhr.responseText));
    }
};
xhr.send();

4. Using Promises to Deal with Callback Hell
Promises provide a cleaner alternative to callbacks for handling async tasks.

function stepPromise(stepName) {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log(`${stepName} completed`);
            resolve();
        }, 1000);
    });
}
// Promise chaining to avoid callback hell
stepPromise("Step 1")
    .then(() => stepPromise("Step 2"))
    .then(() => stepPromise("Step 3"))
    .then(() => console.log("All steps completed (with Promise)"));

5. Promise Chaining and async/await

Promise Chaining (already shown above)

Using async/await (cleanest syntax)

async function executeSteps() {
    await stepPromise("Step 1");
    await stepPromise("Step 2");
    await stepPromise("Step 3");
    console.log("All steps completed (with async/await)");
}

executeSteps();
1. Prototypal Inheritance and Classes

a. Prototypal Inheritance (old way):
function Animal(name) {
  this.name = name;
}
Animal.prototype.speak = function () {
  console.log(`${this.name} makes a sound.`);
};

function Dog(name, breed) {
  Animal.call(this, name);
  this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.speak = function () {
  console.log(`${this.name} barks.`);
};

const dog = new Dog("Buddy", "Golden Retriever");
dog.speak(); // Buddy barks.

b. ES6 Classes (modern way):
class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }

  speak() {
    console.log(`${this.name} barks.`);
  }
}

const dog2 = new Dog("Max", "Labrador");
dog2.speak(); // Max barks.

2. Object and Array Destructuring
// Object destructuring
const user = {
  id: 1,
  name: "Alice",
  contact: {
    email: "alice@example.com",
    phone: "123-4567"
  }
};

const { name, contact: { email } } = user;
console.log(name);  // Alice
console.log(email); // alice@example.com

// Array destructuring
const fruits = ["apple", "banana", "cherry"];
const [firstFruit, , thirdFruit] = fruits;
console.log(firstFruit);  // apple
console.log(thirdFruit);  // cherry

3. Working with Modules
a. Exporting from a module (file: mathUtils.js)
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;

b. Importing in another file
import { add, subtract } from './mathUtils.js';
console.log(add(5, 3));      // 8
console.log(subtract(5, 3)); // 2

> ⚠️ Note: You need to run this in a module-supporting environment (e.g., browser with type="module" or Node with .mjs or appropriate config).

4. Function Generators and Symbols
a. Generator Function
function* numberGenerator() {
  yield 1;
  yield 2;
  yield 3;
}
const gen = numberGenerator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3

b. Symbols

const ID = Symbol("id");
const person = {
  name: "Bob",
  [ID]: 1234
};
console.log(person);           // { name: 'Bob', [Symbol(id)]: 1234 }
console.log(person[ID]);       // 1234

5. Working with Closures
function outerFunction(outerVariable) {
  return function innerFunction(innerVariable) {
    console.log(`Outer: ${outerVariable}, Inner: ${innerVariable}`);
  };
}

const closureExample = outerFunction("outside");
closureExample("inside"); // Outer: outside, Inner: inside
1. Create a Git Repository Locally

🛠 Steps:

1. Create a simple web app with 5 HTML pages:

mkdir my-web-app
cd my-web-app
touch index.html about.html contact.html services.html portfolio.html

2. Initialize Git:
git init

3. Stage and commit the files:
git add .
git commit -m "Initial commit with 5 HTML pages"

2. Push to GitHub and Explore Remote Options
🛠 Steps:
1. Go to GitHub and create a new repository (e.g., my-web-app).

2. Connect local repo to GitHub:
git remote add origin https://github.com/your-username/my-web-app.git

3. Push to GitHub:
git push -u origin main  # or master, depending on your default branch

🔍 Explore:
Push updates:
git push origin main

Pull latest changes from remote:
git pull origin main

Fetch updates (without merging):
git fetch origin

3. Clone, Modify, and Push Back
🛠 Steps:
1. Clone the repo in another folder:
git clone https://github.com/your-username/my-web-app.git

2. Modify a file (e.g., edit about.html), then:
git add about.html
git commit -m "Updated about page content"
git push origin main

4. Create Branches and Merge
🛠 Steps:
1. Create and switch to new branches:
git checkout -b feature-header
# make changes
git add .
git commit -m "Added header"

git checkout -b feature-footer
# make changes
git add .
git commit -m "Added footer"

2. Merge into main:
git checkout main
git merge feature-header
git merge feature-footer
git commit -m "Merged header and footer features"

5. Publish with GitHub Pages

🛠 Steps:

1. Push all content to the main branch.
2. Go to your GitHub repository > Settings > Pages.
3. Under Source, choose main branch and root folder /.
4. GitHub will provide a URL like:
https://your-username.github.io/my-web-app/
const fs = require('fs');

// Create a readable stream (reading from input.txt)
const readStream = fs.createReadStream('input.txt');

// Create a writable stream (writing to output.txt)
const writeStream = fs.createWriteStream('output.txt');

// Pipe the read stream into the write stream
readStream.pipe(writeStream);

console.log("Streaming data from input.txt to output.txt...");
const fs = require('fs');

// Create a folder
fs.mkdirSync('myFolder');

// Create a text file
fs.writeFileSync('myFolder/info.txt', 'Hello from Node.js');

// Create a JSON file
fs.writeFileSync('myFolder/data.json', '{"name": "Amit"}');

// Create an HTML file
fs.writeFileSync('myFolder/index.html', '<h1>Welcome</h1>');
✅ 1. os Module – System Info
const os = require('os');
console.log("Operating System:", os.type());
console.log("Free Memory:", os.freemem());
console.log("Home Directory:", os.homedir());




✅ 2. path Module – File & Directory Paths
const path = require('path');
const filePath = "/users/admin/project/index.js";
console.log("Directory Name:", path.dirname(filePath));  // /users/admin/project
console.log("Base Name:", path.basename(filePath));      // index.js
console.log("Extension:", path.extname(filePath)); // .js



✅ 3. util Module – Utility Functions
const util = require('util');
const greet = util.format("Hello %s, your score is %d", "Anita", 95);
console.log(greet); // Hello Anita, your score is 95





✅ 4. events Module – Event Emitter
const EventEmitter = require('events');
const emitter = new EventEmitter();
// Registering an event
emitter.on('greet', (name) => {
    console.log(`Hello, ${name}!`);
});
// Emitting the event
emitter.emit('greet', 'Rahul'); // Output: Hello, Rahul!
🧩 1. ES6 Module Pattern (using export / import)
                          
📁 mathUtils.js
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;



📁 main.js
import { add, multiply } from './mathUtils.js';

console.log(add(2, 3));       // 5
console.log(multiply(2, 3));  // 6





🧱 2. CommonJS Module Pattern (Node.js style)

📁 mathUtils.js
function add(a, b) {
    return a + b;
}

function multiply(a, b) {
    return a * b;
}
module.exports = { add, multiply };


📁 main.js
const { add, multiply } = require('./mathUtils');

console.log(add(4, 5));       // 9
console.log(multiply(4, 5));  // 20
async function executeSteps() {
    await stepPromise("Step 1");
    await stepPromise("Step 2");
    await stepPromise("Step 3");
    console.log("All steps completed (with async/await)");
}

executeSteps();
function stepPromise(stepName) {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log(`${stepName} completed`);
            resolve();
        }, 1000);
    });
}

// Promise chaining to avoid callback hell
stepPromise("Step 1")
    .then(() => stepPromise("Step 2"))
    .then(() => stepPromise("Step 3"))
    .then(() => console.log("All steps completed (with Promise)"));
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log("XHR Response:", JSON.parse(xhr.responseText));
    }
};
xhr.send();
function task1(callback) {
  setTimeout(() => {
    console.log("Task 1 completed");
    callback();
  }, 1000);
}

function task2(callback) {
  setTimeout(() => {
    console.log("Task 2 completed");
    callback();
  }, 1000);
}

function task3(callback) {
  setTimeout(() => {
    console.log("Task 3 completed");
    callback();
  }, 1000);
}

function task4(callback) {
  setTimeout(() => {
    console.log("Task 4 completed");
    callback();
  }, 1000);
}

// This is where callback hell starts
task1(() => {
  task2(() => {
    task3(() => {
      task4(() => {
        console.log("All tasks done!");
      });
    });
  });
});
// Higher-order function
function greetUser(greetFn) {
    const name = "Alice";
    greetFn(name);
}

// Function to be passed
function sayHello(name) {
    console.log(`Hello, ${name}!`);
}

greetUser(sayHello);
https://chatgpt.com/share/6803c2a0-b0b0-800e-a3ae-22019667f464
https://chatgpt.com/share/6806f131-1ca0-800e-98cc-208108aa0113


Create express server that has endpoints connecting to Users collection present in Mongo DB 
database using mongoose library and perform CRUD operation on that. 
https://chatgpt.com/share/6806edc3-be74-800e-b64e-d107384cf470

API:KEY-->https://api.openweathermap.org/data/2.5/weather?q=Hyderabad&appid=bb5d6d56c0d5dbe246c95ed802b759fe

25b5d51f0221767ca7aad908df540fdd

1. Use fetch function to access remote data using the given api and display the data in the form of a 
table. 
2. Use fetch function to read the weather details from openweathermap.org and display the details 
like city, min-temp, max-temp, humidity on the webpage for a given city. 
3. From the same website read the weather forecast details for a given city and display the details 
like date – temperature in a table. 
4. Plot a bar chart for the above implementation using date and temperature along X and Y axis 
respectively.  Use ChartJS library. 


API:KEY-->https://api.openweathermap.org/data/2.5/weather?q=Hyderabad&appid=bb5d6d56c0d5dbe246c95ed802b759fe

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Weather Dashboard</title>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <style>
    table, th, td {
      border: 1px solid black;
      border-collapse: collapse;
      padding: 8px;
    }
    #weather-table, #forecast-table {
      margin: 20px 0;
    }
  </style>
</head>
<body>
  <h2>Weather Information</h2>
  <input type="text" id="city" placeholder="Enter City Name">
  <button onclick="getWeather()">Get Weather</button>

  <div id="weather-table"></div>
  <div id="forecast-table"></div>
  <canvas id="forecastChart" width="600" height="300"></canvas>

  <script src="script.js"></script>
</body>
</html>





//script.js
const apiKey = 'YOUR_API_KEY'; // Replace with your OpenWeatherMap API key

async function getWeather() {
  const city = document.getElementById('city').value;
  if (!city) return alert('Please enter a city');

  await getCurrentWeather(city);
  await getWeatherForecast(city);
}

async function getCurrentWeather(city) {
  const response = await fetch(
    `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`
  );
  const data = await response.json();

  const html = `
    <table>
      <tr><th>City</th><th>Min Temp (°C)</th><th>Max Temp (°C)</th><th>Humidity (%)</th></tr>
      <tr>
        <td>${data.name}</td>
        <td>${data.main.temp_min}</td>
        <td>${data.main.temp_max}</td>
        <td>${data.main.humidity}</td>
      </tr>
    </table>
  `;
  document.getElementById('weather-table').innerHTML = html;
}

async function getWeatherForecast(city) {
  const response = await fetch(
    `https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${apiKey}&units=metric`
  );
  const data = await response.json();

  // Extract date and temperature every 8 entries (~24 hours)
  const forecasts = data.list.filter((_, index) => index % 8 === 0);

  const tableRows = forecasts.map(forecast => `
    <tr>
      <td>${forecast.dt_txt.split(' ')[0]}</td>
      <td>${forecast.main.temp}</td>
    </tr>
  `).join('');

  const table = `
    <h3>5-Day Forecast</h3>
    <table>
      <tr><th>Date</th><th>Temperature (°C)</th></tr>
      ${tableRows}
    </table>
  `;
  document.getElementById('forecast-table').innerHTML = table;

  // Plot chart
  const labels = forecasts.map(f => f.dt_txt.split(' ')[0]);
  const temperatures = forecasts.map(f => f.main.temp);
  drawChart(labels, temperatures);
}

function drawChart(labels, data) {
  const ctx = document.getElementById('forecastChart').getContext('2d');
  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: labels,
      datasets: [{
        label: 'Temperature (°C)',
        data: data,
        backgroundColor: 'rgba(54, 162, 235, 0.6)',
        borderColor: 'blue',
        borderWidth: 1
      }]
    },
    options: {
      responsive: true,
      scales: {
        y: {
          beginAtZero: false
        }
      }
    }
  });
}
//Create a user database and a user document and perform crud Shell commands using mongodb 



1. Open MongoDB Shell

mongosh
2. Create or Switch to a Database

use userDB
3. Create a Collection (Optional)
MongoDB creates it automatically when inserting the first document, but you can explicitly create one:


db.createCollection("users")
4. Insert a Document (Create)

db.users.insertOne({
  username: "john_doe",
  email: "john@example.com",
  age: 28,
  address: {
    city: "New York",
    zip: "10001"
  }
})
5. Read Documents (Read)
Find all users:


db.users.find()
Find a specific user:


db.users.findOne({ username: "john_doe" })
6. Update a Document (Update)
Update a field:


db.users.updateOne(
  { username: "john_doe" },
  { $set: { age: 29 } }
)
Add a new field:


db.users.updateOne(
  { username: "john_doe" },
  { $set: { phone: "123-456-7890" } }
)
7. Delete a Document (Delete)
Delete one user:

db.users.deleteOne({ username: "john_doe" })
Delete all users (use with caution):


db.users.deleteMany({})





//Create a real time database in firebase for the student management system and explore the features of Firebase Real Time Database.  Perform CRUD operations on the Real Time Database. 


npm install firebase


import { initializeApp } from 'firebase/app';
import { getDatabase, ref, set, get, update, remove } from 'firebase/database';

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
  databaseURL: "https://YOUR_PROJECT_ID-default-rtdb.firebaseio.com",
  projectId: "YOUR_PROJECT_ID",
  // ...rest config
};

const app = initializeApp(firebaseConfig);
const db = getDatabase(app);

// CREATE
set(ref(db, 'students/1'), {
  name: "John Doe",
  course: "Computer Science",
  age: 21
});

// READ
get(ref(db, 'students/1')).then(snapshot => {
  if (snapshot.exists()) {
    console.log(snapshot.val());
  } else {
    console.log("No data available");
  }
});

// UPDATE
update(ref(db, 'students/1'), {
  age: 22
});

// DELETE
remove(ref(db, 'students/1'));
function outerFunction(outerVariable) {
  return function innerFunction(innerVariable) {
    console.log(`Outer: ${outerVariable}, Inner: ${innerVariable}`);
  };
}

const closureExample = outerFunction("outside");
closureExample("inside"); // Outer: outside, Inner: inside
// Generator function using function* syntax
function* numberGenerator() {
    yield 1;
    yield 2;
    yield 3;
}

const gen = numberGenerator();

console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3




// Creating unique Symbols
const id1 = Symbol("id");
const id2 = Symbol("id");

console.log(id1 === id2); // false (Symbols are always unique)

// Using Symbol as an object key
const user = {
    name: "Amit",
    [id1]: 101
};

console.log(user.name);  // Amit
console.log(user[id1]);  // 101
🔹 a. Exporting from a module
📁 File: mathUtils.js


// mathUtils.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;



🔹 b. Importing in another file
📁 File: main.js


// main.js
import { add, subtract } from './mathUtils.js';

console.log(add(5, 3));      // 8
console.log(subtract(5, 3)); // 2
star

Thu Apr 24 2025 09:50:13 GMT+0000 (Coordinated Universal Time)

@shubhangi.b

star

Thu Apr 24 2025 07:50:10 GMT+0000 (Coordinated Universal Time)

@shubhangi.b

star

Thu Apr 24 2025 06:23:20 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Thu Apr 24 2025 06:09:31 GMT+0000 (Coordinated Universal Time) https://www.addustechnologies.com/blog/betway-clone-script

@Seraphina

star

Thu Apr 24 2025 05:45:39 GMT+0000 (Coordinated Universal Time) https://dgtool.co.il/%D7%A9%D7%93%D7%A8%D7%95%D7%92-%D7%97%D7%95%D7%95%D7%99%D7%99%D7%AA-%D7%94%D7%A2%D7%9C%D7%90%D7%AA-%D7%94%D7%A7%D7%91%D7%A6%D7%99%D7%9D-%D7%91%D7%90%D7%9C%D7%9E%D7%A0%D7%98%D7%95%D7%A8/

@Shesek

star

Thu Apr 24 2025 01:39:42 GMT+0000 (Coordinated Universal Time)

@exam3

star

Thu Apr 24 2025 00:55:02 GMT+0000 (Coordinated Universal Time)

@exam3

star

Thu Apr 24 2025 00:06:13 GMT+0000 (Coordinated Universal Time)

@exam3

star

Wed Apr 23 2025 23:57:11 GMT+0000 (Coordinated Universal Time)

@exam3

star

Wed Apr 23 2025 23:30:04 GMT+0000 (Coordinated Universal Time)

@exam3

star

Wed Apr 23 2025 21:52:29 GMT+0000 (Coordinated Universal Time)

@shirnunn

star

Wed Apr 23 2025 16:18:05 GMT+0000 (Coordinated Universal Time) https://iyrinhealth.com/product/vidalista-60mg-tadalafil-tablets/

@nickhervey #vidalista #vidalista60 #vidalista60mg #tadalafil

star

Wed Apr 23 2025 13:30:46 GMT+0000 (Coordinated Universal Time)

@exam3

star

Wed Apr 23 2025 11:26:42 GMT+0000 (Coordinated Universal Time)

@Pooja

star

Wed Apr 23 2025 11:23:12 GMT+0000 (Coordinated Universal Time)

@usman13

star

Wed Apr 23 2025 11:05:22 GMT+0000 (Coordinated Universal Time) https://www.innovalleyworks.com/salesforce-picklist-dependencies-in-lwc-without-apex/

@mdfaizi

star

Wed Apr 23 2025 10:25:11 GMT+0000 (Coordinated Universal Time) https://innosoft.ae/sports-betting-app-development-company/

@johnstone

star

Wed Apr 23 2025 09:51:57 GMT+0000 (Coordinated Universal Time)

@vjg #python

star

Wed Apr 23 2025 05:45:43 GMT+0000 (Coordinated Universal Time)

@omnixima #css

star

Wed Apr 23 2025 04:34:30 GMT+0000 (Coordinated Universal Time)

@IfedayoAwe

star

Wed Apr 23 2025 03:51:34 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed Apr 23 2025 02:17:22 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed Apr 23 2025 01:51:48 GMT+0000 (Coordinated Universal Time)

@chivchav

star

Wed Apr 23 2025 01:43:42 GMT+0000 (Coordinated Universal Time)

@cciot

star

Wed Apr 23 2025 01:43:14 GMT+0000 (Coordinated Universal Time)

@cciot

star

Wed Apr 23 2025 01:43:01 GMT+0000 (Coordinated Universal Time)

@fsd

star

Wed Apr 23 2025 01:42:45 GMT+0000 (Coordinated Universal Time)

@cciot

star

Wed Apr 23 2025 01:42:23 GMT+0000 (Coordinated Universal Time)

@cciot

star

Wed Apr 23 2025 01:41:55 GMT+0000 (Coordinated Universal Time)

@cciot

star

Wed Apr 23 2025 01:41:08 GMT+0000 (Coordinated Universal Time)

@cciot

star

Wed Apr 23 2025 01:40:45 GMT+0000 (Coordinated Universal Time)

@cciot

star

Wed Apr 23 2025 01:40:21 GMT+0000 (Coordinated Universal Time)

@cciot

star

Wed Apr 23 2025 01:39:41 GMT+0000 (Coordinated Universal Time)

@cciot

star

Wed Apr 23 2025 01:30:55 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/share/6806ee0c-b024-800e-83c3-9fa4fe10af07

@signup

star

Wed Apr 23 2025 01:29:40 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/share/6806ee0c-b024-800e-83c3-9fa4fe10af07

@signup

star

Wed Apr 23 2025 01:27:41 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/share/6806ee0c-b024-800e-83c3-9fa4fe10af07

@signup

star

Wed Apr 23 2025 01:24:58 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/share/6806ee0c-b024-800e-83c3-9fa4fe10af07

@signup

star

Wed Apr 23 2025 01:19:17 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/share/6806eb90-bdac-800e-8a25-6ffb72f6bc0e

@signup

star

Wed Apr 23 2025 01:17:39 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/share/6806eb90-bdac-800e-8a25-6ffb72f6bc0e

@signup

star

Wed Apr 23 2025 01:14:50 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/share/6806eb90-bdac-800e-8a25-6ffb72f6bc0e

@signup

star

Wed Apr 23 2025 01:13:36 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/share/6806eb90-bdac-800e-8a25-6ffb72f6bc0e

@signup

star

Wed Apr 23 2025 01:12:15 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/share/6806eb90-bdac-800e-8a25-6ffb72f6bc0e

@signup

star

Tue Apr 22 2025 20:15:02 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/share/6803c2a0-b0b0-800e-a3ae-22019667f464

@signup

star

Tue Apr 22 2025 20:06:38 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/share/6806f131-1ca0-800e-98cc-208108aa0113

@signup

star

Tue Apr 22 2025 20:01:17 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/share/6806edc3-be74-800e-b64e-d107384cf470

@signup

star

Tue Apr 22 2025 19:59:08 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/share/6807e024-b8e8-800a-8125-77cdc3085e80

@signup

star

Tue Apr 22 2025 19:56:36 GMT+0000 (Coordinated Universal Time)

@signup

star

Tue Apr 22 2025 19:55:19 GMT+0000 (Coordinated Universal Time)

@signup

star

Tue Apr 22 2025 19:53:14 GMT+0000 (Coordinated Universal Time)

@signup

Save snippets that work with our extensions

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