How to Match decimal numbers and currency in Regex.mp4

 



Download How to Match decimal numbers and currency in Regex.mp4


Here’s a simple and easy explanation of how to match decimal numbers and currency values using Regex, along with clear examples.


✔️ Matching Decimal Numbers & Currency in Regex

Image

Image


🟦 1. Matching Decimal Numbers

Decimal numbers are numbers that may have a decimal point.

Examples:

12
12.5
0.99
.75
150.00

✅ Basic Regex for Decimal Numbers

\d+(\.\d+)?

✔️ Explanation

  • \d+ → one or more digits

  • (.\d+)? → optional decimal part

    • \. → the dot

    • \d+ → digits after the dot

    • ? → the whole decimal part is optional

✔️ Matches

  • 12

  • 12.5

  • 150.00

❌ Does NOT match

  • .75 (because it requires digits before the dot)


🟦 2. Matching Decimals With Optional Leading Zero

If you want to allow numbers like .75, use this:

✅ Regex

\d*(\.\d+)?

✔️ Matches

  • .75

  • 0.75

  • 12.9

  • 12


🟦 3. Allowing Either Integer or Decimal, but Not Empty

This is often used in real applications.
You want either:

  • digits only → 45

  • digits + decimals → 45.90

  • dot + decimals → .90

✅ Better Regex

\d+(\.\d+)?|\.\d+

🟦 4. Matching Currency Values (₹, $, €, etc.)

Currency usually has:

  • Symbol → $, , , £

  • Decimal part with exactly 2 digits → .00, .50, .99

  • Optional commas → 1,000.50

Examples:

$10.99
₹1,200.00
€0.50
£99

✔️ 4.1 Currency With Symbol & Optional Decimal

✅ Regex

[$₹€£]\d+(\.\d{2})?

✔️ Explanation

  • [$₹€£] → matches one symbol

  • \d+ → the number

  • (\.\d{2})? → optional .00 decimal part with 2 digits

✔️ Matches

  • $10

  • $10.99

  • ₹50.00

  • €9.50


✔️ 4.2 Currency With Commas (1,000.00)

✅ Regex

[$₹€£]\d{1,3}(,\d{3})*(\.\d{2})?

✔️ Explanation

  • \d{1,3} → first group (1–3 digits)

  • (,\d{3})* → optional groups of ,000

  • (.\d{2})? → optional decimal part

✔️ Matches

  • $1,000.00

  • ₹25,50,000.99 (Indian numbering also works depending on format)

  • €999.50


🟩 5. Currency Without Symbol (just numbers like 10.99)

If you want to match only valid currency decimals, exactly 2 digits:

✅ Regex

\d+(\.\d{2})?

✔️ Matches:

  • 10

  • 10.99

❌ Does NOT match:

  • 10.9

  • 10.999


🟩 6. Complete Universal Regex

Match currency numbers with optional:

  • symbol

  • commas

  • decimals

✅ Universal Regex

([$₹€£])?\d{1,3}(,\d{3})*(\.\d{2})?

🎉 Summary (Super Simple)

Purpose Regex
Basic decimal \d+(\.\d+)?
Allow .75 \d*(\.\d+)?
Currency with symbol [$₹€£]\d+(\.\d{2})?
Currency with commas [$₹€£]\d{1,3}(,\d{3})*(\.\d{2})?
Strict 2-decimal currency \d+(\.\d{2})?

Enjoy! Follow us for more... 

Explaination about Shorthand character sets.mp4



Download Explanation about Regex shortnand character sets.mp4

 Here’s a simple and clear explanation of the most common Regex shorthand character sets, with easy examples to help you understand how they work.


Regex Shorthand Character Sets (Explained Simply)

Regular expressions (regex) use shorthand character sets to make pattern-matching easier.
Instead of writing long character ranges, you can use short symbols like \d, \w, \s, etc.

Below is a friendly explanation of each.


🔹 1. \d → Digit characters

Meaning: Matches any number from 0–9

Examples:

  • Regex: \d
    Matches: 3 in "A3Z"

  • Regex: \d\d
    Matches: "45" in "Age: 45"


🔹 2. \D → Non-digit characters

Meaning: Matches anything except 0–9

Examples:

  • Regex: \D
    Matches: A in "A3"

  • Regex: \D+
    Matches: "Name" in "Name123"


🔹 3. \w → Word characters

Meaning: Matches

  • Letters (A–Z, a–z)

  • Numbers (0–9)

  • Underscore (_)

Examples:

  • Regex: \w
    Matches: a in "a!"

  • Regex: \w+
    Matches: "Hello123" in "Hello123!!"


🔹 4. \W → Non-word characters

Meaning: Matches anything except letters, numbers, and underscore

Examples:

  • Regex: \W
    Matches: ! in "Hi!"

  • Regex: \W+
    Matches: " @#" in "User @# Name"


🔹 5. \s → Whitespace characters

Meaning: Matches spaces, tabs, and newlines
(space, \t, \n)

Examples:

  • Regex: \s
    Matches the space in "Hello World"

  • Regex: \s+
    Matches " " (multiple spaces)


🔹 6. \S → Non-whitespace characters

Meaning: Matches anything that is not space, tab, or newline

Examples:

  • Regex: \S
    Matches: H in " Hello"

  • Regex: \S+
    Matches: "Hello" in "Hello World"


📌 Additional Character Class Shorthands (POSIX Style)

Some regex engines (like Linux grep -E, PHP, Perl) use POSIX character classes inside [[: ... :]].

Examples:

🔹 [:digit:] → Digits (0–9)

🔹 [:alpha:] → Alphabet letters (A–Z, a–z)

🔹 [:alnum:] → Letters + numbers

🔹 [:upper:] → Uppercase letters

🔹 [:lower:] → Lowercase letters

Example use:

[[:digit:]]+

Matches "2024" in "Year: 2024"


🎯 Summary Table (Quick View)

Shorthand Meaning Example Match
\d Digit 5
\D Not a digit A
\w Word character A, 3, _
\W Not word character !
\s Whitespace (space)
\S Non-whitespace H
[[:digit:]] Digit 7
[[:alpha:]] Letters A, z

Enjoy! Follow us for more... 

How to install nano for Windows.mp4

 


Download How to Install Nano on Windows .mp4



How to Install Nano on Windows

Nano is a lightweight, beginner-friendly text editor commonly used on Linux systems. You can use Nano on Windows too — through several methods.


Method 1: Install Nano Using Windows Subsystem for Linux (WSL)

(Recommended — easiest and most stable)

Step 1: Enable WSL

  1. Open PowerShell as Administrator

  2. Run:

wsl --install

After rebooting, Windows will install a Linux distribution (usually Ubuntu).


Step 2: Update Linux

Open the Linux terminal and run:

sudo apt update

Step 3: Install Nano

sudo apt install nano

✔ You can now run Nano in Windows through WSL:

nano filename.txt

Method 2: Install Nano Using Git for Windows

If you install Git for Windows, Nano is already included.

Step 1: Download Git

👉 https://git-scm.com/download/win

Step 2: Install Git

During installation:

  • On the "Choose your default editor" screen
    select Nano

After installation, open:

  • Git Bash

Now use:

nano test.txt

Method 3: Install Nano Using Chocolatey (Package Manager)

If you use Chocolatey:

Step 1: Install Chocolatey (if not installed)

Run PowerShell as Administrator:

Set-ExecutionPolicy Bypass -Scope Process -Force; `
[System.Net.ServicePointManager]::SecurityProtocol = `
[System.Net.ServicePointManager]::SecurityProtocol -bor 3072; `
iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

Step 2: Install Nano

choco install nano

Run Nano:

nano filename.txt

Method 4: Portable Nano for Windows (Manual Install)

A native Windows build exists but is less maintained.

Download:

👉 https://nano-editor.org/dist/win32-support/

After extracting:

  • Open CMD in the folder

  • Run:

nano.exe file.txt

✅ Recommended Option

If you want full Linux-like behavior:
Use WSL

If you want something quick and simple:
Use Git Bash


Enjoy! Follow us for more... 

How to Find or installing nano on Linux ?





Download How to Find or installing nano on Linux ? 


🧩 Step 1: Check if Nano is already installed

Open your terminal and run:

nano --version
  • If Nano is installed, you’ll see version information (like GNU nano, version 6.4).

  • If it’s not installed, you’ll see an error such as:
    bash: nano: command not found


🧰 Step 2: Install Nano (based on your Linux distribution)

🐧 Ubuntu / Debian / Linux Mint

sudo apt update
sudo apt install nano -y

🧱 Fedora

sudo dnf install nano -y

💿 CentOS / RHEL

sudo yum install nano -y

On newer RHEL versions (8+), you can use dnf instead of yum.

🧩 Arch Linux / Manjaro

sudo pacman -S nano

🐙 openSUSE

sudo zypper install nano

⚙️ Step 3: Verify installation

After installation, confirm again:

nano --version

If it prints version info — you’re all set!


💡 Optional: Make Nano the default editor

If you want Nano to open automatically for things like git commit messages or crontab -e, set it as the default editor:

export EDITOR=nano

To make this permanent, add the above line to your ~/.bashrc or ~/.zshrc.


Enjoy! Follow us for more... 

Adding automatic timestamps in SQL

 


Download Video Adding Automatic Timestamps in SQL.mp4


Adding automatic timestamps in SQL is a common practice to track when rows are created or updated. Here’s how you can do it depending on your database — I’ll focus on SQLite, since your recent topic is about SQLite 3 and PHP interface.


🧩 1. Using Automatic Timestamps in SQLite

SQLite doesn’t have a built-in CURRENT_TIMESTAMP default like MySQL’s TIMESTAMP DEFAULT CURRENT_TIMESTAMP — but you can use default expressions with datetime('now').

✅ Example: Add a timestamp when inserting new records

CREATE TABLE users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    email TEXT UNIQUE,
    created_at TEXT DEFAULT (datetime('now', 'localtime'))
);

Now when you insert a record:

INSERT INTO users (name, email)
VALUES ('Alice', 'alice@example.com');

SQLite automatically adds the current local date and time to created_at.

Result:

id name email created_at
1 Alice alice@example.com 2025-11-06 22:10:53

🕒 2. Automatically Update Timestamp on Edit

SQLite does not support automatic updates to a column when a row changes, but you can achieve it using a trigger.

✅ Example with Trigger

CREATE TABLE articles (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT,
    content TEXT,
    created_at TEXT DEFAULT (datetime('now', 'localtime')),
    updated_at TEXT
);

CREATE TRIGGER update_articles_timestamp
AFTER UPDATE ON articles
FOR EACH ROW
BEGIN
    UPDATE articles
    SET updated_at = datetime('now', 'localtime')
    WHERE id = OLD.id;
END;

Now, whenever you update a row:

UPDATE articles SET content = 'New text here' WHERE id = 1;

SQLite will automatically fill or refresh the updated_at field.


🧠 3. Using Timestamps in PHP with SQLite3 Interface

When using the PHP SQLite3 interface, you don’t need to manually generate timestamps if you’ve already set the default and trigger.

Example PHP Code:

<?php
$db = new SQLite3('example.db');

$db->exec("CREATE TABLE IF NOT EXISTS logs (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    message TEXT,
    created_at TEXT DEFAULT (datetime('now', 'localtime'))
)");

$stmt = $db->prepare("INSERT INTO logs (message) VALUES (:message)");
$stmt->bindValue(':message', 'System started', SQLITE3_TEXT);
$stmt->execute();

$result = $db->query("SELECT * FROM logs");
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    echo $row['id'] . " | " . $row['message'] . " | " . $row['created_at'] . "\n";
}
?>

Enjoy! Follow us for more... 




SQLite 3 php interface, Choosing an interface.

 


Download SQLite 3 php interface,mp4

SQLite3 is a lightweight, file-based database engine that can be easily integrated with PHP without the need for a separate server process (like MySQL or PostgreSQL). PHP comes with built-in support for SQLite3, making it great for small-to-medium applications, local storage, or prototyping.

Here’s a full guide on using the SQLite3 PHP interface 👇


🧱 1. Enabling SQLite3 in PHP

Most modern PHP installations already have SQLite3 enabled by default.
To confirm:

php -m | grep sqlite

You should see sqlite3 in the list.
If not, enable it in your php.ini by uncommenting:

extension=sqlite3

Restart your web server afterward.


⚙️ 2. Creating and Connecting to an SQLite3 Database

SQLite databases are just files on disk. You can open (or create) one using the SQLite3 class.

<?php
// Create or open a database file
$db = new SQLite3('example.db');

// Check connection
if ($db) {
    echo "Connected to SQLite3 database successfully!";
}
?>

This will create a file named example.db in your current directory.


📄 3. Creating a Table

<?php
$db = new SQLite3('example.db');

// Create a table
$query = "CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    email TEXT UNIQUE NOT NULL
)";
$db->exec($query);

echo "Table created successfully!";
?>

✏️ 4. Inserting Data

<?php
$db = new SQLite3('example.db');

$stmt = $db->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->bindValue(':name', 'Alice');
$stmt->bindValue(':email', 'alice@example.com');
$stmt->execute();

echo "Data inserted!";
?>

🔍 5. Querying Data

<?php
$db = new SQLite3('example.db');

$results = $db->query("SELECT * FROM users");

while ($row = $results->fetchArray(SQLITE3_ASSOC)) {
    echo "ID: {$row['id']} | Name: {$row['name']} | Email: {$row['email']} <br>";
}
?>

🧹 6. Updating and Deleting Data

Update Example:

$db->exec("UPDATE users SET email='alice_new@example.com' WHERE id=1");

Delete Example:

$db->exec("DELETE FROM users WHERE id=1");

🛠️ 7. Using PDO with SQLite (Alternative Method)

PDO provides a more flexible and modern way to interact with databases.

<?php
try {
    $pdo = new PDO('sqlite:example.db');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $pdo->exec("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)");
    $pdo->exec("INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com')");

    foreach ($pdo->query("SELECT * FROM users") as $row) {
        echo $row['name'] . " - " . $row['email'] . "<br>";
    }
} catch (PDOException $e) {
    echo $e->getMessage();
}
?>

🧠 8. When to Use SQLite3 in PHP

✅ Great for:

  • Small websites or internal tools

  • Local data storage

  • Desktop/web hybrid apps

  • Prototyping before using MySQL/PostgreSQL

🚫 Not ideal for:

  • High-concurrency web apps

  • Large-scale data sets

  • Distributed systems


Enjoy! Follow us for more... 

How to add mouse input in cpp programming using xCode.mp4

 


Download How to add mouse input in cpp programming using xCode.MP4


🖱️ How to Add Mouse Input in C++ Programming Using Xcode

When developing interactive graphics or games in C++ using Xcode, handling mouse input is an essential part of creating a responsive and user-friendly application. Whether you’re building a macOS app, a game engine, or an OpenGL project, learning how to add mouse input helps bring your C++ applications to life.

In this guide, we’ll explore how to add mouse input in C++ using Xcode, with code examples and key explanations.


🚀 Why Mouse Input Matters in C++ Development

In modern C++ application development, user input handling allows you to capture and respond to actions like clicks, drags, and cursor movement. If you’re using Xcode on macOS, you can easily integrate mouse events using frameworks such as Cocoa, SFML, or OpenGL.

Popular use cases:

  • Detecting mouse clicks in a game window

  • Tracking mouse movement for drawing or selecting objects

  • Handling scrolling or dragging in graphical user interfaces


🧰 Setting Up Xcode for C++ Mouse Input

Before writing the code, make sure your Xcode project is properly configured for C++:

  1. Open Xcode and create a new Command Line Tool or macOS App project.

  2. Choose C++ as your language.

  3. Set up any external libraries if you’re using OpenGL, SFML, or SDL.


🖋️ Example 1: Basic Mouse Input Using SFML in Xcode

The SFML (Simple and Fast Multimedia Library) provides an easy way to handle mouse input in C++.

🔧 Code Example:

#include <SFML/Graphics.hpp>
#include <iostream>

int main() {
    sf::RenderWindow window(sf::VideoMode(800, 600), "Mouse Input Example");

    while (window.isOpen()) {
        sf::Event event;
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed)
                window.close();

            if (event.type == sf::Event::MouseButtonPressed) {
                if (event.mouseButton.button == sf::Mouse::Left)
                    std::cout << "Left mouse button clicked at ("
                              << event.mouseButton.x << ", "
                              << event.mouseButton.y << ")" << std::endl;
            }

            if (event.type == sf::Event::MouseMoved) {
                std::cout << "Mouse moved to: (" 
                          << event.mouseMove.x << ", "
                          << event.mouseMove.y << ")" << std::endl;
            }
        }

        window.clear();
        window.display();
    }

    return 0;
}

✅ What This Code Does:

  • Detects when the mouse button is clicked.

  • Tracks mouse movement coordinates.

  • Displays the output in the Xcode console.


🧩 Example 2: Handling Mouse Input with OpenGL and GLUT

If you’re working with OpenGL, you can use GLUT (OpenGL Utility Toolkit) for mouse input:

#include <GLUT/glut.h>
#include <iostream>

void mouse(int button, int state, int x, int y) {
    if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
        std::cout << "Mouse clicked at (" << x << ", " << y << ")" << std::endl;
}

void display() {
    glClear(GL_COLOR_BUFFER_BIT);
    glFlush();
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutCreateWindow("Mouse Input in OpenGL");
    glutMouseFunc(mouse);
    glutDisplayFunc(display);
    glutMainLoop();
    return 0;
}

This approach is perfect for graphics or game programming where real-time input is required.


💡 Tips for Debugging Mouse Input in Xcode

  • Ensure your app window is focused to receive input.

  • Check that event polling loops are active.

  • Use breakpoints or console logs to verify coordinates.

  • Always rebuild the project after changing input event configurations.


🏁 Conclusion

Adding mouse input handling in C++ programming using Xcode is an essential step toward building interactive, graphical, or game-based applications. Whether you’re using SFML, GLUT, or the Cocoa framework, Xcode offers the flexibility and performance needed for professional C++ development.

Now that you’ve learned how to implement mouse input, try extending your program with keyboard input, camera control, or UI interactions to take your C++ projects to the next level!


Enjoy! Follow us for more... 

How to combined lighting and textures in cpp programming using xCode.mp4

 


Download How to combined lighting and textures in cpp programming using xCode.mp4


🧠 How to Combine Lighting and Textures in C++ Programming Using Xcode

When creating 3D applications or games in C++, achieving realism is often about mastering two essential concepts — lighting and textures. Lighting adds depth and mood, while textures bring surfaces to life. When combined, they form the foundation of realistic rendering. In this post, we’ll explore how to combine lighting and textures in C++ using Xcode, Apple’s powerful IDE.


🔧 Setting Up Your Xcode Environment

Before diving into code, make sure your environment is ready:

  1. Install Xcode from the Mac App Store.

  2. Create a new C++ Command Line Tool project.

  3. Add OpenGL (or Metal, for modern Apple graphics) frameworks.

  4. Configure your project’s build settings to link the required graphics libraries.

For OpenGL:

#include <GLUT/glut.h>
#include <OpenGL/gl.h>

💡 Step 1: Understanding Lighting

Lighting simulates how light interacts with objects. In OpenGL, you can use different types of lights — ambient, diffuse, and specular.

Here’s a simple setup for basic lighting:

void setupLighting() {
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);

    GLfloat lightPosition[] = {1.0, 1.0, 1.0, 0.0};
    GLfloat lightColor[] = {1.0, 1.0, 1.0, 1.0};
    GLfloat ambientColor[] = {0.2, 0.2, 0.2, 1.0};

    glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor);
    glLightfv(GL_LIGHT0, GL_AMBIENT, ambientColor);
}

This creates a white light shining from a position above your 3D scene.


🖼️ Step 2: Applying Textures

Textures wrap 2D images around 3D geometry to make them look detailed. You can load texture data from an image and map it to an object’s surface.

Here’s a simple example:

GLuint texture;

void loadTexture(const char* filename) {
    // Load image (pseudo-code)
    unsigned char* data = loadImage(filename); 
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    // Apply texture data
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
}

Once your texture is loaded, you can apply it to an object:

glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture);

🎨 Step 3: Combining Lighting and Textures

Now, to make both work together, we’ll enable both lighting and texturing in our render function:

void display() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);

    setupLighting();
    loadTexture("brick_wall.jpg");

    glEnable(GL_LIGHTING);
    glEnable(GL_TEXTURE_2D);

    glBegin(GL_QUADS);
        glNormal3f(0.0, 0.0, 1.0); // surface normal for lighting
        glTexCoord2f(0.0, 0.0); glVertex3f(-1.0, -1.0, 0.0);
        glTexCoord2f(1.0, 0.0); glVertex3f( 1.0, -1.0, 0.0);
        glTexCoord2f(1.0, 1.0); glVertex3f( 1.0,  1.0, 0.0);
        glTexCoord2f(0.0, 1.0); glVertex3f(-1.0,  1.0, 0.0);
    glEnd();

    glutSwapBuffers();
}

This renders a textured quad illuminated by a light source. The glNormal3f() function ensures that the lighting interacts correctly with the surface.


🧩 Step 4: Adjusting Material Properties

For finer control, you can adjust the material’s properties to influence how it reacts to light.

GLfloat mat_specular[] = {1.0, 1.0, 1.0, 1.0};
GLfloat mat_shininess[] = {50.0};

glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);

This makes your texture surface appear glossy under direct light.


🚀 Conclusion

Combining lighting and textures in C++ with Xcode can transform your 3D scenes from flat and dull to dynamic and realistic. While OpenGL is the classic way to do this, modern Apple platforms also support Metal, which offers even more performance and flexibility.

Experiment with different light positions, texture images, and material settings to bring your C++ graphics projects to life!


Enjoy! Follow us for more... 

How to create the code behind the class in cpp programming using Microsoft Visual Sytudio.mp4

 


Download How to create the code behind the class in cpp programming using Microsoft Visual Sytudio.mp4

Creating the code behind a class in C++ using Microsoft Visual Studio is a common practice to separate class declarations (in header files) from definitions (in source files) — improving readability and maintainability.

Here’s a step-by-step guide 👇


🧩 Step 1: Create a New Project

  1. Open Microsoft Visual Studio.

  2. Go to File → New → Project.

  3. Choose Console App (C++).

  4. Name your project (e.g., ClassExample) and click Create.


🧱 Step 2: Add a Header File (.h)

  1. In Solution Explorer, right-click the project → Add → New Item...

  2. Select Header File (.h) and name it, e.g., Student.h.

  3. Add the class declaration here.

Example – Student.h

#pragma once
#include <string>

class Student {
private:
    std::string name;
    int age;

public:
    Student(std::string n, int a); // Constructor declaration
    void displayInfo();            // Method declaration
};

⚙️ Step 3: Add a Source File (.cpp)

  1. Right-click the project again → Add → New Item...

  2. Choose C++ File (.cpp) and name it Student.cpp.

  3. Include the header file and define the methods.

Example – Student.cpp

#include "Student.h"
#include <iostream>
using namespace std;

Student::Student(std::string n, int a) {
    name = n;
    age = a;
}

void Student::displayInfo() {
    cout << "Name: " << name << ", Age: " << age << endl;
}

🚀 Step 4: Use the Class in main.cpp

Visual Studio automatically creates a main.cpp file. Use your class there:

Example – main.cpp

#include <iostream>
#include "Student.h"
using namespace std;

int main() {
    Student s1("Alice", 21);
    s1.displayInfo();
    return 0;
}

🧠 Step 5: Build and Run

  • Press Ctrl + F5 or click Run → Start Without Debugging

  • You’ll see:

    Name: Alice, Age: 21
    

✅ Summary

File Purpose
Student.h Class declaration (what it looks like)
Student.cpp Class definition (how it works)
main.cpp Entry point of the program


Enjoy! Follow us for more... 

How to Enhance the data model using Portable Object Notation Windows Project during build a Windows Phone App.mp4

 



Download How to Enhance the data model using Portable Object Notation Windows Project.mp4


PONWP, which likely stands for "Project Online for Windows Platform" or a “Portable Object Notation Windows Project” — a type of UWP (Universal Windows Platform) or Windows Presentation Foundation (WPF) application built in Microsoft Visual Studio.

Since “PONWP” isn’t an official Visual Studio project type, the most reasonable interpretation is that it’s a custom or internal app built on top of UWP or WPF frameworks — both of which use data models that can be enhanced via C# classes, Entity Framework, or other ORM/data-binding layers.

Let’s go step-by-step on how to enhance the data model in such a Visual Studio project.


🧩 Step-by-Step: Enhancing the Data Model in a PONWP Project

1. Open Your Solution

  • Launch Microsoft Visual Studio.

  • Open your PONWP project (or .sln file).

  • Locate the folder where your data model classes are stored — usually something like:

    /Models/
    /Data/
    /Entities/
    

2. Review the Current Model

Check your existing entity classes. For example:

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
}

Determine what you need to enhance — such as:

  • Adding new fields (e.g., Email, DateOfHire)

  • Adding relationships (e.g., EmployeeProject)

  • Creating new entity classes


3. Add or Modify Entities

Example enhancement:

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }

    // New fields
    public string Email { get; set; }
    public DateTime DateOfHire { get; set; }

    // New relationship
    public ICollection<Project> Projects { get; set; }
}

public class Project
{
    public int ProjectId { get; set; }
    public string Title { get; set; }
    public DateTime Deadline { get; set; }

    public ICollection<Employee> Employees { get; set; }
}

4. Update the Database Context

If you’re using Entity Framework (EF):

public class AppDbContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
    public DbSet<Project> Projects { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        // Define relationships
        modelBuilder.Entity<Employee>()
            .HasMany(e => e.Projects)
            .WithMany(p => p.Employees);
    }
}

5. Apply Migrations

If it’s an EF Core project:

Add-Migration EnhanceEmployeeModel
Update-Database

This updates your underlying database schema to match your new model.


6. Update Data Binding in the UI

If your PONWP app uses MVVM (Model-View-ViewModel):

  • Update your ViewModels to include the new properties.

  • Update XAML bindings to display new data.

Example:

<TextBox Text="{Binding Employee.Email, Mode=TwoWay}" Header="Email" />
<DatePicker Date="{Binding Employee.DateOfHire}" Header="Date of Hire" />

7. Update Business Logic

Modify services or repository layers that interact with your model:

public class EmployeeService
{
    private readonly AppDbContext _context;

    public EmployeeService(AppDbContext context)
    {
        _context = context;
    }

    public async Task AddEmployeeAsync(Employee employee)
    {
        _context.Employees.Add(employee);
        await _context.SaveChangesAsync();
    }
}

8. Test Your Enhancements

  • Run your project (Ctrl + F5).

  • Use Visual Studio’s Debugging tools to inspect model values.

  • Verify that new fields appear in UI and persist in the database.


9. Document and Commit

  • Update your internal documentation (ER diagrams, README, etc.).

  • Commit your changes to version control (Git):

    git add .
    git commit -m "Enhanced Employee data model with Email and Project relationships"
    

Enjoy! Follow us for more... 

How to Add normals matrix and lighting effects in cpp programming using xCode.mp4



 Download Now How to Add normals matrix and lighting effects in cpp programming using xCode.mp4


Adding normals matrices and lighting effects in C++ (especially with Xcode and OpenGL/Metal) involves understanding how 3D lighting works at the vertex or fragment level. Let’s go step-by-step using OpenGL as the graphics API, since it’s commonly used in C++ projects in Xcode.


🧩 Step 1: Understanding the Normal Matrix

When you apply transformations (rotation, scaling, translation) to your model, you must also transform the normals correctly so lighting calculations remain accurate.

The normal matrix is:
[
N = (M_{modelView})^{-1^T}
]
It’s the inverse transpose of the upper-left 3×3 portion of your model-view matrix.

This matrix ensures that normals are properly transformed, even under non-uniform scaling.


⚙️ Step 2: Example Code (C++ with OpenGL)

#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

int main() {
    glfwInit();
    GLFWwindow* window = glfwCreateWindow(800, 600, "Lighting in C++ Xcode", NULL, NULL);
    glfwMakeContextCurrent(window);
    glewInit();

    // Define transformation matrices
    glm::mat4 model = glm::rotate(glm::mat4(1.0f),
                                  glm::radians(45.0f),
                                  glm::vec3(0.0f, 1.0f, 0.0f));
    glm::mat4 view = glm::translate(glm::mat4(1.0f),
                                    glm::vec3(0.0f, 0.0f, -5.0f));
    glm::mat4 projection = glm::perspective(glm::radians(45.0f),
                                            800.0f / 600.0f,
                                            0.1f, 100.0f);

    glm::mat4 modelView = view * model;
    glm::mat3 normalMatrix = glm::transpose(glm::inverse(glm::mat3(modelView)));

    // Pass matrices to shader
    GLuint shaderProgram = LoadShaders("vertex_shader.glsl", "fragment_shader.glsl");
    glUseProgram(shaderProgram);
    glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "modelViewMatrix"), 1, GL_FALSE, glm::value_ptr(modelView));
    glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "projectionMatrix"), 1, GL_FALSE, glm::value_ptr(projection));
    glUniformMatrix3fv(glGetUniformLocation(shaderProgram, "normalMatrix"), 1, GL_FALSE, glm::value_ptr(normalMatrix));

    // Main loop
    while (!glfwWindowShouldClose(window)) {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        // Render objects here
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

💡 Step 3: Vertex Shader (GLSL)

#version 330 core
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec3 aNormal;

uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
uniform mat3 normalMatrix;

out vec3 FragPos;
out vec3 Normal;

void main() {
    FragPos = vec3(modelViewMatrix * vec4(aPos, 1.0));
    Normal = normalize(normalMatrix * aNormal);
    gl_Position = projectionMatrix * vec4(FragPos, 1.0);
}

🌟 Step 4: Fragment Shader (GLSL)

#version 330 core
in vec3 FragPos;
in vec3 Normal;
out vec4 FragColor;

uniform vec3 lightPos = vec3(5.0, 5.0, 5.0);
uniform vec3 lightColor = vec3(1.0, 1.0, 1.0);
uniform vec3 objectColor = vec3(0.5, 0.2, 0.2);

void main() {
    vec3 norm = normalize(Normal);
    vec3 lightDir = normalize(lightPos - FragPos);

    float diff = max(dot(norm, lightDir), 0.0);
    vec3 diffuse = diff * lightColor;

    vec3 result = (diffuse + 0.1) * objectColor;
    FragColor = vec4(result, 1.0);
}

🔧 Step 5: Xcode Setup

  1. Create a new C++ project.

  2. Link the following frameworks/libraries:

    • OpenGL.framework

    • GLFW and GLEW (install via Homebrew if needed)

  3. Add your shader files to the project.

  4. Run and adjust lighting parameters in real time.



Enjoy! Follow us for more... 

How to use indices of vertex buffers in cpp programming using xCode.mp4


 Download How to use indices of vertex buffers in cpp programming using xCode.mp4


Using indices with vertex buffers in C++ (especially in graphics programming, e.g., OpenGL) helps you reuse vertices efficiently — instead of repeating the same vertex data, you store it once and use an index buffer to reference it.

Let’s walk through how to use indices of vertex buffers in C++ using Xcode (on macOS), typically with OpenGL.


🎯 Goal

Render a shape (like a triangle or square) using Vertex Buffer Objects (VBOs) and Element Buffer Objects (EBOs) — the EBO holds indices.


🧩 Step-by-Step Example

1️⃣ Include headers

#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>

Make sure you’ve linked OpenGL and GLEW/GLFW frameworks in Xcode:

  • Add frameworks under:
    Build Phases → Link Binary With Libraries → + → OpenGL.framework, libGLEW, libglfw


2️⃣ Initialize GLFW and create a window

int main() {
    if (!glfwInit()) {
        std::cerr << "Failed to initialize GLFW\n";
        return -1;
    }

    GLFWwindow* window = glfwCreateWindow(800, 600, "Indexed Drawing Example", NULL, NULL);
    if (!window) {
        std::cerr << "Failed to create GLFW window\n";
        glfwTerminate();
        return -1;
    }

    glfwMakeContextCurrent(window);
    glewInit();

3️⃣ Define vertices and indices

We’ll draw a rectangle made from two triangles.

    float vertices[] = {
        // positions        // colors
        0.5f,  0.5f, 0.0f,  1.0f, 0.0f, 0.0f, // top right
        0.5f, -0.5f, 0.0f,  0.0f, 1.0f, 0.0f, // bottom right
       -0.5f, -0.5f, 0.0f,  0.0f, 0.0f, 1.0f, // bottom left
       -0.5f,  0.5f, 0.0f,  1.0f, 1.0f, 0.0f  // top left 
    };

    unsigned int indices[] = {
        0, 1, 3, // first triangle
        1, 2, 3  // second triangle
    };

4️⃣ Create buffers (VBO, VAO, EBO)

    unsigned int VBO, VAO, EBO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);

    glBindVertexArray(VAO);

    // Vertex buffer
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    // Index buffer
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

5️⃣ Define vertex attributes

    // Position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);

    // Color attribute
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
    glEnableVertexAttribArray(1);

6️⃣ Render loop

    while (!glfwWindowShouldClose(window)) {
        glClear(GL_COLOR_BUFFER_BIT);

        glBindVertexArray(VAO);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); // Use indices here

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

7️⃣ Cleanup

    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);
    glDeleteBuffers(1, &EBO);
    glfwTerminate();
    return 0;
}

💡 Key Notes

  • glDrawElements is the function that uses indices:

    glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0);
    

    It draws using the EBO instead of re-reading vertex data.

  • The EBO must remain bound while drawing.

  • The VAO stores the vertex + index buffer bindings.


🧠 Summary

Concept Purpose
VBO (Vertex Buffer Object) Stores vertex data (positions, colors, etc.)
EBO (Element Buffer Object) Stores indices that tell OpenGL which vertices to draw
VAO (Vertex Array Object) Stores the configuration of vertex attributes and buffer bindings

Enjoy! Follow us for more... 

Best Websites to Practice Python.


Python Basics 👇:

1.  http://codingbat.com/python

2.  https://www.hackerrank.com/

3.  https://www.hackerearth.com/practice/


Practice Problems set :

4.  https://projecteuler.net/archives

5.  http://www.codeabbey.com/index/task_list

6.  http://www.pythonchallenge.com/


Follow us for more... 

Free online Resources to learn Full Stack Development


CSS3 → http://web.dev/learn/css/


React → http://reactjs.org


Python → http://python.org


Java → http://java67.com


Ruby → http://gorails.com


MongoDB → http://learn.mongodb.com


AWS → http://aws.amazon.com/training


Azure → http://learn.microsoft.com/en-us/training


Git & GitHub → http://LearnGitBranching.js.org


Google Cloud → http://cloud.google.com/edu


Follow us for more... 

How to Work with the Projection matrix in cpp programming using xCode.mp4

 

Download How to Work with the Projection matrix in cpp programming using xCode.mp4


Working with a Projection Matrix in C++ (especially in graphics programming using Xcode on macOS) typically involves OpenGL or a graphics API like Metal. Since you mentioned Xcode, I’ll explain the OpenGL-based workflow, as it’s the most common for learning transformations like projection, translation, rotation, and scaling.


🧠 What Is a Projection Matrix?

A projection matrix defines how 3D points are projected onto a 2D screen.
There are two types:

  • Orthographic projection → no perspective (useful for 2D or CAD-like views).

  • Perspective projection → objects farther away appear smaller (realistic 3D view).


⚙️ Setting Up an OpenGL Project in Xcode

  1. Create a New Project

    • Open Xcode → File → New → Project.

    • Choose macOS → Command Line Tool.

    • Set Language = C++.

  2. Add OpenGL Framework

    • Go to Build Phases → Link Binary with Libraries.

    • Add:

      • OpenGL.framework

      • GLUT.framework


🧩 Example: Using a Projection Matrix

Here’s a minimal C++ OpenGL example showing how to set up and use projection matrices.

#include <GLUT/glut.h>
#include <cmath>

// Window dimensions
int width = 800, height = 600;

void reshape(int w, int h) {
    glViewport(0, 0, w, h); // Adjust viewport
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    // Create a perspective projection matrix
    gluPerspective(45.0, (double)w / (double)h, 0.1, 100.0);

    // Switch to model view for drawing
    glMatrixMode(GL_MODELVIEW);
}

void display() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();

    // Move the camera backwards
    glTranslatef(0.0f, 0.0f, -5.0f);

    // Draw a rotating cube
    static float angle = 0.0f;
    glRotatef(angle, 1.0f, 1.0f, 0.0f);

    glutWireCube(2.0);

    angle += 0.5f;
    glutSwapBuffers();
}

void timer(int value) {
    glutPostRedisplay();
    glutTimerFunc(16, timer, 0); // roughly 60 FPS
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(width, height);
    glutCreateWindow("Projection Matrix Example");

    glEnable(GL_DEPTH_TEST);

    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutTimerFunc(0, timer, 0);

    glutMainLoop();
    return 0;
}

🧮 Explanation

1. gluPerspective(fov, aspect, near, far)

Creates a perspective projection matrix:

fov    → Field of view (in degrees)
aspect → Width/height ratio
near   → Near clipping plane
far    → Far clipping plane

2. Orthographic Projection (Alternative)

If you want no perspective:

glOrtho(-2, 2, -2, 2, 0.1, 100);

3. Transformations (Model-View Matrix)

You can translate, rotate, and scale your objects after setting the projection:

glTranslatef(0.0f, 0.0f, -5.0f); // move back
glRotatef(45, 1, 0, 0);          // rotate
glScalef(1.5f, 1.5f, 1.5f);      // scale up

🧰 For Modern OpenGL (Optional)

If you’re using modern OpenGL (Core Profile), you’ll manually create matrices using libraries like GLM:

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

glm::mat4 projection = glm::perspective(glm::radians(45.0f),
                                        (float)width / (float)height,
                                        0.1f, 100.0f);

You then pass the matrix to your shader using:

glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "projection"), 1, GL_FALSE, &projection[0][0]);

✅ Summary

Task Function Description
Set projection gluPerspective() / glOrtho() Defines camera projection
Translate glTranslatef(x, y, z) Moves object
Rotate glRotatef(angle, x, y, z) Rotates object
Scale glScalef(x, y, z) Scales object size
Use GLM glm::perspective() For modern OpenGL matrix math

Would you like me to show you how to build this step-by-step in Xcode, including linking the frameworks and setting the window up properly?

How to apply Rotating, translating, and scaling in cpp programming using xCode.mp4

 
Download How to apply Rotating, translating, and scaling in cpp programming using xCode.mp4





Great question 👍 — let’s go step-by-step on how to perform rotation, translation, and scaling in C++, especially if you’re doing graphics programming in Xcode (which usually means using either OpenGL or a graphics framework).

I’ll cover two approaches:


🧩 1. Using Plain C++ (Matrix Transformations)

If you’re learning the math behind 2D/3D transformations, you can do this with just matrices and no external libraries.

Here’s a simple 2D transformation example:

✅ Code Example (2D)

#include <iostream>
#include <cmath>
using namespace std;

struct Point {
    float x, y;
};

// Translate point by tx, ty
Point translate(Point p, float tx, float ty) {
    p.x += tx;
    p.y += ty;
    return p;
}

// Scale point by sx, sy
Point scale(Point p, float sx, float sy) {
    p.x *= sx;
    p.y *= sy;
    return p;
}

// Rotate point by angle (in degrees)
Point rotate(Point p, float angle) {
    float rad = angle * M_PI / 180.0;
    float x_new = p.x * cos(rad) - p.y * sin(rad);
    float y_new = p.x * sin(rad) + p.y * cos(rad);
    return {x_new, y_new};
}

int main() {
    Point p = {1, 1};

    cout << "Original: (" << p.x << ", " << p.y << ")\n";

    p = translate(p, 2, 3);
    cout << "Translated: (" << p.x << ", " << p.y << ")\n";

    p = scale(p, 2, 2);
    cout << "Scaled: (" << p.x << ", " << p.y << ")\n";

    p = rotate(p, 45);
    cout << "Rotated (45°): (" << p.x << ", " << p.y << ")\n";

    return 0;
}

🧮 This uses basic math for rotation, translation, and scaling.
You can run this directly in Xcode → New Command Line Tool → Language: C++.


🎨 2. Using OpenGL (in Xcode)

If you’re actually rendering graphics (2D or 3D), then transformations are done using OpenGL matrices.

✅ Setting up

In Xcode:

  1. Create a new macOS → Command Line Tool.

  2. Add OpenGL headers:

    #include <GLUT/glut.h> // macOS
    #include <cmath>
    

✅ Example Code

#include <GLUT/glut.h>
#include <cmath>

void display() {
    glClear(GL_COLOR_BUFFER_BIT);

    // Reset transformations
    glLoadIdentity();

    // 1️⃣ Translate
    glTranslatef(0.3f, 0.2f, 0.0f);

    // 2️⃣ Rotate
    glRotatef(45, 0.0f, 0.0f, 1.0f);

    // 3️⃣ Scale
    glScalef(0.5f, 0.5f, 1.0f);

    // Draw a simple triangle
    glBegin(GL_TRIANGLES);
        glColor3f(1, 0, 0);
        glVertex2f(-0.5f, -0.5f);
        glColor3f(0, 1, 0);
        glVertex2f(0.5f, -0.5f);
        glColor3f(0, 0, 1);
        glVertex2f(0.0f, 0.5f);
    glEnd();

    glFlush();
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutCreateWindow("Transformations in OpenGL");
    glutDisplayFunc(display);
    glutMainLoop();
    return 0;
}

🌀 Explanation:

  • glTranslatef(x, y, z) → moves object.

  • glRotatef(angle, x, y, z) → rotates object about an axis.

  • glScalef(x, y, z) → scales object.


🧠 Summary

Transformation Mathematical Formula OpenGL Function
Translation (x', y') = (x + tx, y + ty) glTranslatef(tx, ty, tz)
Scaling (x', y') = (x * sx, y * sy) glScalef(sx, sy, sz)
Rotation (x', y') = (x cosθ – y sinθ, x sinθ + y cosθ) glRotatef(angle, x, y, z)

Would you like me to show you how to visualize these transformations (e.g. an animation where a shape rotates, moves, and scales in real time)?
I can give you that version next.

Cleaning up the code - Making an app struct using XCode.

 

Download Cleaning up the code - Making an app struct.mp4



Escaping metacharacters in regular expression (regex). mp4

 

Download Escaping metacharacters in regular expression (regex). mp4



In programming — especially in regular expressions (regex) and string handlingescaping metacharacters means treating special characters (like . or *) as literal symbols instead of their special meaning.

Let’s break it down clearly 👇


🔹 What Are Metacharacters?

Metacharacters are characters with special meanings in regex or string patterns.
For example, in regex, these are metacharacters:

. ^ $ * + ? ( ) [ ] { } | \ /

Each has a purpose, such as:

  • . → matches any character

  • ^ → matches start of a string

  • $ → matches end of a string

  • * → matches zero or more repetitions

  • [] → defines a character set


🔹 Escaping Metacharacters

To use a metacharacter as a literal character (not as a special one), you must escape it.

✅ Example (Regex)

let regex = /a\.b/;
console.log(regex.test("a.b"));   // true
console.log(regex.test("acb"));   // false

Here, the \. escapes the . so it matches an actual dot . instead of “any character”.


🔹 Escaping in JavaScript Strings

In JavaScript, the backslash \ is also an escape character inside strings — so you might need double escaping!

Example:

let regex = new RegExp("a\\.b");  // Double escape inside string
console.log(regex.test("a.b"));   // true

🔹 Common Escapes

Character Escaped Version Meaning
. \. literal dot
* \* literal asterisk
? \? literal question mark
+ \+ literal plus sign
( \( literal open parenthesis
[ \[ literal open bracket
{ \{ literal open brace
` ` |
\ \\ literal backslash

🔹 Practical Tip

If you want to escape all regex metacharacters in a string dynamically, you can use:

function escapeRegex(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

console.log(escapeRegex("price is $5.99")); 
// Output: "price is \$5\.99"

Enjoy! Follow us for more... 

Join WhatsApp Group

Follow on Instagram

Follow on Facebook


JavaScript Output Methods (Brief Explanation)

 

JavaScript can show output (results or messages) in many ways. The most common methods are:


1. `innerHTML` – Displays output inside an HTML element.  


   ```html

   document.getElementById("demo").innerHTML = "Hello JavaScript!";

   ```

   It is used to change content on a webpage directly.


2. `document.write()` – Writes output directly to the HTML page.  


   ```html

   document.write("Welcome!");

   ```

   It is mostly used for testing because it can erase the page after loading.


3. *`alert()* – Displays a popup message box.  


   ```html

   alert("This is an alert box!");

   ```

   Useful for showing simple messages.


4. *console.log()`* – Shows output in the browser console (for debugging).  

   ```html

   console.log("This is a log message");

   ```


5. *`window.print()`* – Opens the print dialog for the webpage.  


   ```html

   window.print();

   ```


Each method serves a different purpose — for example, `console.log()` is great for developers, while `innerHTML` changes what users see on the screen.


Enjoy! Follow us for more... 

Join WhatsApp Group

Follow on Instagram





How to Filtering data during Web Development in html.

 

Download How to Filtering data during Web Development in html.mp4


Filtering data in HTML programming usually involves combining HTML, CSS, and JavaScript — because HTML alone is static (it can display data, but can’t filter or manipulate it).

Here’s a simple guide and example on how to filter data displayed on a webpage.


🧩 Example: Filtering a Table with an Input Box

✅ Step 1: Create the HTML structure

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Filter Table Data</title>
  <style>
    table {
      border-collapse: collapse;
      width: 50%;
      margin-top: 10px;
    }
    th, td {
      border: 1px solid #999;
      padding: 8px;
      text-align: left;
    }
    #myInput {
      width: 50%;
      padding: 8px;
      margin-top: 10px;
    }
  </style>
</head>
<body>

  <h2>Filter Table Example</h2>
  <input type="text" id="myInput" onkeyup="filterTable()" placeholder="Search for names...">

  <table id="myTable">
    <tr><th>Name</th><th>Country</th></tr>
    <tr><td>John Doe</td><td>USA</td></tr>
    <tr><td>Mary Smith</td><td>UK</td></tr>
    <tr><td>Linda Johnson</td><td>Canada</td></tr>
    <tr><td>Michael Brown</td><td>Australia</td></tr>
  </table>

  <script>
    function filterTable() {
      let input = document.getElementById("myInput");
      let filter = input.value.toUpperCase();
      let table = document.getElementById("myTable");
      let tr = table.getElementsByTagName("tr");

      for (let i = 1; i < tr.length; i++) { // skip header row
        let td = tr[i].getElementsByTagName("td")[0]; // filter by first column (Name)
        if (td) {
          let textValue = td.textContent || td.innerText;
          tr[i].style.display = textValue.toUpperCase().indexOf(filter) > -1 ? "" : "none";
        }
      }
    }
  </script>

</body>
</html>

🧠 How it works:

  • The user types in the input box.

  • The onkeyup event runs the filterTable() JavaScript function.

  • It compares the user’s input with each table row and hides the rows that don’t match.


⚙️ Variations

You can adapt this approach to filter:

  • Lists (<ul><li>...</li></ul>)

  • Cards or div elements (using document.querySelectorAll('.card'))

  • JSON data fetched from an API (with JavaScript)



Enjoy! Follow us for more... 

Join WhatsApp Group

Follow on Instagram






How to Match decimal numbers and currency in Regex.mp4

  Download  How to Match decimal numbers and currency in Regex.mp4 Here’s a simple and easy explanation of how to match decimal numbers and...