Snippets Collections
const path = require('path');

const filePath = '/users/student/projects/app/index.js';

console.log('Directory Name:', path.dirname(filePath));
console.log('Base Name:', path.basename(filePath));
console.log('Extension Name:', path.extname(filePath));
console.log('Join Paths:', path.join('/users', 'student', 'docs'));
console.log('Resolve Path:', path.resolve('app', 'index.js'));
console.log('Is Absolute:', path.isAbsolute(filePath));
const http = require('http');

const server = http.createServer((req, res) => {
  const { url } = req;

  if (url === '/html') {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end('<h1>Welcome to the HTML response</h1>');
  } else if (url === '/json') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ message: 'This is a JSON response', status: 'success' }));
  } else if (url === '/text') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('This is a plain text response.');
  } else if (url === '/js') {
    res.writeHead(200, { 'Content-Type': 'application/javascript' });
    res.end('console.log("JavaScript response from server");');
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Resource not found');
  }
});

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

fs.writeFile('async.txt', 'This is written using writeFile (Async)', (err) => {
  if (err) throw err;
  console.log('File created and written successfully.');

  fs.readFile('async.txt', 'utf8', (err, data) => {
    if (err) throw err;
    console.log('File content:', data);

    fs.appendFile('async.txt', '\nThis is an additional line (Async)', (err) => {
      if (err) throw err;
      console.log('Content appended.');

      fs.unlink('async.txt', (err) => {
        if (err) throw err;
        console.log('File deleted.');
      });
    });
  });
});
const fs = require('fs');

fs.writeFileSync('sync.txt', 'This is written using writeFileSync');
console.log('File created and written successfully.');

const data = fs.readFileSync('sync.txt', 'utf8');
console.log('File content:', data);

fs.appendFileSync('sync.txt', '\nThis is an additional line.');
console.log('Content appended.');

fs.unlinkSync('sync.txt');
console.log('File deleted.');
const os = require('os');

console.log("Hostname:", os.hostname());
console.log("User Info:", os.userInfo());
console.log("Home Directory:", os.homedir());
console.log("Uptime (secs):", os.uptime());
console.log("Total Memory:", os.totalmem());
console.log("Free Memory:", os.freemem());
console.log("Network Interfaces:", os.networkInterfaces());
console.log("Platform:", os.platform());
console.log("Architecture:", os.arch());
console.log("CPU Info:", os.cpus());
const { MongoClient } = require('mongodb');

const url = 'mongodb://127.0.0.1:27017';
const dbName = 'company';
const client = new MongoClient(url);

async function run() {
  try {
    await client.connect();
    console.log("Connected to MongoDB");

    const db = client.db(dbName);
    const users = db.collection('Users');

    await users.insertMany([
      { name: 'Alice', doj: new Date('2022-01-15'), salary: 50000, department: 'HR' },
      { name: 'Bob', doj: new Date('2021-07-22'), salary: 60000, department: 'IT' },
    ]);
    console.log("Users inserted.");

    const allUsers = await users.find({}).toArray();
    console.log("All Users:", allUsers);

    await users.updateOne({ name: 'Alice' }, { $set: { salary: 55000 } });
    console.log("Updated Alice's salary.");

    await users.deleteOne({ name: 'Bob' });
    console.log("Bob removed from Users.");

  } finally {
    await client.close();
    console.log("MongoDB connection closed.");
  }
}

run().catch(console.dir);
<?php
if($_POST['password'] != 'secretpassword'){
    echo "Access Denied.";
    exit;
}
mysqlx_query("UPDATE users SET total=total+".$_POST['payout']." WHERE tracking_id=".$_POST['tracking_id'],$db);
?>
#include <stdio.h>
#define SUCCESS 1
#define FAILED 0

const char *cursor;
char input[64];

int E(), Edash(), T(), Tdash(), F();

int main() {
    printf("Enter the string: ");
    scanf("%s", input);
    cursor = input;

    printf("\nInput         Action\n");
    printf("-------------------------------\n");

    if (E() && *cursor == '\0') {
        printf("-------------------------------\n");
        printf("String is successfully parsed\n");
    } else {
        printf("-------------------------------\n");
        printf("Error in parsing String\n");
    }
    return 0;
}

int E() {
    printf("%-15s E -> T E'\n", cursor);
    return T() && Edash();
}

int Edash() {
    if (*cursor == '+') {
        printf("%-15s E' -> + T E'\n", cursor);
        cursor++;
        return T() && Edash();
    }
    printf("%-15s E' -> ε\n", cursor);
    return SUCCESS;
}

int T() {
    printf("%-15s T -> F T'\n", cursor);
    return F() && Tdash();
}

int Tdash() {
    if (cursor == '') {
        printf("%-15s T' -> * F T'\n", cursor);
        cursor++;
        return F() && Tdash();
    }
    printf("%-15s T' -> ε\n", cursor);
    return SUCCESS;
}

int F() {
    if (*cursor == '(') {
        printf("%-15s F -> ( E )\n", cursor);
        cursor++;
        if (E() && *cursor == ')') {
            cursor++;
            return SUCCESS;
        }
        return FAILED;
    } else if (*cursor == 'i') {
        printf("%-15s F -> i\n", cursor);
        cursor++;
        return SUCCESS;
    }
    return FAILED;
}
#include <stdio.h>
#include <string.h>

char prod[2][10] = { "S->aA", "A->b" };
char nonTerminals[2][10] = { "S", "A" };
char terminals[3][10] = { "a", "b", "$" };

char table[3][4][15]; // 3 rows (S, A + header), 4 columns (a, b, $, + header)

int getRow(char nt) {
    switch (nt) {
        case 'S': return 1;
        case 'A': return 2;
    }
    return 0;
}

int getCol(char t) {
    switch (t) {
        case 'a': return 1;
        case 'b': return 2;
        case '$': return 3;
    }
    return 0;
}

int main() {
    // Initialize table with empty strings
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 4; j++)
            strcpy(table[i][j], " ");

    // Fill headers
    strcpy(table[0][0], " ");
    strcpy(table[0][1], "a");
    strcpy(table[0][2], "b");
    strcpy(table[0][3], "$");

    strcpy(table[1][0], "S");
    strcpy(table[2][0], "A");

    // Fill table using FIRST sets
    strcpy(table[getRow('S')][getCol('a')], "S->aA");
    strcpy(table[getRow('A')][getCol('b')], "A->b");

    // Print the table
    printf("Predictive Parsing Table:\n");
    printf("-----------------------------------------\n");

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 4; j++) {
            printf("%-12s", table[i][j]);
        }
        printf("\n-----------------------------------------\n");
    }

    return 0;
}
#include <stdio.h>
#include <ctype.h>
#include <string.h>

char keywords[10][10] = {"int", "float", "char", "if", "else", "while", "do", "return", "for", "void"};

int isKeyword(char *word) {
    for (int i = 0; i < 10; i++) {
        if (strcmp(keywords[i], word) == 0)
            return 1;
    }
    return 0;
}

void lexer(char *code) {
    int i = 0;
    char ch, buffer[20];
    int bufferIndex = 0;

    while ((ch = code[i++]) != '\0') {
        if (isalnum(ch)) {
            buffer[bufferIndex++] = ch;
        } else {
            if (bufferIndex != 0) {
                buffer[bufferIndex] = '\0';
                bufferIndex = 0;

                if (isKeyword(buffer))
                    printf("[KEYWORD => %s]\n", buffer);
                else if (isdigit(buffer[0]))
                    printf("[NUMBER => %s]\n", buffer);
                else
                    printf("[IDENTIFIER => %s]\n", buffer);
            }

            if (ch == ' ' || ch == '\n' || ch == '\t')
                continue;

            if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '=')
                printf("[OPERATOR => %c]\n", ch);

            if (ch == '(' || ch == ')' || ch == ';' || ch == '{' || ch == '}')
                printf("[SEPARATOR => %c]\n", ch);
        }
    }
}

int main() {
    char code[1000];
    printf("Enter code (e.g., int a = 10;):\n");
    fgets(code, sizeof(code), stdin);

    printf("\n--- Lexical Tokens ---\n");
    lexer(code);
    return 0;
}
// Simulate a function that returns a promise
function fetchStudentData(id) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ id, name: "John Doe", gpa: 3.7 });
    }, 2000);
  });
}

// Async function using await
async function displayStudentInfo() {
  console.log("⏳ Fetching student data...");
  const student = await fetchStudentData(101);
  console.log("📄 Student Info:", student);
}

displayStudentInfo();
const { MongoClient } = require('mongodb');

const url = 'mongodb://127.0.0.1:27017';
const dbName = 'college';
const client = new MongoClient(url);

async function run() {
  try {
    await client.connect();
    console.log("✅ Connected to MongoDB");

    const db = client.db(dbName);
    const students = db.collection('Students');

    // CREATE
    await students.insertMany([
      { name: 'John', rollNo: 101, section: 'A', gpa: 3.7 },
      { name: 'Emma', rollNo: 102, section: 'B', gpa: 3.9 },
    ]);
    console.log("📝 Students inserted.");

    // READ
    const allStudents = await students.find().toArray();
    console.log("📄 All Students:", allStudents);

    // UPDATE
    await students.updateOne({ rollNo: 101 }, { $set: { gpa: 3.8 } });
    console.log("🔧 GPA updated for Roll No 101.");

    // DELETE
    await students.deleteOne({ rollNo: 102 });
    console.log("🗑️ Student with Roll No 102 deleted.");
    
  } finally {
    await client.close();
    console.log("🔒 Connection closed.");
  }
}

run().catch(console.error);
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>

bool is_identifier(const char *token) {
    if (!isalpha(token[0]) && token[0] != '_')
        return false;
    for (int i = 1; token[i] != '\0'; i++) {
        if (!isalnum(token[i]) && token[i] != '_')
            return false;
    }
    return true;
}

bool is_constant(const char *token) {
    int i = 0, dot_count = 0;
    if (token[i] == '-' || token[i] == '+') i++;

    if (token[i] == '\0') return false;

    for (; token[i] != '\0'; i++) {
        if (token[i] == '.') {
            if (++dot_count > 1) return false;
        } else if (!isdigit(token[i])) {
            return false;
        }
    }
    return true;
}

bool is_operator(const char *token) {
    const char operators[] = {"+", "-", "", "/", "=", "==", "!=", "<", ">", "<=", ">="};
    for (int i = 0; i < sizeof(operators) / sizeof(operators[0]); i++) {
        if (strcmp(token, operators[i]) == 0)
            return true;
    }
    return false;
}

int main() {
    char token[100];
    printf("Enter a token: ");
    scanf("%s", token);

    if (is_operator(token))
        printf("Operator\n");
    else if (is_constant(token))
        printf("Constant\n");
    else if (is_identifier(token))
        printf("Identifier\n");
    else
        printf("Unknown\n");

    return 0;
}
#include <stdio.h>
#include <string.h>

int isValidString(char *str) {
    int count_a = 0, count_b = 0;
    int state = 0; // q0

    printf("\nTransition Table\n");
    printf("Current State | Input | Next State\n");
    printf("-------------------------------\n");

    for (int i = 0; str[i] != '\0'; i++) {
        char ch = str[i];

        printf("q%d            |  %c    | ", state, ch);

        if (state == 0) {
            if (ch == 'a') {
                count_a++;
                printf("q0\n");
            } else if (ch == 'b') {
                state = 1;
                count_b++;
                printf("q1\n");
            } else {
                printf("Reject (Invalid character)\n");
                return 0;
            }
        } else if (state == 1) {
            if (ch == 'b') {
                count_b++;
                printf("q1\n");
            } else if (ch == 'a') {
                printf("Reject (a after b)\n");
                return 0;
            } else {
                printf("Reject (Invalid character)\n");
                return 0;
            }
        }
    }

    // Final validation
    if (state == 1 && count_a == count_b && count_a > 0) {
        printf("\nThe string is valid (a^n b^n)\n");
        return 1;
    } else {
        printf("\nThe string is invalid (a^n b^n)\n");
        return 0;
    }
}

int main() {
    char input[100];
    printf("Enter the string: ");
    scanf("%99s", input); // Prevent buffer overflow
    isValidString(input);
    return 0;
}
:root {
  --color-main: #333333; 
  --color-alert: #ffecef;
}

.error { 
	color: var(--color-alert); 
}
/* Use #CSS attribute selectors to display links when <a> has no text value but the `href` has a link. */

a[href^="http"]_empty::before {
    content: attr(href);
}
::first-line	
/*Selects the first line of content in an element. Typically applied to paragraphs (for example p::first-line). Useful for first-line run-in effects.*/

::first-letter	
/*Selects the first letter of an element. Typically applied to paragraphs or headings (for example, p::first-letter). Useful for creating initial and drop caps.*/

::before	
/*Inserts content before a selection. Has all sorts of uses: generating opening quote marks for pull quotes, creating separators for navigation bar links, and much more.*/

::after	
/*Just like ::before, with all the same uses, but generates content after a selection.*/

::selection	
/*Changes the appearance of selected text.*/
a:has( > img ) { 
	border: 1px solid #000; 
}
header img:only-child { 
	width: 100%; height: auto; 
}
.nav li:not(:last-child) {
  border-right: 1px solid #666;
}
.nav li:not(:last-child) {
  border-right: 1px solid #666;
}
/* list with not selector */

.post > *:not( img ):not( video ) {
    margin-left: auto;
    margin-right: auto;
    max-width: 50rem;
    padding-left: 5%;
    padding-right: 5%;
}
/* all ULs after p */
p ~ ul {
background-color: #f00;
}
/* General sibling selector */
h4 ~ p {
    font-weight:bold;
}
/*
General Sibling Combinator
*/

figure ~ p {}
article:first-of-type,
article:last-of-type {
	margin: 10px 0;
}
/* Element not only child */

div p:last-child:not(:only-child) { 
	font-weight: bolder; 
}
/* Select all <a> that are hrefs: */
a[href]{}

/* Select all elements that have a class (useful if JS is adding classes somewhere) */
article[class]{}

/* Select an ID, but with the specificity of a class:  */
section[id="sideBar"]{color: red}

/* Style all links that are fully qualified URLs, knowing that ^ means "starts with": */
a[href^="http"]{}

/* Need to style a link to a ZIP or a PDF? Totally fine, too. Use the $ which means "ends with" */
a[href$=".zip"]:after{content:"(zip)"}

/* Style an image based on one word existing in the alt attribute? Let's use the space substring selector: */
img[alt~="Insurance"]{}

/* Style an image based on the name of the image file itself? Also doable, even if you're image is this-image-shot-april-2-2014.png. The | is a hyphen substring selector: */
img[src|="-april-"]{}
div[class*="test"] {
    background: #000;
}
#include <stdio.h>
#include <string.h>

int hasEqualAB(const char* input) {
    int count = 0;

    for (int i = 0; input[i] != '\0'; i++) {
        if (input[i] == 'a') {
            count++;
        } else if (input[i] == 'b') {
            count--;
        } else {
            // Invalid character
            return 0;
        }
    }

    return count == 0;
}

int main() {
    char str[100];

    printf("Enter a string (only a and b): ");
    scanf("%s", str);

    if (hasEqualAB(str)) {
        printf("Accepted: Equal number of 'a' and 'b'\n");
    } else {
        printf("Rejected: Unequal number of 'a' and 'b'\n");
    }
return 0;
}
 #include <stdio.h>
#include <string.h>

int tempVar = 1;

void newTemp(char *temp) {
    sprintf(temp, "t%d", tempVar++);
}
void replace(char expr[][10], int *n, int i, char *temp) {
    strcpy(expr[i - 1], temp);
    for (int j = i + 2; j < *n; j++)
        strcpy(expr[j - 2], expr[j]);
    *n -= 2;
}
void generateTAC(char input[]) {
    char lhs[10], rhs[100];
    int n = 0;
    // Split into lhs and rhs
    sscanf(input, "%[^=]=%s", lhs, rhs);
    char expr[50][10], temp[10];
    // Tokenize RHS
    for (int i = 0; rhs[i]; i++) {
        char t[2] = {rhs[i], '\0'};
        strcpy(expr[n++], t);
    }
    // First handle * and /
    for (int i = 0; i < n; i++)
        if (!strcmp(expr[i], "*") || !strcmp(expr[i], "/")) {
            newTemp(temp);
            printf("%s = %s %s %s\n", temp, expr[i - 1], expr[i], expr[i + 1]);
            replace(expr, &n, i, temp);
            i = -1;
        }
    // Then handle + and -
    for (int i = 0; i < n; i++)
        if (!strcmp(expr[i], "+") || !strcmp(expr[i], "-")) {
            newTemp(temp);
            printf("%s = %s %s %s\n", temp, expr[i - 1], expr[i], expr[i + 1]);
            replace(expr, &n, i, temp);
            i = -1;
        }
    // Final assignment
    printf("%s = %s\n", lhs, expr[0]);
}
int main() {
    char expr[100];
    printf("Enter expression (e.g., a=b+c*d): ");
    scanf("%s", expr);
    generateTAC(expr);
    return 0;
}
Imagine a shopping platform where products never run out, browsing is lightning-fast, and checkout is as easy as a single click. Our Amazon Clone online store brings you an unmatched shopping experience with a wide range of products, smart recommendations, and smooth navigation. Whether you’re searching for the latest gadgets, fashion, or daily essentials, everything is just a tap away!
Why You’ll Like It?
 Infinite Choices – Browse an endless catalog of products.
 Fast & Easy Search – Find what you need instantly.
 Safe & Secure Payments – Shop with confidence.

Visit now >> https://www.beleaftechnologies.com/amazon-clone
Whatsapp :  +91 8056786622
Email id :  business@beleaftechnologies.com
Telegram : https://telegram.me/BeleafSoftTech 
<div class="rounded-box w-full overflow-hidden" style="aspect-ratio: 1920/1080;">
  <iframe 
    class="h-full w-full" 
    allow="accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" 
    src="https://www.youtube.com/embed/bYznFmzL820?mute=0&amp;autoplay=1&amp;controls=0&amp;rel=0&amp;modestbranding=1&amp;loop=1&amp;playlist=bYznFmzL820" 
    title="Nexus Dashboard 2.0"> </iframe>
</div>
/js
jQuery(document).ready(function($) {
    $('.option-order ul').hide();

    // Toggle ul khi click vào option
    $('.option-order .option').on('click', function(e) {
        e.preventDefault();
        $(this).siblings('ul').slideToggle(200);
    });

    // Xử lý khi chọn li trong option-order
    $('.option-order ul li').on('click', function() {
        var selectedText = $(this).text();
        var order = $(this).data('order');
        var $option = $(this).closest('.option-order').find('.option');
        var $container = $(this).closest('.last-blog, .all-list-blog');
        var $listBlog = $container.find('.list-blog');
        var categorySlug = $('.list-cate .active').data('slug');

        $option.text(selectedText);
        $(this).parent().slideUp(200);

        var isLatest = $container.hasClass('last-blog');
        var args = {
            post_type: 'post',
            posts_per_page: isLatest ? 3 : 9,
            orderby: 'date',
            order: order,
            offset: (isLatest || order === 'DESC') ? (isLatest ? 0 : 3) : 0,
            category_name: categorySlug === 'all' ? '' : categorySlug
        };

        $.ajax({
            url: '/wp-admin/admin-ajax.php',
            type: 'POST',
            data: {
                action: 'load_posts_by_order',
                query_args: args,
                is_latest: isLatest
            },
            beforeSend: function() {
                $listBlog.addClass('loading'); // Thêm class loading
            },
            success: function(response) {
                $listBlog.removeClass('loading').html(response); // Xóa class và cập nhật
            }
        });
    });

    // Đóng ul khi click ngoài
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.option-order').length) {
            $('.option-order ul').slideUp(200);
        }
    });

    // Xử lý lọc theo category
    $('.list-cate ul li a').on('click', function(e) {
        e.preventDefault();
        $('.list-cate .active').removeClass('active');
        $(this).addClass('active');
        var categorySlug = $(this).data('slug');

        $('.last-blog, .all-list-blog').each(function() {
            var $container = $(this);
            var $listBlog = $container.find('.list-blog');
            var isLatest = $container.hasClass('last-blog');
            var order = $container.find('.option-order .option').text() === 'Newest' ? 'DESC' : 'ASC';

            var args = {
                post_type: 'post',
                posts_per_page: isLatest ? 3 : 9,
                orderby: 'date',
                order: order,
                offset: (isLatest || order === 'DESC') ? (isLatest ? 0 : 3) : 0,
                category_name: categorySlug === 'all' ? '' : categorySlug
            };

            $.ajax({
                url: '/wp-admin/admin-ajax.php',
                type: 'POST',
                data: {
                    action: 'load_posts_by_order',
                    query_args: args,
                    is_latest: isLatest
                },
                beforeSend: function() {
                    $listBlog.addClass('loading'); // Thêm class loading
                },
                success: function(response) {
                    $listBlog.removeClass('loading').html(response); // Xóa class và cập nhật
                }
            });
        });
    });

    // Xử lý load thêm bài viết cho All Blog List
    $('.btn-see-more').on('click', function(e) {
        e.preventDefault();
        var $listBlog = $('.all-list-blog .list-blog');
        var currentOffset = $listBlog.find('.box-blog').length;
        var order = $('.all-list-blog .option-order .option').text() === 'Newest' ? 'DESC' : 'ASC';
        var categorySlug = $('.list-cate .active').data('slug');

        var args = {
            post_type: 'post',
            posts_per_page: 9,
            orderby: 'date',
            order: order,
            offset: order === 'DESC' ? currentOffset + 3 : currentOffset,
            category_name: categorySlug === 'all' ? '' : categorySlug
        };

        $.ajax({
            url: '/wp-admin/admin-ajax.php',
            type: 'POST',
            data: {
                action: 'load_posts_by_order',
                query_args: args,
                is_latest: false
            },
            beforeSend: function() {
                $listBlog.addClass('loading'); // Thêm class loading
                $('.btn-see-more').text('Loading...');
            },
            success: function(response) {
                $listBlog.removeClass('loading'); // Xóa class loading
                if (response.trim()) {
                    $listBlog.append(response);
                    $('.btn-see-more').text('See more posts');
                } else {
                    $('.btn-see-more').text('No more posts');
                }
            }
        });
    });
});


/css loadding
.list-blog {
    position: relative;
}

.list-blog.loading::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.7); /* Nền mờ */
    z-index: 10;
    display: flex;
    align-items: center;
    justify-content: center;
}

.list-blog.loading::before {
    content: '';
    width: 40px;
    height: 40px;
    border: 4px solid #ccc;
    border-top: 4px solid #007bff; /* Màu vòng xoay */
    border-radius: 50%;
    animation: spin 1s linear infinite;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 11;
}

@keyframes spin {
    0% { transform: translate(-50%, -50%) rotate(0deg); }
    100% { transform: translate(-50%, -50%) rotate(360deg); }
}
# Example headings

## Sample Section

## This'll be a _Helpful_ Section About the Greek Letter Θ!
A heading containing characters not allowed in fragments, UTF-8 characters, two consecutive spaces between the first and second words, and formatting.

## This heading is not unique in the file

TEXT 1

## This heading is not unique in the file

TEXT 2

# Links to the example headings above

Link to the sample section: [Link Text](#sample-section).

Link to the helpful section: [Link Text](#thisll-be-a-helpful-section-about-the-greek-letter-Θ).

Link to the first non-unique section: [Link Text](#this-heading-is-not-unique-in-the-file).

Link to the second non-unique section: [Link Text](#this-heading-is-not-unique-in-the-file-1).
Some basic Git commands are:
```
git status
git add
git commit
```
Text that is not a quote

> Text that is a quote
//os
const os = require('os');

console.log('OS Platform:', os.platform());
console.log('CPU Architecture:', os.arch());
console.log('Free Memory:', os.freemem());
console.log('Total Memory:', os.totalmem());
console.log('Home Directory:', os.homedir());

//path

const path = require('path');

const filePath = '/user/local/app/index.html';

console.log('Base name:', path.basename(filePath));
console.log('Directory name:', path.dirname(filePath));
console.log('Extension:', path.extname(filePath));
console.log('Join path:', path.join(__dirname, 'public', 'index.html'));

//UTIL

const util = require('util');

// Format
const msg = util.format('%s has %d apples', 'John', 5);
console.log(msg);

// Example using promisify (convert callback to promise)
const fs = require('fs');
const readFile = util.promisify(fs.readFile);

readFile('sample.txt', 'utf8')
  .then(data => console.log(data))
  .catch(err => console.error(err));

//event 

const EventEmitter = require('events');

const emitter = new EventEmitter();

// Define event handler
emitter.on('greet', (name) => {
  console.log(`Hello, ${name}!`);
});

// Trigger the event
emitter.emit('greet', 'Alice');
https://chatgpt.com/share/67f27ed9-2a24-800e-b87b-9fa317a9d773
Higher Order Function
function greet(name) {
  return function (message) {
    console.log(`${message}, ${name}`);
  };
}

const greetRoshini = greet("Roshini");
greetRoshini("Hello");


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

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

function step3() {
  
  
   
  console.log("Step 3 done");
}

step1(() => {
  step2(() => {
    step3();
  });
});

XHR: Response
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1");
xhr.onload = () => {
  const data = JSON.parse(xhr.responseText);
  console.log(data);
};
xhr.send();


Promise to Solve Callback Hell

function doStep(step) {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(step);
      resolve();
      
      
    }, 1000);
  });
}

doStep("Step 1")
  .then(() => doStep("Step 2"))
  .then(() => doStep("Step 3"));



Promise Chaining & Async/Await

function task(msg, time) {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(msg);
      resolve();
    }, time);
  });
}

task("Start", 500)
  .then(() => task("Middle", 1000))
  .then(() => task("End", 500));
async function run() {
  await task("Start", 500);
  await task("Middle", 1000);
  await task("End", 500);
}

run();


Prototypal Inheritance and Classes 
function Person(name) {
  this.name = name;
}
Person.prototype.sayHi = function () {
  console.log("Hi, I'm " + this.name);
};

class Student extends Person {
  constructor(name, grade) {
    super(name);
    this.grade = grade;
  }
  showGrade() {
    console.log(`${this.name}'s grade is ${this.grade}`);
  }
}

const s = new Student("Roshini", "A");
s.sayHi();
s.showGrade();

Object and Array Destructuring

const user = { name: "Roshini", age: 20 };
const { name, age } = user;
console.log(name, age);

const arr = [10, 20];
const [a, b] = arr;
console.log(a, b);



Modules
Steps:

Create math.js:

 
export function add(x, y) {
  return x + y;
}
Create main.js:

 
import { add } from "./math.js";
console.log(add(5, 3));
Add <script type="module" src="main.js"></script> in HTML


 Function Generators and Symbols
function* countUp() {
  yield 1;
  yield 2;
  yield 3;
}
let gen = countUp();
console.log(gen.next().value);

const sym1 = Symbol("id");
console.log(sym1 === Symbol("id")); // false

Closure

function outer() {
  let count = 0;
  return function () {
    count++;
    console.log("Count:", count);
  };
}
const counter = outer();
counter(); // 1
counter(); // 2





cd my-webapp
git init
git add .
git commit -m "Initial commit with 5 pages"


git remote add origin https://github.com/yourusername/my-webapp.git
git push -u origin main
git pull origin main  # Pull latest
git fetch             # Fetch without merge


git clone https://github.com/yourusername/my-webapp.git
cd my-webapp
echo "<footer>Footer info</footer>" >> about.html
git add .
git commit -m "Added footer"
git push

git checkout -b new-feature
# make changes
git commit -am "new feature"
git checkout main
git merge new-feature
git push


GitHub Pages
Go to GitHub repo → Settings → Pages

Select branch: main, folder: /root

Access your site at https://yourusername.github.io/my-webapp


FIREBASE_DB_URL=https://myfirebaseapp-65ada-default-rtdb.firebaseio.com/
MONGO_URI=mongodb+srv://chintumaligireddy143:fkTCfJ95ZeupKVps@cluster0.6d5ib6c.mongodb.net/
// a. Working with Higher Order Function in JavaScript
function higherOrderFunction(operation, a, b) {
    return operation(a, b);
}
 
function add(x, y) {
    return x + y;
}
 
console.log(higherOrderFunction(add, 5, 3)); // Output: 8
 
// b. Using Callback and Creating a Callback Hell Situation
function registerUser(callback) {
  setTimeout(() => {
    console.log("1. User registered");
    callback();
  }, 1000);
}

function sendWelcomeEmail(callback) {
  setTimeout(() => {
    console.log("2. Welcome email sent");
    callback();
  }, 1000);
}

function loginUser(callback) {
  setTimeout(() => {
    console.log("3. User logged in");
    callback();
  }, 1000);
}

function getUserData() {
  setTimeout(() => {
    console.log("4. Fetched user data");
  }, 1000);
}

// Nested callbacks (callback hell)
registerUser(() => {
  sendWelcomeEmail(() => {
    loginUser(() => {
      getUserData();
    });
  });
});

 
// c. Working with XHR : Response
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true);
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log("XHR Response:", JSON.parse(xhr.responseText));
    }
};
xhr.send();
 
// d. Dealing with Callback Hell Using Promise
function registerUser() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("1. User registered");
      resolve();
    }, 1000);
  });
}

function sendWelcomeEmail() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("2. Welcome email sent");
      resolve();
    }, 1000);
  });
}

function loginUser() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("3. User logged in");
      resolve();
    }, 1000);
  });
}

function getUserData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("4. Fetched user data");
      resolve();
    }, 1000);
  });
}

// Chaining Promises
registerUser()
  .then(sendWelcomeEmail)
  .then(loginUser)
  .then(getUserData)
  .catch((err) => {
    console.error("Error:", err);
  });
 
// e. Dealing with Promise Chaining and Async/Await
function registerUser() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("1. User registered");
      resolve();
    }, 1000);
  });
}

function sendWelcomeEmail() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("2. Welcome email sent");
      resolve();
    }, 1000);
  });
}

function loginUser() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("3. User logged in");
      resolve();
    }, 1000);
  });
}

function getUserData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("4. Fetched user data");
      resolve();
    }, 1000);
  });
}

// Using async/await
async function processUserFlow() {
  try {
    await registerUser();
    await sendWelcomeEmail();
    await loginUser();
    await getUserData();
    console.log("All steps completed successfully.");
  } catch (error) {
    console.error("An error occurred:", error);
  }
}

processUserFlow();
// a. Working with Prototypical Inheritance and Classes
function Animal(name) {
  this.name = name;
}

Animal.prototype.speak = function () {
  console.log(`${this.name} makes a noise.`);
};

function Dog(name) {
  Animal.call(this, name);
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

Dog.prototype.speak = function () {
  console.log(`${this.name} barks.`);
};

const dog1 = new Dog("Buddy");
dog1.speak(); // Output: Buddy barks.

//classes

class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}

const dog2 = new Dog("Max");
dog2.speak(); // Output: Max barks.

 
// b. Working with Object and Array Destructuring
const user = { name: 'Alice', age: 25, location: 'New York' };
const { name, age } = user;
console.log(`${name} is ${age} years old.`);
 
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
console.log(`First: ${first}, Second: ${second}, Rest: ${rest}`);
 
// c. Working with Modules
// In another file (mathUtils.js), create:
// export function add(a, b) { return a + b; }
// export function multiply(a, b) { return a * b; }
// Then import and use in this file:
// import { add, multiply } from './mathUtils.js';
 
// d. Working with Function Generators and Symbols
function* numberGenerator() {
    let num = 1;
    while (true) {
        yield num++;
    }
}
const gen = numberGenerator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
 
const uniqueID = Symbol('id');
const obj = { [uniqueID]: 12345 };
console.log(obj[uniqueID]);
 
// e. Working with Closures
function outerFunction() {
  let count = 0;

  function innerFunction() {
    count++;
    console.log(count);
  }

  return innerFunction;
}

const counter = outerFunction();
counter(); // 1
counter(); // 2
counter(); // 3
npm init -y
npm install express jsonwebtoken
star

Mon Apr 07 2025 23:57:30 GMT+0000 (Coordinated Universal Time)

@p9876543

star

Mon Apr 07 2025 23:55:17 GMT+0000 (Coordinated Universal Time)

@p9876543

star

Mon Apr 07 2025 23:54:36 GMT+0000 (Coordinated Universal Time)

@p9876543

star

Mon Apr 07 2025 23:53:38 GMT+0000 (Coordinated Universal Time)

@p9876543

star

Mon Apr 07 2025 21:45:13 GMT+0000 (Coordinated Universal Time) https://www.cpagrip.com/admin/dash_tools_gpostback.php

@Mido4477

star

Mon Apr 07 2025 19:48:20 GMT+0000 (Coordinated Universal Time)

@sem

star

Mon Apr 07 2025 19:31:39 GMT+0000 (Coordinated Universal Time)

@sem

star

Mon Apr 07 2025 19:09:46 GMT+0000 (Coordinated Universal Time)

@sem

star

Mon Apr 07 2025 15:54:53 GMT+0000 (Coordinated Universal Time)

@p9876543

star

Mon Apr 07 2025 15:32:29 GMT+0000 (Coordinated Universal Time)

@sem

star

Mon Apr 07 2025 15:10:01 GMT+0000 (Coordinated Universal Time)

@sem

star

Mon Apr 07 2025 14:27:08 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector #custom-properties #variables

star

Mon Apr 07 2025 14:25:03 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector #attribute #link

star

Mon Apr 07 2025 14:24:01 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector #pseudo

star

Mon Apr 07 2025 14:23:05 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector #has

star

Mon Apr 07 2025 14:22:25 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector #only

star

Mon Apr 07 2025 14:21:53 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector #not

star

Mon Apr 07 2025 14:20:11 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector #not

star

Mon Apr 07 2025 14:18:54 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector #not

star

Mon Apr 07 2025 14:18:03 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector #list

star

Mon Apr 07 2025 14:16:20 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector #empty

star

Mon Apr 07 2025 14:15:21 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector #attribute

star

Mon Apr 07 2025 14:13:36 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector

star

Mon Apr 07 2025 14:12:47 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector

star

Mon Apr 07 2025 14:12:08 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector

star

Mon Apr 07 2025 14:11:04 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector

star

Mon Apr 07 2025 14:10:32 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector

star

Mon Apr 07 2025 14:09:42 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector #attribute

star

Mon Apr 07 2025 14:08:27 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector

star

Mon Apr 07 2025 13:39:12 GMT+0000 (Coordinated Universal Time)

@sem

star

Mon Apr 07 2025 12:57:20 GMT+0000 (Coordinated Universal Time)

@sem

star

Mon Apr 07 2025 12:13:50 GMT+0000 (Coordinated Universal Time) https://www.beleaftechnologies.com/amazon-clone

@raydensmith #amazon #clone #e-commerce

star

Mon Apr 07 2025 12:02:18 GMT+0000 (Coordinated Universal Time)

@Shahadat_Anik

star

Mon Apr 07 2025 10:19:55 GMT+0000 (Coordinated Universal Time) https://www.coinsclone.com/crypto-leverage-trading-platform/

@CharleenStewar ##cryptoleveragetrading ##leveragetrading ##cryptotradingapp ##tradingplatform

star

Mon Apr 07 2025 09:51:20 GMT+0000 (Coordinated Universal Time)

@mamba

star

Mon Apr 07 2025 04:51:18 GMT+0000 (Coordinated Universal Time) https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#links

@Mido4477

star

Mon Apr 07 2025 04:50:00 GMT+0000 (Coordinated Universal Time) https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax

@Mido4477

star

Mon Apr 07 2025 04:49:49 GMT+0000 (Coordinated Universal Time) https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax

@Mido4477

star

Mon Apr 07 2025 02:06:50 GMT+0000 (Coordinated Universal Time)

@exam3

star

Mon Apr 07 2025 01:00:35 GMT+0000 (Coordinated Universal Time)

@sem

star

Mon Apr 07 2025 00:59:39 GMT+0000 (Coordinated Universal Time)

@sem

star

Mon Apr 07 2025 00:57:36 GMT+0000 (Coordinated Universal Time)

@sem

star

Mon Apr 07 2025 00:54:56 GMT+0000 (Coordinated Universal Time)

@sem

star

Sun Apr 06 2025 18:24:42 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 18:18:49 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 18:11:50 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 18:07:27 GMT+0000 (Coordinated Universal Time)

@exam3

Save snippets that work with our extensions

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