Snippets Collections
#include<bits/stdc++.h>
using namespace std;
const int N = 1e3+5;
vector<int> graph[N];
bool visited[N];
void dfs(int vertex)
{
  visited[vertex]=true;
  for(int child:graph[vertex])
    {
      
      if(visited[child])
        continue;
      dfs(child);
    }
}
int main()
{
    int v,e,j,k;
    cin>>v>>e;
    for(int i=0;i<v;++i)
    {
        cin>>j>>k;
        graph[k].push_back(j);
        graph[j].push_back(k);
        
    }
}
class AVLNode<T extends Comparable<T>> {
    T data;
    AVLNode<T> left, right;
    int height;

    public AVLNode(T data) {
        this.data = data;
        this.height = 1; // New node initially has height 1
    }
}

public class AVLTree<T extends Comparable<T>> {
    private AVLNode<T> root;

    public AVLTree() {
        this.root = null;
    }

    // Get height of node
    private int height(AVLNode<T> node) {
        return node == null ? 0 : node.height;
    }

    // Right rotation
    private AVLNode<T> rotateRight(AVLNode<T> y) {
        AVLNode<T> x = y.left;
        AVLNode<T> T2 = x.right;

        x.right = y;
        y.left = T2;

        y.height = Math.max(height(y.left), height(y.right)) + 1;
        x.height = Math.max(height(x.left), height(x.right)) + 1;

        return x;
    }

    // Left rotation
    private AVLNode<T> rotateLeft(AVLNode<T> x) {
        AVLNode<T> y = x.right;
        AVLNode<T> T2 = y.left;

        y.left = x;
        x.right = T2;

        x.height = Math.max(height(x.left), height(x.right)) + 1;
        y.height = Math.max(height(y.left), height(y.right)) + 1;

        return y;
    }

    // Balance factor of a node
    private int getBalance(AVLNode<T> node) {
        return node == null ? 0 : height(node.left) - height(node.right);
    }

    // Insert operation
    public void insert(T data) {
        root = insertRec(root, data);
    }

    private AVLNode<T> insertRec(AVLNode<T> node, T data) {
        if (node == null) {
            return new AVLNode<>(data);
        }

        if (data.compareTo(node.data) < 0) {
            node.left = insertRec(node.left, data);
        } else if (data.compareTo(node.data) > 0) {
            node.right = insertRec(node.right, data);
        } else {
            return node;
        }

        node.height = Math.max(height(node.left), height(node.right)) + 1;

        int balance = getBalance(node);

        if (balance > 1 && data.compareTo(node.left.data) < 0) {
            return rotateRight(node);
        }

        if (balance < -1 && data.compareTo(node.right.data) > 0) {
            return rotateLeft(node);
        }

        if (balance > 1 && data.compareTo(node.left.data) > 0) {
            node.left = rotateLeft(node.left);
            return rotateRight(node);
        }

        if (balance < -1 && data.compareTo(node.right.data) < 0) {
            node.right = rotateRight(node.right);
            return rotateLeft(node);
        }

        return node;
    }

    // Search operation
    public boolean search(T data) {
        return searchRec(root, data) != null;
    }

    private AVLNode<T> searchRec(AVLNode<T> node, T data) {
        if (node == null || node.data.equals(data)) {
            return node;
        }

        if (data.compareTo(node.data) < 0) {
            return searchRec(node.left, data);
        } else {
            return searchRec(node.right, data);
        }
    }

    // In-order traversal
    public void inOrder() {
        inOrderRec(root);
    }

    private void inOrderRec(AVLNode<T> node) {
        if (node != null) {
            inOrderRec(node.left);
            System.out.print(node.data + " ");
            inOrderRec(node.right);
        }
    }

    // Delete operation
    public void delete(T data) {
        root = deleteRec(root, data);
    }

    private AVLNode<T> deleteRec(AVLNode<T> root, T data) {
        if (root == null) {
            return root;
        }

        if (data.compareTo(root.data) < 0) {
            root.left = deleteRec(root.left, data);
        } else if (data.compareTo(root.data) > 0) {
            root.right = deleteRec(root.right, data);
        } else {
            if ((root.left == null) || (root.right == null)) {
                AVLNode<T> temp = root.left != null ? root.left : root.right;
                if (temp == null) {
                    return null;
                } else {
                    return temp;
                }
            } else {
                AVLNode<T> temp = minValueNode(root.right);
                root.data = temp.data;
                root.right = deleteRec(root.right, temp.data);
            }
        }

        root.height = Math.max(height(root.left), height(root.right)) + 1;

        int balance = getBalance(root);

        if (balance > 1 && getBalance(root.left) >= 0) {
            return rotateRight(root);
        }

        if (balance > 1 && getBalance(root.left) < 0) {
            root.left = rotateLeft(root.left);
            return rotateRight(root);
        }

        if (balance < -1 && getBalance(root.right) <= 0) {
            return rotateLeft(root);
        }

        if (balance < -1 && getBalance(root.right) > 0) {
            root.right = rotateRight(root.right);
            return rotateLeft(root);
        }

        return root;
    }

    private AVLNode<T> minValueNode(AVLNode<T> node) {
        AVLNode<T> current = node;
        while (current.left != null) {
            current = current.left;
        }
        return current;
    }

    public static void main(String[] args) {
        AVLTree<Integer> avlTree = new AVLTree<>();
        avlTree.insert(10);
        avlTree.insert(20);
        avlTree.insert(5);
        avlTree.insert(6);
        avlTree.insert(15);
        avlTree.insert(25);

        System.out.println("In-order traversal:");
        avlTree.inOrder();
        System.out.println();

        System.out.println("Search 15: " + avlTree.search(15));
        System.out.println("Search 100: " + avlTree.search(100));

        avlTree.delete(20);

        System.out.println("In-order traversal after deleting 20:");
        avlTree.inOrder();
        System.out.println();
    }
}
class TreeNode<T extends Comparable<T>> {
    T data;
    TreeNode<T> left, right;

    public TreeNode(T data) {
        this.data = data;
        this.left = this.right = null;
    }
}

public class BinarySearchTree<T extends Comparable<T>> {
    private TreeNode<T> root;

    public BinarySearchTree() {
        this.root = null;
    }

    // Insert operation
    public void insert(T data) {
        root = insertRec(root, data);
    }

    private TreeNode<T> insertRec(TreeNode<T> root, T data) {
        if (root == null) {
            root = new TreeNode<>(data);
            return root;
        }

        if (data.compareTo(root.data) < 0) {
            root.left = insertRec(root.left, data);
        } else if (data.compareTo(root.data) > 0) {
            root.right = insertRec(root.right, data);
        }

        return root;
    }

    // Search operation
    public boolean search(T data) {
        return searchRec(root, data) != null;
    }

    private TreeNode<T> searchRec(TreeNode<T> root, T data) {
        if (root == null || root.data.equals(data)) {
            return root;
        }

        if (data.compareTo(root.data) < 0) {
            return searchRec(root.left, data);
        } else {
            return searchRec(root.right, data);
        }
    }

    // In-order traversal (sorted order)
    public void inOrder() {
        inOrderRec(root);
    }

    private void inOrderRec(TreeNode<T> root) {
        if (root != null) {
            inOrderRec(root.left);
            System.out.print(root.data + " ");
            inOrderRec(root.right);
        }
    }

    // Delete operation
    public void delete(T data) {
        root = deleteRec(root, data);
    }

    private TreeNode<T> deleteRec(TreeNode<T> root, T data) {
        if (root == null) {
            return null;
        }

        if (data.compareTo(root.data) < 0) {
            root.left = deleteRec(root.left, data);
        } else if (data.compareTo(root.data) > 0) {
            root.right = deleteRec(root.right, data);
        } else {
            // Node to be deleted found

            // Case 1: Node has no children (leaf node)
            if (root.left == null && root.right == null) {
                return null;
            }

            // Case 2: Node has only one child
            if (root.left == null) {
                return root.right;
            }
            if (root.right == null) {
                return root.left;
            }

            // Case 3: Node has two children
            T minValue = findMinValue(root.right);
            root.data = minValue;
            root.right = deleteRec(root.right, minValue);
        }

        return root;
    }

    private T findMinValue(TreeNode<T> root) {
        T minValue = root.data;
        while (root.left != null) {
            minValue = root.left.data;
            root = root.left;
        }
        return minValue;
    }

    public static void main(String[] args) {
        BinarySearchTree<Integer> bst = new BinarySearchTree<>();

        bst.insert(50);
        bst.insert(30);
        bst.insert(70);
        bst.insert(20);
        bst.insert(40);
        bst.insert(60);
        bst.insert(80);

        System.out.println("In-order traversal:");
        bst.inOrder();
        System.out.println();

        System.out.println("Search 60: " + bst.search(60));
        System.out.println("Search 100: " + bst.search(100));

        bst.delete(70);

        System.out.println("In-order traversal after deleting 70:");
        bst.inOrder();
        System.out.println();
    }
}
public class LinearProbingHashTable {
    private String[] keys;
    private String[] values;
    private int size;
    private int capacity;

    public LinearProbingHashTable(int capacity) {
        this.capacity = capacity;
        this.keys = new String[capacity];
        this.values = new String[capacity];
        this.size = 0;
    }

    private int hash(String key) {
        return key.length() % capacity;
    }
    
    public void put(String key, String value) {
        if (key == null || value == null) {
            throw new IllegalArgumentException("Key or value cannot be null.");
        }
        
        int index = hash(key);
        while (keys[index] != null) {
            if (keys[index].equals(key)) {
				values[index] = value;
                return;
            }
            index = (index + 1) % capacity;
        }
        keys[index] = key;
        values[index] = value;
        size++;
    }

    public String get(String key) {
        int index = hash(key);
        while (keys[index] != null) {
            if (keys[index].equals(key)) {
                return values[index];
            }
             index = (index + 1) % capacity;
        }
        return null; 
    }

    public void display() {
        for (int i = 0; i < capacity; i++) {
            if (keys[i] != null) {
                System.out.println("Key: " + keys[i] + ", Value: " + values[i]);
            }
        }
    }

    public static void main(String[] args) {
        LinearProbingHashTable hashTable = new LinearProbingHashTable(10);

        hashTable.put("John", "Doe");
        hashTable.put("Alice", "Smith");
        hashTable.put("Bob", "Johnson");
        hashTable.put("Charlie", "Brown");
 
        hashTable.display();

        System.out.println("Value associated with 'John': " + hashTable.get("John"));
        System.out.println("Value associated with 'Alice': " + hashTable.get("Alice"));
        System.out.println("Value associated with 'Bob': " + hashTable.get("Bob"));
        System.out.println("Value associated with 'Charlie': " + hashTable.get("Charlie"));
        System.out.println("Value associated with 'Dave': " + hashTable.get("Dave")); // Not found
    }
}
import java.util.LinkedList;

class KeyValuePair<K, V> {
    private K key;
    private V value;

    public KeyValuePair(K key, V value) {
        this.key = key;
        this.value = value;
    }

    public K getKey() {
        return key;
    }

    public V getValue() {
        return value;
    }
}

class SeparateChaining<K, V> {
    private LinkedList<KeyValuePair<K, V>>[] table;
    private int capacity;
	
    @SuppressWarnings("unchecked")
    public SeparateChaining(int capacity) {
        this.capacity = capacity;
        this.table = new LinkedList[capacity];
        for (int i = 0; i < capacity; i++) {
            table[i] = new LinkedList<>();
        }
    }

    private int hash(K key) {
        return Math.abs(key.hashCode() % capacity);
    }

    public void put(K key, V value) {
        int index = hash(key);
        LinkedList<KeyValuePair<K, V>> list = table[index];
        for (KeyValuePair<K, V> pair : list) {
            if (pair.getKey().equals(key)) {
                pair = new KeyValuePair<>(key, value);
                return;
            }
        }
        list.add(new KeyValuePair<>(key, value));
    }

    public V get(K key) {
        int index = hash(key);
        LinkedList<KeyValuePair<K, V>> list = table[index];
        for (KeyValuePair<K, V> pair : list) {
            if (pair.getKey().equals(key)) {
                return pair.getValue();
            }
        }
        return null;
    }

    public void remove(K key) {
        int index = hash(key);
        LinkedList<KeyValuePair<K, V>> list = table[index];
        for (KeyValuePair<K, V> pair : list) {
            if (pair.getKey().equals(key)) {
                list.remove(pair);
                return;
            }
        }
    }

    public void display() {
        for (int i = 0; i < capacity; i++) {
            System.out.print("Bucket " + i + ": ");
            for (KeyValuePair<K, V> pair : table[i]) {
                System.out.print("[" + pair.getKey() + ": " + pair.getValue() + "] ");
            }
            System.out.println();
        }
    }
}

public class SeparateChainingExample {
    public static void main(String[] args) {
        SeparateChaining<String, Integer> map = new SeparateChaining<>(5);

        map.put("John", 25);
        map.put("Alice", 30);
        map.put("Bob", 35);
        map.put("Doe", 40);  // Adding more elements to see separate chaining in action
        map.put("Eve", 45);

        System.out.println("Initial Map:");
        map.display();

        System.out.println("\nAlice's age: " + map.get("Alice"));
        System.out.println("Bob's age: " + map.get("Bob"));

        map.remove("Alice");

        System.out.println("\nMap after removing Alice:");
        map.display();

        System.out.println("Alice's age after removal: " + map.get("Alice"));
    }
}
class Node<T extends Comparable<T>> {
    T data;
    Node<T> next;

    public Node(T data) {
        this.data = data;
        this.next = null;
    }
}

public class SortedChain<T extends Comparable<T>> {
    private Node<T> head;

    public void insert(T data) {
        Node<T> newNode = new Node<>(data);
        
        if (head == null || head.data.compareTo(data) >= 0) {
            newNode.next = head;
            head = newNode;
        } else {
            Node<T> current = head;
            while (current.next != null && current.next.data.compareTo(data) < 0) {
                current = current.next;
            }
            newNode.next = current.next;
            current.next = newNode;
        }
    }

    public void display() {
        Node<T> current = head;
        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        SortedChain<Integer> sortedChain = new SortedChain<>();
        sortedChain.insert(5);
        sortedChain.insert(3);
        sortedChain.insert(7);
        sortedChain.insert(1);
        sortedChain.insert(9);

        System.out.println("Sorted Chain:");
        sortedChain.display();
    }
}
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

class Product {
    private int id;
    private String name;
    private double price;
    private String type;
    private double rating;

    public Product(int id, String name, double price, String type, double rating) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.type = type;
        this.rating = rating;
    }

    public double getRating() {
        return rating;
    }

    public double getPrice() {
        return price;
    }

    public String getType() {
        return type;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", type='" + type + '\'' +
                ", rating=" + rating +
                '}';
    }
}

public class ProductStreamExample {
    public static void main(String[] args) {
        List<Product> products = Arrays.asList(
                new Product(1, "Laptop", 1500.0, "Electronics", 4.5),
                new Product(2, "Smartphone", 800.0, "Electronics", 4.2),
                new Product(3, "Watch", 300.0, "Fashion", 3.8),
                new Product(4, "Headphones", 100.0, "Electronics", 4.8),
                new Product(5, "Shoes", 50.0, "Fashion", 3.5),
                new Product(6, "Camera", 2000.0, "Electronics", 4.7)
        );

        // i) Find all the products having rating between 4 and 5
        List<Product> productsRatingBetween4And5 = products.stream()
                .filter(p -> p.getRating() >= 4 && p.getRating() <= 5)
                .collect(Collectors.toList());
        System.out.println("Products with rating between 4 and 5: " + productsRatingBetween4And5);
		System.out.println();
        
        // ii) Find first n products having price > 10000
        int n = 2;
        List<Product> firstNProductsPriceGreaterThan1000 = products.stream()
                .filter(p -> p.getPrice() > 1000)
                .limit(n)
                .collect(Collectors.toList());
        System.out.println("First " + n + " products with price > 1000: " + firstNProductsPriceGreaterThan1000);
		System.out.println();
        
        // iii) Find the number of products under each type (map containing type and count)
        Map<String, Long> productCountByType = products.stream()
		.collect(Collectors.groupingBy(Product::getType, Collectors.counting()));
        System.out.println("Number of products under each type: " + productCountByType);
		System.out.println();
        
        // iv) Find average rating of products with type = "Electronics"
        double averageRatingElectronics = products.stream()
                .filter(p -> p.getType().equals("Electronics"))
                .mapToDouble(Product::getRating)
                .average()
                .orElse(0.0);
        System.out.println("Average rating of products with type 'Electronics': " + averageRatingElectronics);
    }
}
import java.util.Map;
import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        // Creating a TreeMap to store names and ages
        TreeMap<String, Integer> ageMap = new TreeMap<>();

        // Adding key-value pairs to the TreeMap
        ageMap.put("John", 30);
        ageMap.put("Alice", 25);
        ageMap.put("Bob", 35);
        ageMap.put("Eve", 28);

        // Accessing values using get() method
        System.out.println("Age of John: " + ageMap.get("John"));
        System.out.println("Age of Alice: " + ageMap.get("Alice"));

        // Updating a value using put() method
        ageMap.put("John", 32);
        System.out.println("Updated age of John: " + ageMap.get("John"));

        // Checking if a key exists
        String name = "Bob";
        if (ageMap.containsKey(name)) {
            System.out.println(name + " exists in the map.");
        } else {
            System.out.println(name + " does not exist in the map.");
        }

        // Removing an entry using remove() method
        ageMap.remove("Eve");
        System.out.println("Map after removing Eve: " + ageMap);

        // Iterating over map entries using for-each loop
        System.out.println("Iterating over map entries:");
        for (Map.Entry<String, Integer> entry : ageMap.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }

        // Checking size and emptiness
        System.out.println("Size of map: " + ageMap.size());
        System.out.println("Is map empty? " + ageMap.isEmpty());

        // Checking if map contains a key and value
        System.out.println("Contains key 'Bob': " + ageMap.containsKey("Bob"));
        System.out.println("Contains value 35: " + ageMap.containsValue(35));

        // Clear the map
        ageMap.clear();
        System.out.println("Map after clearing: " + ageMap);
    }
}
import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        // Creating a LinkedHashMap to store names and ages
        LinkedHashMap<String, Integer> ageMap = new LinkedHashMap<>();

        // Adding key-value pairs to the LinkedHashMap
        ageMap.put("John", 30);
        ageMap.put("Alice", 25);
        ageMap.put("Bob", 35);
        ageMap.put("Eve", 28);

        // Accessing values using get() method
        System.out.println("Age of John: " + ageMap.get("John"));
        System.out.println("Age of Alice: " + ageMap.get("Alice"));

        // Updating a value using put() method
        ageMap.put("John", 32);
        System.out.println("Updated age of John: " + ageMap.get("John"));

        // Checking if a key exists
        String name = "Bob";
        if (ageMap.containsKey(name)) {
            System.out.println(name + " exists in the map.");
        } else {
            System.out.println(name + " does not exist in the map.");
        }

        // Removing an entry using remove() method
        ageMap.remove("Eve");
        System.out.println("Map after removing Eve: " + ageMap);

        // Iterating over map entries
        System.out.println("Iterating over map entries:");
        for (Map.Entry<String, Integer> entry : ageMap.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }

        // Checking size and emptiness
        System.out.println("Size of map: " + ageMap.size());
        System.out.println("Is map empty? " + ageMap.isEmpty());

        // Checking if map contains a key and value
        System.out.println("Contains key 'Bob': " + ageMap.containsKey("Bob"));
        System.out.println("Contains value 35: " + ageMap.containsValue(35));

        // Clear the map
        ageMap.clear();
        System.out.println("Map after clearing: " + ageMap);
    }
}
select 
json_event->'project',
json_event->'pipeline_params'->'artifacts_iac' as iac
from cicd_event
where event_type = 'ci_start'
and jsonb_array_length(jsonb_path_query_array(
	json_event->'pipeline_params'->'artifacts_iac',
	'$[*] ? (@.classifier == "terraform")'
)) >=2
import java.util.HashMap;
import java.util.Map;

public class HashMapMethodsExample {
    public static void main(String[] args) {
        // Creating a HashMap to store names and ages
        HashMap<String, Integer> ageMap = new HashMap<>();

        // Adding key-value pairs to the HashMap
        ageMap.put("John", 30);
        ageMap.put("Alice", 25);
        ageMap.put("Bob", 35);

        // Accessing values using get() method
        System.out.println("Age of John: " + ageMap.get("John"));
        System.out.println("Age of Alice: " + ageMap.get("Alice"));

        // Updating a value using put() method
        ageMap.put("John", 32);
        System.out.println("Updated age of John: " + ageMap.get("John"));

        // Checking if a key exists
        String name = "Bob";
        if (ageMap.containsKey(name)) {
            System.out.println(name + " exists in the map.");
        } else {
            System.out.println(name + " does not exist in the map.");
        }

        // Removing an entry using remove() method
        ageMap.remove("Alice");
        System.out.println("Map after removing Alice: " + ageMap);

        // Iterating over map entries
        System.out.println("Iterating over map entries:");
        for (Map.Entry<String, Integer> entry : ageMap.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }

        // Checking size and emptiness
        System.out.println("Size of map: " + ageMap.size());
        System.out.println("Is map empty? " + ageMap.isEmpty());

        // Checking if map contains a key and value
        System.out.println("Contains key 'Bob': " + ageMap.containsKey("Bob"));
        System.out.println("Contains value 35: " + ageMap.containsValue(35));

        // Clear the map
        ageMap.clear();
        System.out.println("Map after clearing: " + ageMap);
    }
}
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class Person {
    private String name;
    private int age;
    private double income;

    public Person(String name, int age, double income) {
        this.name = name;
        this.age = age;
        this.income = income;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public double getIncome() {
        return income;
    }
}

public class PersonExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        List<Person> setA = new ArrayList<>();

        // Read the number of persons
        System.out.print("Enter the number of persons: ");
        int n = scanner.nextInt();
        scanner.nextLine(); // consume newline character

        // Read details for each person
        for (int i = 0; i < n; i++) {
            System.out.println("Enter details for person " + (i + 1) + ":");
            System.out.print("Name: ");
            String name = scanner.nextLine();
            System.out.print("Age: ");
            int age = scanner.nextInt();
            System.out.print("Income: ");
            double income = scanner.nextDouble();
            scanner.nextLine(); // consume newline character

            // Create a new Person object and add it to the list
            Person person = new Person(name, age, income);
            setA.add(person);
        }

        // Initialize sets B, C, and B and C
        List<Person> setB = new ArrayList<>();
        List<Person> setC = new ArrayList<>();
        List<Person> setBC = new ArrayList<>();

        // Compute the sets
        for (Person person : setA) {
            if (person.getAge() > 60) {
                setB.add(person);
            }
            if (person.getIncome() < 10000) {
                setC.add(person);
            }
            if (person.getAge() > 60 && person.getIncome() < 10000) {
                setBC.add(person);
            }
        }

        // Print the results
        System.out.println("\nSet A:");
        for (Person person : setA) {
            System.out.println("Name: " + person.getName() + ", Age: " + person.getAge() + ", Income: " + person.getIncome());
        }

        System.out.println("\nSet B (age > 60):");
        for (Person person : setB) {
            System.out.println("Name: " + person.getName() + ", Age: " + person.getAge() + ", Income: " + person.getIncome());
        }

        System.out.println("\nSet C (income < 10000):");
        for (Person person : setC) {
            System.out.println("Name: " + person.getName() + ", Age: " + person.getAge() + ", Income: " + person.getIncome());
        }

        System.out.println("\nSet B and C (age > 60 and income < 10000):");
        for (Person person : setBC) {
            System.out.println("Name: " + person.getName() + ", Age: " + person.getAge() + ", Income: " + person.getIncome());
        }
    }
}
import java.util.TreeSet;
import java.util.Iterator;

public class TreeSetExample {
    public static void main(String[] args) {
        // Create a TreeSet
        TreeSet<String> fruits = new TreeSet<>();

        // Add elements to the TreeSet
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        fruits.add("Date");
        fruits.add("Elderberry");
        fruits.add("Fig");
        fruits.add("Grape");

        // Display the TreeSet
        System.out.println("Fruits in the TreeSet: " + fruits);

        // Attempt to add a duplicate element
        boolean isAdded = fruits.add("Apple");
        System.out.println("Attempt to add 'Apple' again: " + isAdded); // Should print false

        // Check the size of the TreeSet
        System.out.println("Size of the TreeSet: " + fruits.size());

        // Check if an element exists
        boolean containsCherry = fruits.contains("Cherry");
        System.out.println("Does the set contain 'Cherry'? " + containsCherry);

        // Remove an element
        fruits.remove("Banana");
        System.out.println("Fruits after removing 'Banana': " + fruits);

        // Iterate through the TreeSet using an Iterator
        System.out.println("Iterating through the TreeSet using an Iterator:");
        Iterator<String> iterator = fruits.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        // Iterate through the TreeSet using a for-each loop
        System.out.println("Iterating through the TreeSet using a for-each loop:");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }

        // Convert the TreeSet to an array
        Object[] fruitsArray = fruits.toArray();
        System.out.println("Fruits as an array:");
        for (Object fruit : fruitsArray) {
            System.out.println(fruit);
        }

        // Check if the TreeSet is empty
        System.out.println("Is the TreeSet empty? " + fruits.isEmpty());

        // Clone the TreeSet
        TreeSet<String> clonedFruits = (TreeSet<String>) fruits.clone();
        System.out.println("Cloned TreeSet: " + clonedFruits);

        // Clear the TreeSet
        fruits.clear();
        System.out.println("Is the TreeSet empty after clearing? " + fruits.isEmpty());

        // Add all elements from another collection
        TreeSet<String> moreFruits = new TreeSet<>();
        moreFruits.add("Kiwi");
        moreFruits.add("Lemon");
        moreFruits.add("Mango");
        fruits.addAll(moreFruits);
        System.out.println("Fruits after adding more fruits: " + fruits);

        // Retain only certain elements
        TreeSet<String> retainFruits = new TreeSet<>();
        retainFruits.add("Kiwi");
        retainFruits.add("Mango");
        fruits.retainAll(retainFruits);
        System.out.println("Fruits after retaining certain fruits: " + fruits);

        // Remove all elements from another collection
        fruits.removeAll(retainFruits);
        System.out.println("Fruits after removing retained fruits: " + fruits);

        // Accessing the first and last elements
        System.out.println("First fruit in the TreeSet: " + moreFruits.first());
        System.out.println("Last fruit in the TreeSet: " + moreFruits.last());

        // Subset of the TreeSet
        TreeSet<String> subSet = (TreeSet<String>) moreFruits.subSet("Kiwi", "Mango");
        System.out.println("Subset from 'Kiwi' to 'Mango': " + subSet);
    }
}
import java.util.LinkedHashSet;
import java.util.Iterator;

public class LinkedHashSetExample {
    public static void main(String[] args) {
        // Create a LinkedHashSet
        LinkedHashSet<String> fruits = new LinkedHashSet<>();

        // Add elements to the LinkedHashSet
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        fruits.add("Date");
        fruits.add("Elderberry");
        fruits.add("Fig");
        fruits.add("Grape");

        // Display the LinkedHashSet
        System.out.println("Fruits in the LinkedHashSet: " + fruits);

        // Attempt to add a duplicate element
        boolean isAdded = fruits.add("Apple");
        System.out.println("Attempt to add 'Apple' again: " + isAdded); // Should print false

        // Check the size of the LinkedHashSet
        System.out.println("Size of the LinkedHashSet: " + fruits.size());

        // Check if an element exists
        boolean containsCherry = fruits.contains("Cherry");
        System.out.println("Does the set contain 'Cherry'? " + containsCherry);

        // Remove an element
        fruits.remove("Banana");
        System.out.println("Fruits after removing 'Banana': " + fruits);

        // Iterate through the LinkedHashSet using an Iterator
        System.out.println("Iterating through the LinkedHashSet using an Iterator:");
        Iterator<String> iterator = fruits.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        // Iterate through the LinkedHashSet using a for-each loop
        System.out.println("Iterating through the LinkedHashSet using a for-each loop:");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }

        // Convert the LinkedHashSet to an array
        Object[] fruitsArray = fruits.toArray();
        System.out.println("Fruits as an array:");
        for (Object fruit : fruitsArray) {
            System.out.println(fruit);
        }

        // Check if the LinkedHashSet is empty
        System.out.println("Is the LinkedHashSet empty? " + fruits.isEmpty());

        // Clone the LinkedHashSet
        LinkedHashSet<String> clonedFruits = (LinkedHashSet<String>) fruits.clone();
        System.out.println("Cloned LinkedHashSet: " + clonedFruits);

        // Clear the LinkedHashSet
        fruits.clear();
        System.out.println("Is the LinkedHashSet empty after clearing? " + fruits.isEmpty());

        // Add all elements from another collection
        LinkedHashSet<String> moreFruits = new LinkedHashSet<>();
        moreFruits.add("Kiwi");
        moreFruits.add("Lemon");
        moreFruits.add("Mango");
        fruits.addAll(moreFruits);
        System.out.println("Fruits after adding more fruits: " + fruits);

        // Retain only certain elements
        LinkedHashSet<String> retainFruits = new LinkedHashSet<>();
        retainFruits.add("Kiwi");
        retainFruits.add("Mango");
        fruits.retainAll(retainFruits);
        System.out.println("Fruits after retaining certain fruits: " + fruits);

        // Remove all elements from another collection
        fruits.removeAll(retainFruits);
        System.out.println("Fruits after removing retained fruits: " + fruits);
    }
}
public class BoundedArithematic<T extends Number> {
    public double add(T a, T b) {
        return a.doubleValue() + b.doubleValue();
    }
    public double subtract(T a, T b) {
        return a.doubleValue() - b.doubleValue();
    }
    public double multiply(T a, T b) {
        return a.doubleValue() * b.doubleValue();
    }	
   public double divide(T a, T b) {
        if (b.doubleValue() == 0) {
            throw new ArithmeticException("Division by zero is not allowed.");
        }
        return a.doubleValue() / b.doubleValue();
    }
    public static void main(String[] args) {
        BoundedArithematic<Number> calculator = new BoundedArithematic<>();
        Integer a = 10;
        Integer b = 5;
        System.out.println("Addition: " + calculator.add(a, b));
        System.out.println("Subtraction: " + calculator.subtract(a, b));
        System.out.println("Multiplication: " + calculator.multiply(a, b));
        System.out.println("Division: " + calculator.divide(a, b));
    }
}
==
//Wildcard Arguments
public class MagicBox<T> {
    private T item;

    public void addItem(T item) {
        this.item = item;
        System.out.println("Added item to the magic box: " + item);
    }

    public T getItem() {
                return item;
    }

    public void processBox(MagicBox<? super Integer> box) {
        System.out.println("Items in the box are processed["+box.getItem()+"]"); 
    }

    public static void main(String[] args) {
        
        MagicBox<Integer> integerBox = new MagicBox<>();
        integerBox.addItem(43);
        		
		MagicBox<String> stringBox = new MagicBox<>();
        stringBox.addItem("Sofiya");
        	
		
        MagicBox<Boolean> booleanBox = new MagicBox<>();
        booleanBox.addItem(false);
        
		MagicBox<Object> dobubleBox = new MagicBox<>();
        dobubleBox.addItem(43.43);
		
		integerBox.processBox(integerBox);
		dobubleBox.processBox(dobubleBox);
		
		
		
        
    }
}
import java.util.HashSet;
import java.util.Iterator;

public class HashSetExample {
    public static void main(String[] args) {
        // Create a HashSet
        HashSet<String> fruits = new HashSet<>();

        // Add elements to the HashSet
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        fruits.add("Date");
        fruits.add("Elderberry");
        fruits.add("Fig");
        fruits.add("Grape");

        // Display the HashSet
        System.out.println("Fruits in the HashSet: " + fruits);

        // Attempt to add a duplicate element
        boolean isAdded = fruits.add("Apple");
        System.out.println("Attempt to add 'Apple' again: " + isAdded); // Should print false

        // Check the size of the HashSet
        System.out.println("Size of the HashSet: " + fruits.size());

        // Check if an element exists
        boolean containsCherry = fruits.contains("Cherry");
        System.out.println("Does the set contain 'Cherry'? " + containsCherry);

        // Remove an element
        fruits.remove("Banana");
        System.out.println("Fruits after removing 'Banana': " + fruits);

        // Iterate through the HashSet using an Iterator
        System.out.println("Iterating through the HashSet using an Iterator:");
        Iterator<String> iterator = fruits.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        // Iterate through the HashSet using a for-each loop
        System.out.println("Iterating through the HashSet using a for-each loop:");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }

        // Convert the HashSet to an array
        Object[] fruitsArray = fruits.toArray();
        System.out.println("Fruits as an array:");
        for (Object fruit : fruitsArray) {
            System.out.println(fruit);
        }

        // Check if the HashSet is empty
        System.out.println("Is the HashSet empty? " + fruits.isEmpty());

        // Clone the HashSet
        HashSet<String> clonedFruits = (HashSet<String>) fruits.clone();
        System.out.println("Cloned HashSet: " + clonedFruits);

        // Clear the HashSet
        fruits.clear();
        System.out.println("Is the HashSet empty after clearing? " + fruits.isEmpty());

        // Add all elements from another collection
        HashSet<String> moreFruits = new HashSet<>();
        moreFruits.add("Kiwi");
        moreFruits.add("Lemon");
        moreFruits.add("Mango");
        fruits.addAll(moreFruits);
        System.out.println("Fruits after adding more fruits: " + fruits);

        // Retain only certain elements
        HashSet<String> retainFruits = new HashSet<>();
        retainFruits.add("Kiwi");
        retainFruits.add("Mango");
        fruits.retainAll(retainFruits);
        System.out.println("Fruits after retaining certain fruits: " + fruits);

        // Remove all elements from another collection
        fruits.removeAll(retainFruits);
        System.out.println("Fruits after removing retained fruits: " + fruits);
    }
}
import java.util.LinkedList;

public class GenericQueue<T> {
    private LinkedList<T> queueList;

    public GenericQueue() {
        this.queueList = new LinkedList<>();
    }

    public void enqueue(T item) {
        queueList.addLast(item);
    }

    public T dequeue() {
        if (!queueList.isEmpty()) {
            return queueList.removeFirst();
        } else {
            System.out.println("Queue Underflow");
            return null;
        }
    }

    public boolean isEmpty() {
        return queueList.isEmpty();
    }

    public T peek() {
        if (!queueList.isEmpty()) {
            return queueList.getFirst();
        } else {
            return null;
        }
    }

    public static void main(String[] args) {
        GenericQueue<Integer> intQueue = new GenericQueue<>();
        intQueue.enqueue(1);
        intQueue.enqueue(2);
        intQueue.enqueue(3);
        intQueue.enqueue(4);
        intQueue.enqueue(5);

        System.out.println("Front element: " + intQueue.peek()); // 1

        while (!intQueue.isEmpty()) {
            System.out.println("Dequeued element: " + intQueue.dequeue());
        }

        System.out.println("Queue is empty: " + intQueue.isEmpty()); // true

        GenericQueue<String> stringQueue = new GenericQueue<>();
        stringQueue.enqueue("one");
        stringQueue.enqueue("two");
        stringQueue.enqueue("three");

        System.out.println("Front element: " + stringQueue.peek()); // one

        while (!stringQueue.isEmpty()) {
            System.out.println("Dequeued element: " + stringQueue.dequeue());
        }

        System.out.println("Queue is empty: " + stringQueue.isEmpty()); // true
    }
}
#include<bits/stdc++.h>
using namespace std;
const int N = 1e3+5;
vector<int> graph[N];
int main()
{
    int v,e,j,k;
    cin>>v>>e;
    for(int i=0;i<v;++i)
    {
        cin>>j>>k;
        graph[k].push_back(j);
        graph[j].push_back(k);
        
    }
}
#include<bits/stdc++.h>
using namespace std;
const int N = 1e3+5;
int graph[N][N];
int main()
{
    int v,e,j,k;
    cin>>v>>e;
    for(int i=0;i<e;++i)
    {
        cin>>j>>k;
        graph[i][j]=1;
        graph[j][i]=1;
        
    }
}
import java.util.Scanner;  

interface StringFunction {  
    String reverse(String input);  
}  
public class StringLambdaExample1 {  
    public static void main(String[] args) {  
    
        Scanner scanner = new Scanner(System.in);  
 
        StringFunction reverseFunction = (str) -> {  
            String reversedString = "";  
  
            for (int index = str.length() - 1; index >= 0; index--) {  
              
                reversedString += str.charAt(index);  
            }
            return reversedString;  
        };  
        String fixedString = " javaTpoint";  
        System.out.println("Reversed word using lambda function: " + reverseFunction.reverse(fixedString));  
        System.out.println("Enter a string to be reversed:");  
        String userInput = scanner.nextLine();  
        System.out.println("After reversing: " + reverseFunction.reverse(userInput));  
        scanner.close();  
    }  
}  
import java.util.ArrayList;

public class GenericQueue<T> {
    private ArrayList<T> queueList;

    public GenericQueue() {
        this.queueList = new ArrayList<>();
    }

    public void enqueue(T item) {
        queueList.add(item);
    }

    public T dequeue() {
        if (!queueList.isEmpty()) {
            return queueList.remove(0);
        } else {
            System.out.println("Queue Underflow");
            return null;
        }
    }

    public boolean isEmpty() {
        return queueList.isEmpty();
    }

    public T peek() {
        if (!queueList.isEmpty()) {
            return queueList.get(0);
        } else {
            return null;
        }
    }

    public static void main(String[] args) {
        GenericQueue<Integer> intQueue = new GenericQueue<>();
        intQueue.enqueue(1);
        intQueue.enqueue(2);
        intQueue.enqueue(3);
        intQueue.enqueue(4);
        intQueue.enqueue(5);

        System.out.println("Front element: " + intQueue.peek()); // 1

        while (!intQueue.isEmpty()) {
            System.out.println("Dequeued element: " + intQueue.dequeue());
        }

        System.out.println("Queue is empty: " + intQueue.isEmpty()); // true

        GenericQueue<String> stringQueue = new GenericQueue<>();
        stringQueue.enqueue("one");
        stringQueue.enqueue("two");
        stringQueue.enqueue("three");

        System.out.println("Front element: " + stringQueue.peek()); // one

        while (!stringQueue.isEmpty()) {
            System.out.println("Dequeued element: " + stringQueue.dequeue());
        }

        System.out.println("Queue is empty: " + stringQueue.isEmpty()); // true
    }
}
import java.util.LinkedList;

public class GenericStack<T> {
    private LinkedList<T> stackList;

    public GenericStack() {
        this.stackList = new LinkedList<>();
    }

    public void push(T item) {
        stackList.addFirst(item);
    }

    public T pop() {
        if (!stackList.isEmpty()) {
            return stackList.removeFirst();
        } else {
            System.out.println("Stack Underflow");
            return null;
        }
    }

    public boolean isEmpty() {
        return stackList.isEmpty();
    }

    public T peek() {
        if (!stackList.isEmpty()) {
            return stackList.getFirst();
        } else {
            return null;
        }
    }

    public static void main(String[] args) {
        GenericStack<Integer> intStack = new GenericStack<>();
        intStack.push(1);
        intStack.push(2);
        intStack.push(3);
        intStack.push(4);
        intStack.push(5);

        System.out.println("Top element: " + intStack.peek()); // 5

        while (!intStack.isEmpty()) {
            System.out.println("Popped element: " + intStack.pop());
        }

        System.out.println("Stack is empty: " + intStack.isEmpty()); // true

        GenericStack<String> stringStack = new GenericStack<>();
        stringStack.push("one");
        stringStack.push("two");
        stringStack.push("three");

        System.out.println("Top element: " + stringStack.peek()); // three

        while (!stringStack.isEmpty()) {
            System.out.println("Popped element: " + stringStack.pop());
        }

        System.out.println("Stack is empty: " + stringStack.isEmpty()); // true
    }
}
import java.util.ArrayList;

public class GenericStack<T> {
    private ArrayList<T> stackList;
    private int maxSize;

    public GenericStack(int size) {
        this.stackList = new ArrayList<>(size);
        this.maxSize = size;
    }

    public void push(T item) {
        if (stackList.size() < maxSize) {
            stackList.add(item);
        } else {
            System.out.println("Stack Overflow");
        }
    }

    public T pop() {
        if (!stackList.isEmpty()) {
            return stackList.remove(stackList.size() - 1);
        } else {
            System.out.println("Stack Underflow");
            return null;
        }
    }

    public boolean isEmpty() {
        return stackList.isEmpty();
    }

    public boolean isFull() {
        return stackList.size() == maxSize;
    }

    public T peek() {
        if (!stackList.isEmpty()) {
            return stackList.get(stackList.size() - 1);
        } else {
            return null;
        }
    }

    public static void main(String[] args) {
        GenericStack<Integer> intStack = new GenericStack<>(5);
        intStack.push(1);
        intStack.push(2);
        intStack.push(3);
        intStack.push(4);
        intStack.push(5);

        System.out.println("Stack is full: " + intStack.isFull()); // true
        System.out.println("Top element: " + intStack.peek()); // 5

        while (!intStack.isEmpty()) {
            System.out.println("Popped element: " + intStack.pop());
        }

        System.out.println("Stack is empty: " + intStack.isEmpty()); // true

        GenericStack<String> stringStack = new GenericStack<>(3);
        stringStack.push("one");
        stringStack.push("two");
        stringStack.push("three");

        System.out.println("Stack is full: " + stringStack.isFull()); // true
        System.out.println("Top element: " + stringStack.peek()); // three

        while (!stringStack.isEmpty()) {
            System.out.println("Popped element: " + stringStack.pop());
        }

        System.out.println("Stack is empty: " + stringStack.isEmpty()); // true
    }
}
class Node<T> {
    T data;
    Node<T> next;

    public Node(T data) {
        this.data = data;
        this.next = null;
    }
}

class GenericQueueArray<T> {
    private T[] queueArray;
    private int front, rear, size, capacity;

    @SuppressWarnings("unchecked")
    public GenericQueueArray(int capacity) {
        this.capacity = capacity;
        this.queueArray = (T[]) new Object[capacity];
        this.front = 0;
        this.rear = 0; // Initialize rear to be the same as front
        this.size = 0;
    }

    public void enqueue(T item) {
        if (isFull()) {
            System.out.println("Queue is full");
            return;
        }
        queueArray[rear] = item;
        rear = (rear + 1) % capacity;
        size++;
    }

    public T dequeue() {
        if (isEmpty()) {
            System.out.println("Queue is empty");
            return null;
        }
        T item = queueArray[front];
        front = (front + 1) % capacity;
        size--;
        return item;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public boolean isFull() {
        return size == capacity;
    }
}

class GenericQueueLinkedList<T> {
    private Node<T> front, rear;

    public GenericQueueLinkedList() {
        this.front = this.rear = null;
    }

    public void enqueue(T item) {
        Node<T> newNode = new Node<>(item);
        if (isEmpty()) {
            front = rear = newNode;
        } else {
            rear.next = newNode;
            rear = newNode;
        }
    }

    public T dequeue() {
        if (isEmpty()) {
            System.out.println("Queue is empty");
            return null;
        }
        T item = front.data;
        front = front.next;
        if (front == null) {
            rear = null;
        }
        return item;
    }

    public boolean isEmpty() {
        return front == null;
    }
}

public class GenericQueueExample {
    public static void main(String[] args) {
        // Static input for demonstration
        GenericQueueArray<Integer> intQueueArray = new GenericQueueArray<>(5);
        intQueueArray.enqueue(1);
        intQueueArray.enqueue(2);
        intQueueArray.enqueue(3);
        System.out.println("Array Queue Dequeue: " + intQueueArray.dequeue());
        System.out.println("Array Queue Dequeue: " + intQueueArray.dequeue());

        GenericQueueLinkedList<Integer> intQueueLinkedList = new GenericQueueLinkedList<>();
        intQueueLinkedList.enqueue(1);
        intQueueLinkedList.enqueue(2);
        intQueueLinkedList.enqueue(3);
        System.out.println("Linked List Queue Dequeue: " + intQueueLinkedList.dequeue());
        System.out.println("Linked List Queue Dequeue: " + intQueueLinkedList.dequeue());

        GenericQueueArray<Double> doubleQueueArray = new GenericQueueArray<>(5);
        doubleQueueArray.enqueue(1.1);
        doubleQueueArray.enqueue(2.2);
        doubleQueueArray.enqueue(3.3);
        System.out.println("Array Queue Dequeue: " + doubleQueueArray.dequeue());
        System.out.println("Array Queue Dequeue: " + doubleQueueArray.dequeue());

        GenericQueueLinkedList<Double> doubleQueueLinkedList = new GenericQueueLinkedList<>();
        doubleQueueLinkedList.enqueue(1.1);
        doubleQueueLinkedList.enqueue(2.2);
        doubleQueueLinkedList.enqueue(3.3);
        System.out.println("Linked List Queue Dequeue: " + doubleQueueLinkedList.dequeue());
        System.out.println("Linked List Queue Dequeue: " + doubleQueueLinkedList.dequeue());

        GenericQueueArray<String> stringQueueArray = new GenericQueueArray<>(5);
        stringQueueArray.enqueue("one");
        stringQueueArray.enqueue("two");
        stringQueueArray.enqueue("three");
        System.out.println("Array Queue Dequeue: " + stringQueueArray.dequeue());
        System.out.println("Array Queue Dequeue: " + stringQueueArray.dequeue());

        GenericQueueLinkedList<String> stringQueueLinkedList = new GenericQueueLinkedList<>();
        stringQueueLinkedList.enqueue("one");
        stringQueueLinkedList.enqueue("two");
        stringQueueLinkedList.enqueue("three");
        System.out.println("Linked List Queue Dequeue: " + stringQueueLinkedList.dequeue());
        System.out.println("Linked List Queue Dequeue: " + stringQueueLinkedList.dequeue());
    }
}
// Java program to implement Max Heap

// Main class
public class MaxHeap {
	private int[] Heap;
	private int size;
	private int maxsize;

	public MaxHeap(int maxsize)
	{
		this.maxsize = maxsize;
		this.size = 0;
		Heap = new int[this.maxsize];
	}

	private int parent(int pos) { return (pos - 1) / 2; }

	private int leftChild(int pos) { return (2 * pos) + 1; }
	private int rightChild(int pos)
	{
		return (2 * pos) + 2;
	}

	private boolean isLeaf(int pos)
	{
		if (pos > (size / 2) && pos <= size) {
			return true;
		}
		return false;
	}
	private void swap(int fpos, int spos)
	{
		int tmp;
		tmp = Heap[fpos];
		Heap[fpos] = Heap[spos];
		Heap[spos] = tmp;
	}

	private void maxHeapify(int pos)
	{
		if (isLeaf(pos))
			return;

		if (Heap[pos] < Heap[leftChild(pos)]
			|| Heap[pos] < Heap[rightChild(pos)]) {

			if (Heap[leftChild(pos)]
				> Heap[rightChild(pos)]) {
				swap(pos, leftChild(pos));
				maxHeapify(leftChild(pos));
			}
			else {
				swap(pos, rightChild(pos));
				maxHeapify(rightChild(pos));
			}
		}
	}

	public void insert(int element)
	{
		Heap[size] = element;

		int current = size;
		while (Heap[current] > Heap[parent(current)]) {
			swap(current, parent(current));
			current = parent(current);
		}
		size++;
	}

	public void print()
	{

		for (int i = 0; i < size / 2; i++) {

			System.out.print("Parent Node : " + Heap[i]);

			if (leftChild(i)
				< size) 
				System.out.print(" Left Child Node: "+ Heap[leftChild(i)]);
			if (rightChild(i)
				< size) 						
				System.out.print(" Right Child Node: "+ Heap[rightChild(i)]);

			System.out.println(); 		}
	}

	public int extractMax()
	{
		int popped = Heap[0];
		Heap[0] = Heap[--size];
		maxHeapify(0);
		return popped;
	}

	public static void main(String[] arg)
	{
		System.out.println("The Max Heap is ");

		MaxHeap maxHeap = new MaxHeap(15);

		maxHeap.insert(5);
		maxHeap.insert(3);
		maxHeap.insert(17);
		maxHeap.insert(10);
		maxHeap.insert(84);
		maxHeap.insert(19);
		maxHeap.insert(6);
		maxHeap.insert(22);
		maxHeap.insert(9);
		maxHeap.print();

		System.out.println("The max val is "+ maxHeap.extractMax());
	}
}
import java.util.Scanner;

// Node class for LinkedList-based stack
class Node<T> {
    T data;
    Node<T> next;

    public Node(T data) {
        this.data = data;
        this.next = null;
    }
}

// Generic stack implemented using arrays
class GenericStackArray<T> {
    private T[] stackArray;
    private int top;
    private int maxSize;

    @SuppressWarnings("unchecked")
    public GenericStackArray(int size) {
        this.maxSize = size;
        this.stackArray = (T[]) new Object[maxSize];
        this.top = -1;
    }

    public void push(T item) {
        if (top < maxSize - 1) {
            stackArray[++top] = item;
        } else {
            System.out.println("Stack Overflow");
        }
    }

    public T pop() {
        if (top >= 0) {
            return stackArray[top--];
        } else {
            System.out.println("Stack Underflow");
            return null;
        }
    }

    public boolean isEmpty() {
        return top == -1;
    }
}

// Generic stack implemented using linked lists
class GenericStackLinkedList<T> {
    private Node<T> top;

    public GenericStackLinkedList() {
        this.top = null;
    }

    public void push(T item) {
        Node<T> newNode = new Node<>(item);
        newNode.next = top;
        top = newNode;
    }

    public T pop() {
        if (top == null) {
            System.out.println("Stack Underflow");
            return null;
        }
        T data = top.data;
        top = top.next;
        return data;
    }

    public boolean isEmpty() {
        return top == null;
    }
}

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

        // Testing stack with array implementation
        GenericStackArray<Integer> intStackArray = new GenericStackArray<>(5);
        GenericStackArray<Double> doubleStackArray = new GenericStackArray<>(5);
        GenericStackArray<String> stringStackArray = new GenericStackArray<>(5);

        intStackArray.push(1);
        intStackArray.push(2);
        intStackArray.push(3);
        System.out.println("Popped from intStackArray: " + intStackArray.pop());

        doubleStackArray.push(1.1);
        doubleStackArray.push(2.2);
        doubleStackArray.push(3.3);
        System.out.println("Popped from doubleStackArray: " + doubleStackArray.pop());

        stringStackArray.push("Hello");
        stringStackArray.push("World");
        System.out.println("Popped from stringStackArray: " + stringStackArray.pop());

        // Testing stack with linked list implementation
        GenericStackLinkedList<Integer> intStackLinkedList = new GenericStackLinkedList<>();
        GenericStackLinkedList<Double> doubleStackLinkedList = new GenericStackLinkedList<>();
        GenericStackLinkedList<String> stringStackLinkedList = new GenericStackLinkedList<>();

        intStackLinkedList.push(1);
        intStackLinkedList.push(2);
        intStackLinkedList.push(3);
        System.out.println("Popped from intStackLinkedList: " + intStackLinkedList.pop());

        doubleStackLinkedList.push(1.1);
        doubleStackLinkedList.push(2.2);
        doubleStackLinkedList.push(3.3);
        System.out.println("Popped from doubleStackLinkedList: " + doubleStackLinkedList.pop());

        stringStackLinkedList.push("Hello");
        stringStackLinkedList.push("World");
        System.out.println("Popped from stringStackLinkedList: " + stringStackLinkedList.pop());

        scanner.close();
    }
}
import java.util.LinkedList;
import java.util.Iterator;

public class LinkedListIteratorExample {
    public static void main(String[] args) {
        // Create a LinkedList and add some fruit names
        LinkedList<String> fruits = new LinkedList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        
        // Obtain an iterator for the LinkedList
        Iterator<String> iterator = fruits.iterator();
        
        // Use the iterator to traverse through the LinkedList
        System.out.println("Using Iterator to traverse through the LinkedList:");
        while (iterator.hasNext()) {
            String fruit = iterator.next();
            System.out.println(fruit);
        }
        
        // Use a for-each loop to traverse through the LinkedList
        System.out.println("\nUsing for-each loop to traverse through the LinkedList:");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
        
        // Obtain a new iterator for the LinkedList
        iterator = fruits.iterator(); // Reset the iterator
        while (iterator.hasNext()) {
            String fruit = iterator.next();
            if (fruit.startsWith("B")) {
                iterator.remove(); // Remove elements that start with "B"
            }
        }
        
        // Display the LinkedList after removal of elements that start with 'B'
        System.out.println("\nLinkedList after removal of elements that start with 'B':");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}
import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListIteratorExample {
    public static void main(String[] args) {
        // Create an ArrayList and add some fruit names
        ArrayList<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        
        // Obtain an iterator for the ArrayList
        Iterator<String> iterator = fruits.iterator();
        
        // Use the iterator to traverse through the ArrayList
        System.out.println("Using Iterator to traverse through the ArrayList:");
        while (iterator.hasNext()) {
            String fruit = iterator.next();
            System.out.println(fruit);
        }
        
        // Use a for-each loop to traverse through the ArrayList
        System.out.println("\nUsing for-each loop to traverse through the ArrayList:");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
        
        // Obtain a new iterator for the ArrayList
        iterator = fruits.iterator(); // Reset the iterator
        while (iterator.hasNext()) {
            String fruit = iterator.next();
            if (fruit.startsWith("B")) {
                iterator.remove(); // Remove elements that start with "B"
            }
        }
        
        // Display the ArrayList after removal of elements that start with 'B'
        System.out.println("\nArrayList after removal of elements that start with 'B':");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}
public class ReverseStringLambda {
    @FunctionalInterface
    interface StringReverser {
        String reverse(String str);
    }

    public static void main(String[] args) {
        // Lambda expression to reverse a string
        StringReverser reverser = (str) -> new StringBuilder(str).reverse().toString();
        
        String example = "Hello, World!";
        String reversed = reverser.reverse(example);
        
        // Print original and reversed strings
        System.out.println("Original: " + example);
        System.out.println("Reversed: " + reversed);
    }
}
@FunctionalInterface
interface PiValue {
    double getPi();
}

public class Main {
    public static void main(String[] args) {
        PiValue pi = () -> Math.PI;
        double p = pi.getPi();
        System.out.println("The value of Pi is: " + p);
    }
}
public class MagicBox<T> {
    private T item;

    public void addItem(T item) {
        this.item = item;
        System.out.println("Added item to the magic box: " + item);
    }

    public T getItem() {
        return item;
    }

    public void processBox(MagicBox<? super Integer> box) {
        System.out.println("Items in the box are processed [" + box.getItem() + "]");
    }

    public static void main(String[] args) {
        MagicBox<Integer> integerBox = new MagicBox<>();
        integerBox.addItem(43);
        
        MagicBox<String> stringBox = new MagicBox<>();
        stringBox.addItem("Sofiya");
        
        MagicBox<Boolean> booleanBox = new MagicBox<>();
        booleanBox.addItem(false);
        
        MagicBox<Object> objectBox = new MagicBox<>();
        objectBox.addItem(43.43);

        // Using processBox with a MagicBox that can accept Integer or its supertypes
        integerBox.processBox(integerBox);
        integerBox.processBox(objectBox);

        // The following lines will cause compilation errors as they don't match the processBox parameter type
        // integerBox.processBox(stringBox);
        // integerBox.processBox(booleanBox);
    }
}
public class BoundedArithmetic<T extends Number> {
    public double add(T a, T b) {
        return a.doubleValue() + b.doubleValue();
    }
    
    public double subtract(T a, T b) {
        return a.doubleValue() - b.doubleValue();
    }
    
    public double multiply(T a, T b) {
        return a.doubleValue() * b.doubleValue();
    }
    
    public double divide(T a, T b) {
        if (b.doubleValue() == 0) {
            throw new ArithmeticException("Division by zero is not allowed.");
        }
        return a.doubleValue() / b.doubleValue();
    }
    
    public static void main(String[] args) {
        BoundedArithmetic<Number> calculator = new BoundedArithmetic<>();
        Integer a = 10;
        Integer b = 5;
        System.out.println("Addition: " + calculator.add(a, b));
        System.out.println("Subtraction: " + calculator.subtract(a, b));
        System.out.println("Multiplication: " + calculator.multiply(a, b));
        System.out.println("Division: " + calculator.divide(a, b));
        
        Double x = 15.5;
        Double y = 4.5;
        System.out.println("Addition (Double): " + calculator.add(x, y));
        System.out.println("Subtraction (Double): " + calculator.subtract(x, y));
        System.out.println("Multiplication (Double): " + calculator.multiply(x, y));
        System.out.println("Division (Double): " + calculator.divide(x, y));
    }
}
criteria = "email:equals:"+vendor_email;
response = zoho.crm.searchRecords("users", criteria);
info response;
#include <stdio.h>
struct Banking_Account
{
 char name[32];
 int pin;
 float balance;
};
void print_banking_details(struct Banking_Account account);
int main(void)
{
 struct Banking_Account accounts[3];
 sprintf(accounts[0].name, "Steffan Hooper");
 accounts[0].pin = 7373;
 accounts[0].balance = 1250.0f;
 sprintf(accounts[1].name, "Xinyu Hu");
 accounts[1].pin = 1234;
 accounts[1].balance = 2150.0f;
 sprintf(accounts[2].name, "Jade Abbott");
 accounts[2].pin = 7777;
 accounts[2].balance = 2250.0f;
 print_banking_details(accounts[2]);
 printf("\n");
 print_banking_details(accounts[1]);
 printf("\n");
 print_banking_details(accounts[0]);
 printf("\n");
 return 0;
}
void print_banking_details(struct Banking_Account account)
{
 printf("Account Name: %s\n", account.name);
 printf("Account Balance: $%.2f\n", account.balance);
 printf("Account Pin: %d\n", account.pin);
}
@mixin width {
    width: auto !important;
}
table {
    &.table-fit {
        @include width;
        table-layout: auto !important;
        thead th,
        tbody td,
        tfoot th,
        tfoot td  {
            @include width;
        }
    }
}
table.table-fit {
  width: auto !important;
  table-layout: auto !important;
}
table.table-fit thead th,
table.table-fit tbody td,
table.table-fit tfoot th,
table.table-fit tfoot td {
  width: auto !important;
}
const mongoose = require('mongoose');

function validateEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

const userData = new mongoose.Schema({
    
    email: {
        type: 'string',
        required: true,
        validate:{
            validator: validateEmail,
            message: 'Please enter a valid email',
        }
    },
    password: {
        type: 'string',
        required: true
    }    


  });


  const saveuser = mongoose.model('users', userData);

  module.exports = saveuser;


const mongoose = require('mongoose');

function checkName(name){
    const nameRegex = /^[a-zA-Z]+$/;
    return  nameRegex.test(name);
}

const userDitails = new mongoose.Schema({

    user_id: {
        type: mongoose.Schema.Types.ObjectId,
        required: true
    },
    name: {
        type: 'string',
        required: true,
        validate:{
            validator: checkName,
            message: 'enter valid name'
        }
    },
    phone:{
        type: 'number',
    },
    country: {
        type: 'string',
        enum: ['usa','uk','india']
    },
    file:{
        type: 'string',
    }    

  });


  const saveUserDetails = mongoose.model('userDitails', userDitails);

  module.exports = saveUserDetails;

var jwt = require('jsonwebtoken');


function auth(req,res,next){

    const getToken = req.headers.authorization;

    if(!getToken){
        res.status(401).json({
            status: 'error',
            message: 'not found'
        })
    }

    const tokenCheck = getToken.split(' ');

    if(tokenCheck.length != 2 || tokenCheck[0] !== 'Bearer'){
     
        res.status(401).json({
            status: 'error',
            message: 'Invalid authorization'
        })
        
    }

    const token = tokenCheck[1];

    jwt.verify(token, 'shhhhh', function(err, decoded) {


        if(err){
            res.status(401).json({
                status: 'error',
                message: 'faild authorization'
            })
        }
        
        req.user = decoded;
        next();

      });



}


module.exports = auth;
var express = require('express');
var router = express.Router();
const multer  = require('multer')
const fs = require('fs')
const storage2 = require('node-persist');
const auth = require('../middleware/auth')
var jwt = require('jsonwebtoken');
const path = require('path');



const saveuser = require('../model/user');
const saveUserDetails = require('../model/userDetail');

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/')
  },
  filename: function (req, file, cb) {
    cb(null, `${Date.now()}_${file.originalname}`)
  }
})

const upload = multer(
  { storage: storage }
)

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});


const saveUserData = async (req,res,next) =>{

  try {

    const saveUser = new saveuser({
      email: req.body.email,
      password: req.body.password
    })

    const users = await saveUser.save();

    const userID = users._id;

    const saveDetila = new saveUserDetails({
      user_id: userID,
      name: req.body.name,
      phone: req.body.phone,
      country: req.body.country,
      file: req.file.filename,
    })

    const detils = await saveDetila.save();


    res.status(200).json({
      status: 'success',
      users,
      detils

    })
    
  } catch (error) {
    if (req.file && req.file.path && fs.existsSync(req.file.path)) {
      fs.unlinkSync(req.file.path);
    }
    if(error.name === 'ValidationError'){
      if (req.file && req.file.path && fs.existsSync(req.file.path)) {
        fs.unlinkSync(req.file.path);
      }
      const validationError = {};
      for(const key in error.errors){
        validationError[key] = error.errors[key].message;
      }
      return res.status(400).json({
        error: validationError
      })
    }
    res.send(500).json({
      massage: 'Server Error'
    })

  }

}


const checkUser = async (req,res,next) => {

  try {

    const {email,password} = req.body

    const findUser = await saveuser.find({email: email});

    if(!findUser){
      res.send(201).json({
        status: 'error',
        message: 'Email is not Found'
      })
    }

    if(findUser){

      const passwordCheck = await saveuser.find({password: password});

      if(!passwordCheck){
        res.send(201).json({
          status: 'error',
          message: 'Wrong Password'
        })
      } else {

        const storeData = findUser.toString();
        await storage2.init('');
        await storage2.setItem(storeData,'user');
        var token = jwt.sign({ _id: findUser[0]._id }, 'shhhhh');

        res.status(200).json({
          status: 'success',
          message: 'login Successfully',
          token
        })

      }

    }

    
  } catch (error) {
     
    if(error) throw error;

    res.send(500).json({
      massage: 'Server Error'
    })
    
  }

}


const userList = async (req,res,next) => {
  try {

    const query = {};

    if(req.query.email){
      query.email = { $regex: new RegExp(req.query.email,'i')};
    }

    if(req.query.name){
      query.name = {$regex: new RegExp(req.query.name,'i')};
    }

    if(req.query.phone){
      query.phone = req.query.phone
    }

    if(req.query.country){
      req.query = {$regex: new RegExp(req.query.country,'i')};
    }

    const page = parseInt(req.query.page) || 1;
    const pageSize = parseInt(req.query.pageSize) || 5;

    const Listuser = await saveUserDetails.aggregate([
      {
        $match: query
      },
      {
        $lookup: {
          from: "users",
          localField: "user_id",
          foreignField: "_id",
          as: "user",
        },
      },
      {
        $skip: (page - 1) * pageSize,
      },
      {
        $limit: pageSize
      }
    ])

    res.status(200).json({
      status: 'success',
      Listuser
    });
    
  } catch (error) {
    
    res.send(500).json({
      massage: 'Server Error'
    })

  }
}

const updateUser = async (req, res, next) => {
  try {
    const userid = req.params.id;

    const getuserDetila = await saveUserDetails.findOne({ user_id: userid });

    if (!getuserDetila) {
      return res.status(400).json({
        status: 'error',
        message: 'User not found'
      });
    }

    if (getuserDetila.file) {
      const filePath = path.join('uploads/', getuserDetila.file);
      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
      }
    }

    const userData = await saveuser.findByIdAndUpdate(
      userid,
      {
        email: req.body.email,
        password: req.body.password
      },
      { new: true }
    );

    const userDetails = await saveUserDetails.findOneAndUpdate(
      { user_id: userid },
      {
        name: req.body.name,
        phone: req.body.phone,
        country: req.body.country,
        file: req.file.filename,
      },
      {
        new: true
      }
    );

    res.status(200).json({
      status: 'Success',
      userData,
      userDetails,
    });
  } catch (error) {
    if (req.file && req.file.path && fs.existsSync(req.file.path)) {
      fs.unlinkSync(req.file.path);
    }
    console.error(error); // Log the actual error for debugging
    res.status(500).json({
      status: 'error',
      message: error.message // Send the actual error message
    });
  }
};


const deleteUser = async (req, res, next) => {
  try {
    const userid = req.params.id;

    const getUserDetails = await saveUserDetails.findOne({ user_id: userid });

    if (!getUserDetails) {
      return res.status(400).json({
        status: 'error',
        message: 'User not found'
      });
    }

    if (getUserDetails.file) {
      const filePath = path.join('uploads/', getUserDetails.file);
      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
      }
    }

    await saveuser.findByIdAndDelete(userid);
    await saveUserDetails.findOneAndDelete({ user_id: userid });

    res.status(200).json({
      status: 'Success',
      message: 'User deleted successfully'
    });
  } catch (error) {
    console.error(error); // Log the actual error for debugging
    res.status(500).json({
      status: 'error',
      message: error.message // Send the actual error message
    });
  }
};







router.post('/createUser', upload.single('file'),saveUserData)
router.post('/loginUser', checkUser)
router.get('/getData', auth,userList)
router.put('/updateData/:id', auth,upload.single('file'),updateUser)

module.exports = router;
title: "count no.of 1's"
.model small
.stack 100h
.data
   num1 db 05
   count db dup(0)
.code
   mov ax,@data
       mov ds,ax
       xor ax,ax
   mov al,num1
   mov cx,08
   mov bl,0 
   again: rol al,1
          Jc noadd
          inc bl
   noadd:loop again
         mov count,bl
mov ah,4ch
   int 21h
   end
   
// C Program for Message Queue (Reader Process) 
#include <stdio.h> 
#include <sys/ipc.h> 
#include <sys/msg.h> 

// structure for message queue 
struct mesg_buffer { 
	long mesg_type; 
	char mesg_text[100]; 
} message; 

int main() 
{ 
	key_t key; 
	int msgid; 

	// ftok to generate unique key 
	key = ftok("progfile", 65); 

	// msgget creates a message queue 
	// and returns identifier 
	msgid = msgget(key, 0666 | IPC_CREAT); 

	// msgrcv to receive message 
	msgrcv(msgid, &message, sizeof(message), 1, 0); 

	// display the message 
	printf("Data Received is : %s \n", 
					message.mesg_text); 

	// to destroy the message queue 
	msgctl(msgid, IPC_RMID, NULL); 

	return 0; 
}
	// C Program for Message Queue (Writer Process) 
#include <stdio.h> 
#include <sys/ipc.h> 
#include <sys/msg.h> 
#define MAX 10 

// structure for message queue 
struct mesg_buffer { 
	long mesg_type; 
	char mesg_text[100]; 
} message; 

int main() 
{ 
	key_t key; 
	int msgid; 

	// ftok to generate unique key 
	key = ftok("progfile", 65); 

	// msgget creates a message queue 
	// and returns identifier 
	msgid = msgget(key, 0666 | IPC_CREAT); 
	message.mesg_type = 1; 

	printf("Write Data : "); 
	fgets(message.mesg_text,MAX,stdin); 

	// msgsnd to send message 
	msgsnd(msgid, &message, sizeof(message), 0); 

	// display the message 
	printf("Data send is : %s \n", message.mesg_text); 

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

int main() {
    int fd[2]; // Array to hold the two ends of the pipe: fd[0] for reading, fd[1] for writing
    pid_t pid;
    char writeMessage[] = "Hello from parent process!";
    char readMessage[100];

    // Create the pipe
    if (pipe(fd) == -1) {
        perror("pipe failed");
        return 1;
    }

    // Fork a child process
    pid = fork();

    if (pid < 0) {
        perror("fork failed");
        return 1;
    } else if (pid > 0) {
        // Parent process
        close(fd[0]); // Close the reading end of the pipe in the parent

        // Write a message to the pipe
        write(fd[1], writeMessage, strlen(writeMessage) + 1);
        close(fd[1]); // Close the writing end of the pipe after writing

        // Wait for child process to finish
        wait(NULL);
    } else {
        // Child process
        close(fd[1]); // Close the writing end of the pipe in the child

        // Read the message from the pipe
        read(fd[0], readMessage, sizeof(readMessage));
        printf("Child process received: %s\n", readMessage);
        close(fd[0]); // Close the reading end of the pipe after reading
    }

return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

#define FIFO_NAME "myfifo"

int main() {
    int fd;
    char *message = "Hello from writer process!";
    
    // Create the FIFO if it does not exist
    if (mkfifo(FIFO_NAME, 0666) == -1) {
        perror("mkfifo");
        exit(EXIT_FAILURE);
    }

    // Open the FIFO for writing
    fd = open(FIFO_NAME, O_WRONLY);
    if (fd == -1) {
        perror("open");
        exit(EXIT_FAILURE);
    }

    // Write the message to the FIFO
    if (write(fd, message, strlen(message) + 1) == -1) {
        perror("write");
        close(fd);
        exit(EXIT_FAILURE);
    }

    printf("Writer: Wrote message to FIFO.\n");
    
    // Close the FIFO
    close(fd);

    return 0;
}
#include <stdio.h>
#include <stdlib.h>
#define MAX_FRAMES 100
int isPageInFrame(int frames[], int n, int page) {
    for (int i = 0; i < n; i++) {
        if (frames[i] == page) {
            return 1;
        }
    }
    return 0;
}
void printFrames(int frames[], int n) {
    for (int i = 0; i < n; i++) {
        if (frames[i] == -1) {
            printf("-");
        } else {
            printf("%d", frames[i]);
        }
        if (i < n - 1) {
            printf(" ");
        }
    }
    printf("\n");
}
int main() {
    int n, numFrames;
    int pageFaults = 0;
    printf("Enter the number of frames: ");
    scanf("%d", &numFrames);
    int frames[MAX_FRAMES];
    for (int i = 0; i < numFrames; i++) {
        frames[i] = -1;
    }
    printf("Enter the number of page requests: ");
    scanf("%d", &n);
    int pageRequests[n];
    printf("Enter the page requests: ");
    for (int i = 0; i < n; i++) {
        scanf("%d", &pageRequests[i]);
    }
    int currentFrame = 0;
    for (int i = 0; i < n; i++) {
        int page = pageRequests[i];
        if (!isPageInFrame(frames, numFrames, page)) {
            pageFaults++;
            frames[currentFrame] = page;
            currentFrame = (currentFrame + 1) % numFrames;
        }
        printFrames(frames, numFrames);
    }
    printf("Total page faults: %d\n", pageFaults);
    return 0;
}
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>

int main() {
    // Generate unique key
    key_t key = ftok("shmfile", 65);
    if (key == -1) {
        perror("ftok");
        return 1;
    }

    // Get the shared memory segment
    int shmid = shmget(key, 1024, 0666 | IPC_CREAT);
    if (shmid == -1) {
        perror("shmget");
        return 1;
    }

    // Attach to the shared memory
    char *str = (char*)shmat(shmid, (void*)0, 0);
    if (str == (char*)(-1)) {
        perror("shmat");
        return 1;
    }

    // Read data from shared memory
    printf("Data read from memory: %s\n", str);

    // Detach from shared memory
    if (shmdt(str) == -1) {
        perror("shmdt");
        return 1;
    }

    // Destroy the shared memory
    if (shmctl(shmid, IPC_RMID, NULL) == -1) {
        perror("shmctl");
        return 1;
    }

    return 0;
}
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>

int main() {
    // Generate unique key
    key_t key = ftok("shmfile", 65);
    if (key == -1) {
        perror("ftok");
        return 1;
    }

    // Create shared memory segment
    int shmid = shmget(key, 1024, 0666 | IPC_CREAT);
    if (shmid == -1) {
        perror("shmget");
        return 1;
    }

    // Attach to shared memory
    char *str = (char*)shmat(shmid, (void*)0, 0);
    if (str == (char*)(-1)) {
        perror("shmat");
        return 1;
    }

    // Write data to shared memory
    printf("Write Data : ");
    fgets(str, 1024, stdin);
    // Remove the newline character added by fgets
    str[strcspn(str, "\n")] = 0;

    printf("Data written in memory: %s\n", str);

    // Detach from shared memory
    if (shmdt(str) == -1) {
        perror("shmdt");
        return 1;
    }

    return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

int main() {
    int file;
    off_t offset;
    char buffer[20];

    // Open file
    file = open("file.txt", O_RDONLY);
    if (file == -1) {
        perror("Error opening file");
        exit(EXIT_FAILURE);
    }

    // Move file offset to 10 bytes from the beginning
    offset = lseek(file, 10, SEEK_SET);
    if (offset == -1) {
        perror("Error seeking in file");
        close(file);
        exit(EXIT_FAILURE);
    }

    // Read from the new offset
    if (read(file, buffer, 20) == -1) {
        perror("Error reading from file");
        close(file);
        exit(EXIT_FAILURE);
    }

    // Print the read content
    printf("Read content: %.*s\n", 20, buffer);

    // Close file
    close(file);

    return 0;
}
star

Fri Jun 07 2024 14:18:48 GMT+0000 (Coordinated Universal Time)

@ayushg103 #c++

star

Fri Jun 07 2024 14:04:18 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 14:03:07 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 14:02:25 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 14:01:40 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 14:00:56 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 13:59:29 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 13:58:39 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 13:58:10 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 13:57:08 GMT+0000 (Coordinated Universal Time)

@lokan32 #postgres #postgresql #json

star

Fri Jun 07 2024 13:56:50 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 13:54:41 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 13:20:36 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 13:19:38 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 13:19:29 GMT+0000 (Coordinated Universal Time)

@exam

star

Fri Jun 07 2024 13:18:27 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 13:16:51 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 13:13:50 GMT+0000 (Coordinated Universal Time)

@ayushg103 #c++

star

Fri Jun 07 2024 12:56:59 GMT+0000 (Coordinated Universal Time)

@ayushg103 #c++

star

Fri Jun 07 2024 12:53:28 GMT+0000 (Coordinated Universal Time)

@signup

star

Fri Jun 07 2024 12:52:09 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 12:45:22 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 12:44:47 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 12:38:52 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 12:35:28 GMT+0000 (Coordinated Universal Time)

@signup

star

Fri Jun 07 2024 12:34:59 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 12:22:52 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 12:20:07 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 12:07:31 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 12:05:36 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 12:02:16 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 11:55:13 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 11:32:25 GMT+0000 (Coordinated Universal Time)

@RehmatAli2024 #deluge

star

Fri Jun 07 2024 11:27:55 GMT+0000 (Coordinated Universal Time)

@meanaspotato #c

star

Fri Jun 07 2024 10:29:12 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/31184000/making-a-bootstrap-table-column-fit-to-content

@xsirlalo #css

star

Fri Jun 07 2024 10:29:10 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/31184000/making-a-bootstrap-table-column-fit-to-content

@xsirlalo #css

star

Fri Jun 07 2024 08:48:16 GMT+0000 (Coordinated Universal Time) https://github.com/octocat/Hello-World

@calazar23

star

Fri Jun 07 2024 08:30:13 GMT+0000 (Coordinated Universal Time) https://www.dappfort.com/bybit-clone-script/

@novamichelin #ruby #nodejs #json #react.js #css

star

Fri Jun 07 2024 08:10:23 GMT+0000 (Coordinated Universal Time)

@sid_balar

star

Fri Jun 07 2024 08:09:41 GMT+0000 (Coordinated Universal Time)

@sid_balar

star

Fri Jun 07 2024 08:09:01 GMT+0000 (Coordinated Universal Time)

@sid_balar

star

Fri Jun 07 2024 06:09:21 GMT+0000 (Coordinated Universal Time)

@signup

star

Fri Jun 07 2024 04:58:50 GMT+0000 (Coordinated Universal Time)

@prabhas

star

Fri Jun 07 2024 04:58:22 GMT+0000 (Coordinated Universal Time)

@prabhas

star

Fri Jun 07 2024 04:57:31 GMT+0000 (Coordinated Universal Time)

@prabhas

star

Fri Jun 07 2024 04:56:58 GMT+0000 (Coordinated Universal Time)

@prabhas

star

Fri Jun 07 2024 04:56:22 GMT+0000 (Coordinated Universal Time)

@prabhas

star

Fri Jun 07 2024 04:54:34 GMT+0000 (Coordinated Universal Time)

@prabhas

star

Fri Jun 07 2024 04:53:54 GMT+0000 (Coordinated Universal Time)

@prabhas

star

Fri Jun 07 2024 04:52:04 GMT+0000 (Coordinated Universal Time)

@prabhas

Save snippets that work with our extensions

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