Snippets Collections
# RECOMMENDED WAY
import boto3
client = boto3.client(
    s3,                         # boto3 will get the credentials either from
    region_name=us-east-1       # environment vars. or the .aws/credentials file.
)
class Superclass<T> {
    private T element;
    
    public Superclass(T element) {
        this.element = element;
    }
    
    public T getEle() {
        return this.element;
    }
}

class Subclass<T, V> extends Superclass<T> {
    private V value;
    
    public Subclass(T element, V value) {
        super(element);
        this.value = value;
    }
    
    public V getValue() {
        return this.value;
    }
}

public class Hierarchy {
    public static void main(String[] args) {
        System.out.println(" ABC");
        Subclass<String, Integer> h1 = new Subclass<>("abc", 123);
        System.out.println(h1.getEle());
        System.out.println(h1.getValue());
    }
}
public class GenericMethod {
    public static <K, R, V> boolean compare(Pack<K, R> p1, Pack<K, V> p2) {
        return p1.getKey().equals(p2.getKey()) && p1.getValue().equals(p2.getValue());
    }

    public static void main(String[] args) {
        Pack<Integer, String> p1 = new Pack<>(1, "pack");
        Pack<Integer, String> p2 = new Pack<>(2, "abc");
        Pack<Integer, String> p3 = new Pack<>(1, "pack");
        
        System.out.println("p1 & p2 are same?: " + compare(p1, p2));
        System.out.println("p1 & p3 are same?: " + compare(p1, p3));
    }
}

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

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

    public K getKey() {
        return this.key;
    }

    public V getValue() {
        return this.value;
    }
}
import boto3

def read_s3_file(bucket_name, file_name):
    s3 = boto3.client('s3')
    try:
        response = s3.get_object(Bucket=bucket_name, Key=file_name)
        return response['Body'].read().decode('utf-8')
    except Exception as e:
        print(f"Error reading file from S3: {e}")
        return None
import boto3
import json

def read_ocr_from_s3(bucket_name, key_name):
    s3 = boto3.client('s3')
    response = s3.get_object(Bucket=bucket_name, Key=key_name)
    ocr_data = json.loads(response['Body'].read().decode('utf-8'))
    return ''.join([item["text"] for item in ocr_data])
@import 'jeet'

@import 'nib'

​

.large-header

   position: relative

   width: 0%

   background: #eeeeee

   overflow: hidden

   background-size: cover
10
   background-position: center center

   z-index: 1

​

.demo .large-header

   background-image: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/4994/demo-bg.jpg')

​
16
.main-title

   position: absolute

   margin: 0

   padding: 0

   color: #ffffff

   text-align: center

   top: 50%

   left: 50%
@import 'jeet'

@import 'nib'

​

.large-header

   position: relative

   width: 0%

   background: #eeeeee

   overflow: hidden

   background-size: cover
10
   background-position: center center

   z-index: 1

​

.demo .large-header

   background-image: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/4994/demo-bg.jpg')

​
16
.main-title

   position: absolute

   margin: 0

   padding: 0

   color: #ffffff

   text-align: center

   top: 50%

   left: 50%
<div class="container demo">

   <div class="content">

      <div id="large-header" class="large-header">

         <canvas id="demo-canvas"></canvas>

         <h1 class="main-title"><span>IMD <span class='thin'>[ Coach ]</h1>

      </div>

   </div>

</div>
import java.util.Scanner;

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

        System.out.println("Enter the Email address");
        String email = scanner.nextLine();

        if (isValidEmail(email)) {
            System.out.println("Valid Email address");
        } else {
            System.out.println("Invalid Email address");
        }

        scanner.close();
    }

    public static boolean isValidEmail(String email) {
        // Check if email contains '@' character
        if (!email.contains("@")) {
            return false;
        }

        // Split email address into local part and domain part
        String[] parts = email.split("@");
        String localPart = parts[0];
        String domainPart = parts[1];

        // Check if local part and domain part are not empty
        if (localPart.isEmpty() || domainPart.isEmpty()) {
            return false;
        }

        // Check if domain part contains '.' character
        if (!domainPart.contains(".")) {
            return false;
        }

        // Split domain part into domain name and domain extension
        String[] domainParts = domainPart.split("\\.");
        String domainName = domainParts[0];
        String domainExtension = domainParts[1];

        // Check if domain extension is valid
        if (!domainExtension.equals("in") && !domainExtension.equals("com")
                && !domainExtension.equals("net") && !domainExtension.equals("biz")) {
            return false;
        }

        return true;
    }
}
import java.util.*;

public class Stack<E extends Number> {
    private ArrayList<E> list;

    public Stack(ArrayList<E> list) {
        this.list = list;
    }

    public void push(E element) {
        list.add(element);
    }

    public E pop() {
        E v = list.get(list.size() - 1);
        list.remove(list.size() - 1);
        return v;
    }

    public double avg() {
        int len = list.size();
        double sum = 0.0;
        for (E item : list) {
            sum += item.doubleValue();
        }
        return sum / len;
    }

    public boolean compareAvg(Stack<E> s) {
        return this.avg() == s.avg();
    }

    public static void main(String[] args) {
        ArrayList<Integer> intList = new ArrayList<>();
        Stack<Integer> s1 = new Stack<>(intList);
        s1.push(1);
        s1.push(2);
        s1.push(3);
        s1.push(4);
        System.out.println("Integer average: " + s1.avg());

        ArrayList<Double> doubleList = new ArrayList<>();
        Stack<Double> s2 = new Stack<>(doubleList);
        s2.push(1.1);
        s2.push(2.2);
        s2.push(3.3);
        s2.push(4.4);
        System.out.println("Double average: " + s2.avg());

        // Create another stack with the same type
        Stack<Integer> s3 = new Stack<>(new ArrayList<>());
        s3.push(5);
        s3.push(6);
        s3.push(7);
        s3.push(8);
        System.out.println("Are averages same: " + s1.compareAvg(s3));
    }
}
//Main.java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        CountryBO countryBO = new CountryBO();
        AirportBO airportBO = new AirportBO();

        // Input for Country
        System.out.println("Enter the country count:");
        int countryCount = scanner.nextInt();
        scanner.nextLine(); // Consume newline character
        Country[] countries = new Country[countryCount];
        for (int i = 0; i < countryCount; i++) {
            System.out.println("Enter country " + (i + 1) + " details");
            String countryData = scanner.nextLine();
            countries[i] = countryBO.createCountry(countryData);
        }

        // Input for Airport
        System.out.println("Enter the airport count:");
        int airportCount = scanner.nextInt();
        scanner.nextLine(); // Consume newline character
        Airport[] airports = new Airport[airportCount];
        for (int i = 0; i < airportCount; i++) {
            System.out.println("Enter airport " + (i + 1) + " details:");
            String airportData = scanner.nextLine();
            airports[i] = airportBO.createAirport(airportData, countries);
        }

        // Find country for airport
        System.out.println("Enter the airport name for which you need to find the country name:");
        String airportName = scanner.nextLine();
        String countryName = airportBO.findCountryName(airports, airportName);
        System.out.println(airportName + " belongs to " + countryName);

        // Compare airports
        System.out.println("Enter 2 airport names:");
        String airportName1 = scanner.nextLine();
        String airportName2 = scanner.nextLine();
        boolean sameCountry = airportBO.findWhetherAirportsAreInSameCountry(airports, airportName1, airportName2);
        if (sameCountry) {
            System.out.println("The 2 airports are in the same Country");
        } else {
            System.out.println("The 2 airports are in different Country");
        }

        scanner.close();
    }
}






public class AirportBO {
    public Airport createAirport(String data, Country[] countryList) {
        String[] parts = data.split(",");
        for (Country country : countryList) {
            if (country.getCountryName().equals(parts[1])) {
                return new Airport(parts[0], country);
            }
        }
        return null;
    }

    public String findCountryName(Airport[] airportList, String airportName) {
        for (Airport airport : airportList) {
            if (airport.getAirportName().equals(airportName)) {
                return airport.getCountry().getCountryName();
            }
        }
        return null;
    }

    public boolean findWhetherAirportsAreInSameCountry(Airport[] airportList, String airportName1, String airportName2) {
        String country1 = null, country2 = null;
        for (Airport airport : airportList) {
            if (airport.getAirportName().equals(airportName1)) {
                country1 = airport.getCountry().getCountryName();
            }
            if (airport.getAirportName().equals(airportName2)) {
                country2 = airport.getCountry().getCountryName();
            }
        }
        return country1 != null && country2 != null && country1.equals(country2);
    }
}






public class Airport {
    private String airportName;
    private Country country;

    public Airport() {}

    public Airport(String airportName, Country country) {
        this.airportName = airportName;
        this.country = country;
    }

    public String getAirportName() {
        return airportName;
    }

    public void setAirportName(String airportName) {
        this.airportName = airportName;
    }

    public Country getCountry() {
        return country;
    }

    public void setCountry(Country country) {
        this.country = country;
    }
}





public class CountryBO {
    public Country createCountry(String data) {
        String[] parts = data.split(",");
        return new Country(parts[0], parts[1]);
    }
}




public class Country {
    private String iataCountryCode;
    private String countryName;

    public Country() {}

    public Country(String iataCountryCode, String countryName) {
        this.iataCountryCode = iataCountryCode;
        this.countryName = countryName;
    }

    public String getIataCountryCode() {
        return iataCountryCode;
    }

    public void setIataCountryCode(String iataCountryCode) {
        this.iataCountryCode = iataCountryCode;
    }

    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
}
//Country.java
class Country {
    private String iataCountryCode;
    private String countryName;

    public Country() {
    }

    public Country(String iataCountryCode, String countryName) {
        this.iataCountryCode = iataCountryCode;
        this.countryName = countryName;
    }

    public String getIataCountryCode() {
        return iataCountryCode;
    }

    public void setIataCountryCode(String iataCountryCode) {
        this.iataCountryCode = iataCountryCode;
    }

    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }

    @Override
    public String toString() {
        return String.format("%-25s %s", iataCountryCode, countryName);
    }
}

//Client.java
class Client {
    private Integer clientId;
    private String clientName;
    private String phoneNumber;
    private String email;
    private String passport;
    private Country country;

    public Client() {
    }

    public Client(Integer clientId, String clientName, String phoneNumber, String email, String passport, Country country) {
        this.clientId = clientId;
        this.clientName = clientName;
        this.phoneNumber = phoneNumber;
        this.email = email;
        this.passport = passport;
        this.country = country;
    }

    public Integer getClientId() {
        return clientId;
    }

    public void setClientId(Integer clientId) {
        this.clientId = clientId;
    }

    public String getClientName() {
        return clientName;
    }

    public void setClientName(String clientName) {
        this.clientName = clientName;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassport() {
        return passport;
    }

    public void setPassport(String passport) {
        this.passport = passport;
    }

    public Country getCountry() {
        return country;
    }

    public void setCountry(Country country) {
        this.country = country;
    }

    @Override
    public String toString() {
        return String.format("%-25s %-25s %-25s %-25s %-25s %s", clientId, clientName, phoneNumber, email, passport, country);
    }
}


//ClientBO.java
class ClientBO {
    void viewDetails(Client[] clientList) {
        System.out.printf("%-25s %-25s %-25s %-25s %-25s %-25s %-25s\n", "ClientId", "ClientName", "PhoneNumber", "Email", "Passport", "IATACountryCode", "CountryName");
        for (Client client : clientList) {
            System.out.println(client);
        }
    }

    void printClientDetailsWithCountry(Client[] clientList, String countryName) {
        System.out.printf("%-25s %-25s %-25s %-25s %-25s %-25s %-25s\n", "ClientId", "ClientName", "PhoneNumber", "Email", "Passport", "IATACountryCode", "CountryName");
        boolean found = false;
        for (Client client : clientList) {
            if (client.getCountry().getCountryName().equalsIgnoreCase(countryName)) {
                System.out.println(client);
                found = true;
            }
        }
        if (!found) {
            System.out.println("No clients found for the specified country.");
        }
    }
}


//Main.java
import java.util.*;
import java.io.*;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        Integer n, i, ch;
        String clientName, phoneNumber, email, passport, countryName, iataCountryCode;
        Integer clientId;

        System.out.println("Enter number of clients");
        n = Integer.parseInt(br.readLine());
        Client clientList[] = new Client[n];

        ClientBO clientBo = new ClientBO();

        Country country = new Country();

        for (i = 0; i < n; i++) {
            clientList[i] = new Client();
            System.out.println("Enter client " + (i + 1) + " details:");

            System.out.println("Enter the client id");
            clientId = Integer.parseInt(br.readLine());

            System.out.println("Enter the client name");
            clientName = br.readLine();

            System.out.println("Enter the phone number");
            phoneNumber = br.readLine();

            System.out.println("Enter the email id");
            email = br.readLine();

            System.out.println("Enter the passport number");
            passport = br.readLine();

            System.out.println("Enter the iata country code");
            iataCountryCode = br.readLine();

            System.out.println("Enter the country name");
            countryName = br.readLine();

            country = new Country(iataCountryCode, countryName);

            clientList[i] = new Client(clientId, clientName, phoneNumber, email, passport, country);

        }

        do {
            System.out.println("Menu:");
            System.out.println("1. View client details");
            System.out.println("2. Filter client with country");
            System.out.println("3. Exit");

            ch = Integer.parseInt(br.readLine());

            if (ch == 1) {
                clientBo.viewDetails(clientList);
            } else if (ch == 2) {
                System.out.println("Enter country name");
                countryName = br.readLine();
                clientBo.printClientDetailsWithCountry(clientList, countryName);
            } else
                break;

        } while (ch <= 2);

    }

}

//collections


//CallLog.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

class CallLog implements Comparable<CallLog> {
    String name;
    String dialledNumber;
    int duration;
    String dialledDate;

    public CallLog(String name, String dialledNumber, int duration, String dialledDate) {
        this.name = name;
        this.dialledNumber = dialledNumber;
        this.duration = duration;
        this.dialledDate = dialledDate;
    }

    @Override
    public int compareTo(CallLog o) {
        return this.name.compareTo(o.name);
    }

    @Override
    public String toString() {
        return String.format("%s(+91-%s) %d Seconds", name, dialledNumber, duration);
    }
}


 //Main.java//
import java.util.ArrayList;
import java.util.Collections;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException
public class Main {
    public static void main(String[] args) {
        ArrayList<CallLog> logs = readCallLogsFromFile("weeklycall.csv");

        Collections.sort(logs);
        Collections.reverse(logs); // Reverse the sorted list
        System.out.println("Call-Logs");
        System.out.println("Caller Name Duration");
        for (CallLog log : logs) {
            System.out.println(log);
        }
    }

    private static ArrayList<CallLog> readCallLogsFromFile(String filename) {
        ArrayList<CallLog> logs = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split(",");
                String name = parts[0];
                String dialledNumber = parts[1];
                int duration = Integer.parseInt(parts[2]);
                String dialledDate = parts[3];
                logs.add(new CallLog(name, dialledNumber, duration, dialledDate));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return logs;
    }
}


//collection 2
import java.util.*;

class Card {
    private String symbol;
    private int number;

    public Card(String symbol, int number) {
        this.symbol = symbol;
        this.number = number;
    }

    public String getSymbol() {
        return symbol;
    }

    public int getNumber() {
        return number;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null || getClass() != obj.getClass())
            return false;
        Card card = (Card) obj;
        return Objects.equals(symbol, card.symbol);
    }

    @Override
    public int hashCode() {
        return Objects.hash(symbol);
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Set<Card> uniqueSymbols = new HashSet<>();
        int cardsCollected = 0;

        while (uniqueSymbols.size() < 4) {
            System.out.println("Enter a card :");
            String symbol = scanner.next();
            int number = scanner.nextInt();
            Card card = new Card(symbol, number);
            uniqueSymbols.add(card);
            cardsCollected++;
        }

        System.out.println("Four symbols gathered in " + cardsCollected + " cards.");
        System.out.println("Cards in Set are :");
        for (Card card : uniqueSymbols) {
            System.out.println(card.getSymbol() + " " + card.getNumber());
    }
}
}
//collections 2 asses 2
 import java.util.*;

class Card {
    private String symbol;
    private int number;

    public Card(String symbol, int number) {
        this.symbol = symbol;
        this.number = number;
    }

    public String getSymbol() {
        return symbol;
    }

    public int getNumber() {
        return number;
    }

    @Override
    public String toString() {
        return symbol + " " + number;
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Map<String, List<Card>> symbolMap = new TreeMap<>();

        System.out.println("Enter Number of Cards :");
        int N = scanner.nextInt();

        for (int i = 0; i < N; i++) {
            System.out.println("Enter card " + (i + 1) + ":");
            String symbol = scanner.next();
            int number = scanner.nextInt();
            Card card = new Card(symbol, number);

            // If the symbol is already in the map, add the card to its list, else create a new list
            symbolMap.computeIfAbsent(symbol, k -> new ArrayList<>()).add(card);
        }

        // Print distinct symbols in alphabetical order
        System.out.println("Distinct Symbols are :");
        for (String symbol : symbolMap.keySet()) {
            System.out.print(symbol + " ");
        }
        System.out.println();

        // Print details for each symbol
        for (Map.Entry<String, List<Card>> entry : symbolMap.entrySet()) {
            String symbol = entry.getKey();
            List<Card> cards = entry.getValue();

            System.out.println("Cards in " + symbol + " Symbol");
            for (Card card : cards) {
                System.out.println(card);
            }
            System.out.println("Number of cards : " + cards.size());
            int sum = cards.stream().mapToInt(Card::getNumber).sum();
            System.out.println("Sum of Numbers : " + sum);
        }
    }
}

Client.java

public class Client {
    private Integer clientId;
    private String name;
    private String email;
    private String phoneNumber;
    private String country;

    public Client(Integer clientId, String name, String email, String phoneNumber, String country) {
        this.clientId = clientId;
        this.name = name;
        this.email = email;
        this.phoneNumber = phoneNumber;
        this.country = country;
    }

    // Getters and Setters
    public Integer getClientId() {
        return clientId;
    }

    public void setClientId(Integer clientId) {
        this.clientId = clientId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    // Override toString method for CSV format
    @Override
    public String toString() {
        return clientId + "," + name + "," + email + "," + phoneNumber + "," + country;
    }
}

Main.java**

 import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
            FileUtility fileUtility = new FileUtility();
            Client[] clients = fileUtility.readFileData(br);
            Arrays.sort(clients, Comparator.comparing(Client::getClientId));
            fileUtility.writeDataToFile(clients);
            System.out.println("Output file generated successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
FileUtility.java**
  
  import java.io.*;
import java.util.*;

public class FileUtility {
    public Client[] readFileData(BufferedReader br) throws IOException {
        List<Client> clientList = new ArrayList<>();
        String line;
        while ((line = br.readLine()) != null) {
            String[] parts = line.split(",");
            Integer clientId = Integer.parseInt(parts[0].trim());
            String name = parts[1].trim();
            String email = parts[2].trim();
            String phoneNumber = parts[3].trim();
            String country = parts[4].trim();
            clientList.add(new Client(clientId, name, email, phoneNumber, country));
        }
        br.close();
        return clientList.toArray(new Client[0]);
    }

    public void writeDataToFile(Client[] clientArray) throws IOException {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.csv"))) {
            for (Client client : clientArray) {
                writer.write(client.toString());
                writer.newLine();
            }
        }
    }
}
public class Pair<K, V> {
    private K key;
    private V val;
    
    public Pair(K key, V val) {
        this.key = key;
        this.val = val;
    }
    
    public K getKey() {
        return this.key;
    }
    
    public V getVal() {
        return this.val;
    }
    
    public static void main(String[] args) {
        Pair<Integer, String> p1 = new Pair<>(123, "abc");
        Integer i = p1.getKey();
        System.out.println(i);
        System.out.println(p1.getVal());
    }
}
**Main.java**

import java.io.*;
import java.util.Scanner;
 public class Main {
public static void main(String[] args) {
 try {
Scanner scanner = new Scanner(System.in);
// Get airport details from the user
 System.out.println("Enter the name of the airport:");
String name = scanner.nextLine();
System.out.println("Enter the city name:");
String cityName = scanner.nextLine();
System.out.println("Enter the country code:");
 String countryCode = scanner.nextLine();
 // Write airport details to a CSV file
 FileWriter writer = new FileWriter("airport.csv");
writer.write(name + "," + cityName + "," + countryCode);
writer.close();
System.out.println("Airport details have been written to airport.csv successfully.");
 }
catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
 e.printStackTrace();
}
 }
}   
public class Container<T> {
    private T obj;

    public Container(T obj) {
        this.obj = obj;
    }

    public T getObj() {
        return this.obj;
    }

    public void showType() {
        System.out.println("Type: " + obj.getClass().getName());
    }

    public static void main(String[] args) {
        Container<String> c1 = new Container<>("generic");
        String s = c1.getObj();
        System.out.println("String is: " + s);
        c1.showType();

        Container<Integer> c2 = new Container<>(123);
        Integer i = c2.getObj();
        System.out.println("Integer is: " + i);
        c2.showType();
    }
}
//GameScreenLevel1.cpp
void GameScreenLevel1::SetLevelMap() {
	//0 blank, 1 wall, 2 win condition
	int map[MAP_HEIGHT][MAP_WIDTH] = {
		{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
		{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
		{1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1},
		{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
		{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
		{0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0},
		{1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1},
		{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
		{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
		{1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1},
		{0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
		{0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
		{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
	};

	//Clear up any old map
	if (mLevelMap != NULL)
	{
		delete mLevelMap;

	}

	//Set up the new one
	mLevelMap = new LevelMap(map);
}


//Collision.cpp
bool Collision::Circle(Character* character1, Character* character2) {
	//Calculate Vector between 2 characters
	Vector2D vec = Vector2D((character1->GetPosition().x - character2->GetPosition().x), (character1->GetPosition().y - character2->GetPosition().y));

	//Calculate lenght from vector
	double distance = sqrt((vec.x * vec.x) + (vec.y * vec.y));

	//Get Collision Radius 
	double combinedDistance = (character1->GetCollisionRadius() - character2->GetCollisionRadius());

	if (distance < combinedDistance) {
		return true;
	}
	else return false;
}

bool Collision::Box(Rect2D rect1, Rect2D rect2) {
	if (rect1.x + (rect1.width / 2) > rect2.x && rect1.x + (rect1.width / 2) < rect2.x + rect2.width && rect1.y + (rect1.height / 2) > rect2.y && rect1.y + (rect1.height / 2) < rect2.y + rect2.height) {
		return true;
	}
	return false;
}
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int n_pages, size_page, n_frames, size_physical_memory, size_logical_memory;
int m, n,i,j;
int p = 0, d = 0;

int find_p(int),find_d(int);


int main()
{
    // Scanning size of Physical memory
    printf("Enter size of physical memory (power of 2)=  ");
    scanf("%d", &size_physical_memory);

    // Scanning the size of page
    // Frame size == Page size
    printf("Enter size of page/frame (power of 2)=  ");
    scanf("%d", &size_page);

    // Scanning number of pages in logical memory
    //printf("Enter no. of pages = ");
  //  scanf("%d", &n_pages);

   // size_logical_memory = size_page * n_pages;
   printf("Enter size of logical memory (power of 2)= ");
   scanf("%d",&size_logical_memory);
    n_pages=size_logical_memory/size_page;

    // Calculating the number of frames in the Physical memory
    n_frames = size_physical_memory / size_page;

    printf("\n\t\t\tLogical-Memory\t\tPhysical-Memory\n");
    printf("No. of Pages/frames\t\t%d\t\t\t%d\n", n_pages, n_frames);
    printf("Page/Frame size\t\t\t%d\t\t\t%d\n", size_page, size_page);
    printf("Size of Memory\t\t\t%d\t\t\t%d\n\n", size_logical_memory, size_physical_memory);

    // Declaring the Pages,Frames and Pagetable
    char pages[n_pages][size_page];
    int pagetable[n_pages];
    char frames[n_frames][size_page];

    n = sqrt(size_page);
    m = sqrt(size_page * n_pages);

    getchar();

    // Scanning Pages data
    printf("Enter details of the data availalbe in Logical Address Space\n");
    for (i = 0; i < n_pages; i++)
    {
        printf(" Enter the page%d data : ", (i));
        for (j = 0; j < size_page; j++)
        {
			pages[i][j] = getchar();
            getchar();
        }
    }

//Data Available in Logical Address
	printf("\nData Available in Logical Address is:\n");
	for (i = 0; i < n_pages; i++)
    {
        printf("\n Page%d: ", (i));
        for (j = 0; j < size_page; j++)
        {
			printf("%c\t",pages[i][j]);
        }
    }


    // Scanning Pagetable data
    printf("\nEnter the details of page table : \n");
for (i = 0; i < n_pages; i++) {
    printf(" Page%d stored in Frame: ", i);
    scanf("%d", &pagetable[i]);
}

	
        // Initializing all the default frames values to '0'
    for (i = 0; i < n_frames; i++){
        for (j = 0; j < size_page; j++)
        {
            frames[i][j] = '-';
        }
    }



    // Placing the data from pages to frams using page table
    for (i = 0; i < n_pages; i++)
    {
        p = i;
        int f = pagetable[p];
        for (j = 0; j < size_page; j++)
        {
            d = j;
            // Initializing Frames using (f,d)
            frames[f][d] = pages[i][j];
        }
    }

    // Displaying the Frames data
    printf("\nAccording to the given Page Table information \nFrames in the Physical Memory are loaded with following data:\n");
    for (i = 0; i < n_frames; i++)
    {
        printf(" \tFrame%d: ",i);
		for (j = 0; j < size_page; j++)
            printf("%c ", frames[i][j]);
        printf("\n");
    }
    printf("\n");

    // Finding the Physical address through Logical address
    printf("Enter any one address of Logical Memory : ");
    int n;
    scanf("%d", &n);
    p = find_p(n);
    d = find_d(n);
    int f = pagetable[p];
    printf(" Calculated Page Number is: %d\n",p);
    printf(" Calculated Displacement is: %d",d);
    printf("\nThe Physical address of %d (given Logical Address) is %d\n", n, (f * size_page) + d);
    printf("Data item \"%c\" of Logical Address %d is found at Physical Address %d i.e., at Frame Number %d with Displacement %d = \"%c\"\n", pages[n/4][n%4], n, (f * size_page) + d, f, d, frames[f][d]);


    
}

int find_p(int n)
{
    int res = n / size_page;
    return res;
}

int find_d(int n)
{
    int res = n % size_page;
    return res;
}

import {
  ButtonContent,
  DestructiveButton,
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  Icon,
  Input,
  Toaster,
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "ui";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import * as z from "zod";
import React, { useState } from "react";
import { toast } from "sonner";
import wretch from "wretch";
import { useGetVesselFromIMO } from "@/hooks";

const formSchema = z.object({
  imo: z.string().max(7),
  cargo_type: z.string().optional(),
  cargo_sub_type: z.string().optional(),
  mmsi: z.string().max(9).optional(),
  vessel_name: z.string().optional(),
  year_of_build: z.string().optional(),
  flag: z.string().optional(),
  grt: z.string().optional(),
  dwt: z.string().optional(),
  overall_length: z.string().optional(),
  beam: z.string().optional(),
});

const fieldsNameHelper = {
  imo: {
    name: "IMO",
    description: "International Maritime Organization identifier",
  },
  cargo_type: {
    name: "Cargo Type",
    description: "The type of cargo the vessel carries",
  },
  cargo_sub_type: {
    name: "Cargo Sub Type",
    description: "The subtype of cargo the vessel carries",
  },
  mmsi: { name: "MMSI", description: "Maritime Mobile Service Identity" },
  vessel_name: { name: "Vessel Name", description: "The name of the vessel" },
  year_of_build: {
    name: "Year of Build",
    description: "The year the vessel was built",
  },
  flag: { name: "Flag", description: "The flag country code" },
  grt: { name: "GRT", description: "Gross Registered Tonnage" },
  dwt: { name: "DWT", description: "Dead Weight Tonnage" },
  overall_length: {
    name: "Overall Length",
    description: "The overall length of the vessel",
  },
  beam: { name: "Beam", description: "The beam of the vessel" },
};

export function VesselInfoForm() {
  const [imoChecked, setImoChecked] = useState(false);
  const [updateError, setUpdateError] = useState(null);
  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {},
  });

  const imoValue = form.watch("imo");
  const {
    data: vesselData,
    isError,
    isLoading,
  } = useGetVesselFromIMO(imoValue);

  async function onSubmit(values) {
    setUpdateError(null);
    try {
      if (!imoChecked) {
        setImoChecked(true);
        if (vesselData?.length) {
          toast.error("Vessel already exists");
        }
      } else {
        const response = await wretch("/api/form/insertVessel")
          .post(values)
          .res();
        if (response.ok) {
          toast.success("Success!", {
            description: "Vessel details added.",
          });
          form.reset();
          setImoChecked(false);
        } else {
          throw new Error("Error submitting form");
        }
      }
    } catch (error) {
      setUpdateError(error);
    }
  }

  return (
    <div className={"mt-4"}>
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
          <FormField
            control={form.control}
            name="imo"
            render={({ field }) => (
              <FormItem className={"flex flex-row items-center"}>
                <FormLabel className={"w-64 text-lg font-light"}>
                  {fieldsNameHelper.imo.name}
                </FormLabel>
                <div className={"mr-2"}>
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger className="text-black hover:text-black/50 dark:text-white dark:hover:text-white/50">
                        <Icon name="unknown" style="h-5 w-5" />
                      </TooltipTrigger>
                      <TooltipContent>
                        <p>{fieldsNameHelper.imo.description}</p>
                      </TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                </div>
                <FormControl className={"w-full"}>
                  <Input
                    {...field}
                    className={"text-md font-light"}
                    type="text"
                    value={field.value ?? ""}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          {imoChecked && vesselData && vesselData.length > 0 ? (
            <div className="vessel-info">
              <h2 className="text-lg font-semibold">Vessel Information</h2>
              <ul>
                {Object.keys(fieldsNameHelper).map(
                  (key) =>
                    vesselData[0][key] && (
                      <li key={key}>
                        <strong>{fieldsNameHelper[key].name}:</strong>{" "}
                        {vesselData[0][key]}
                      </li>
                    ),
                )}
              </ul>
            </div>
          ) : null}
          {imoChecked &&
            (!vesselData || vesselData.length === 0) &&
            Object.keys(formSchema.shape).map(
              (key, index) =>
                key !== "imo" && (
                  <FormField
                    key={key + index}
                    control={form.control}
                    name={key}
                    render={({ field }) => (
                      <FormItem className={"flex flex-row items-center"}>
                        <FormLabel className={"w-64 text-lg font-light"}>
                          {fieldsNameHelper[key].name}
                        </FormLabel>
                        <div className={"mr-2"}>
                          <TooltipProvider>
                            <Tooltip>
                              <TooltipTrigger className="text-black hover:text-black/50 dark:text-white dark:hover:text-white/50">
                                <Icon name="unknown" style="h-5 w-5" />
                              </TooltipTrigger>
                              <TooltipContent>
                                <p>{fieldsNameHelper[key].description}</p>
                              </TooltipContent>
                            </Tooltip>
                          </TooltipProvider>
                        </div>
                        <FormControl className={"w-full"}>
                          <Input
                            {...field}
                            className={"text-md font-light"}
                            type="text"
                            value={field.value ?? ""}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                ),
            )}
          <div className="flex flex-row justify-end">
            <DestructiveButton type="submit" className="mt-4">
              <ButtonContent>
                {imoChecked ? "Add Vessel" : "Check IMO"}
              </ButtonContent>
            </DestructiveButton>
          </div>
          <Toaster />
        </form>
      </Form>
    </div>
  );
}
import {type NextPage} from "next";
import {Button, HeadingLink, MinimalPage, PageHeading} from "ui";
import {CommandInterface} from "@/components";
import {useRouter} from "next/router";
import {VesselButton} from "@/components/buttons/vesselButton";
import React from "react";

const ManageVessel: NextPage = () => {
  const router = useRouter();
  return (
    <MinimalPage
      pageTitle={"Manage Vessel | Email Interface"}
      pageDescription={"Spot Ship Email Interface | Manage Vessel"}
      commandPrompt
    >
      <CommandInterface/>
      <div className="w-full">
        <HeadingLink icon={"back"} text={"Home"} href={`/secure/home`}/>
      </div>
      <div>
        <PageHeading text="Manage Vessel"/>
      </div>
      <div className="grid w-full grid-flow-row auto-rows-max gap-8 p-8 pt-16 lg:w-2/3 lg:grid-cols-2">
        <Button
          text="Add Vessel"
          icon="plus-circle"
          iconRight
          action={() => {
            router.push("/secure/manager/manageVessel/addVessel");
          }}
          colour="Primary"
        />
        <Button
          text="Add Regular Vessel"
          icon="plus-circle"
          iconRight
          action={() => {
            router.push("/secure/manager/manageVessel/addRegularVessel");
          }}
          colour="Primary"
        />
        <Button
          text="Edit Vessel"
          icon="edit"
          iconRight
          action={() => {
            router.push("/secure/manager/manageVessel/editVessel");
          }}
          colour="Secondary"
        />
      </div>
      <div className="grid w-full grid-flow-row auto-rows-max gap-8 px-8 lg:w-2/3 lg:grid-cols-2">
        <VesselButton/>
      </div>
    </MinimalPage>
  );
};

export default ManageVessel;
import { NextPage } from "next";
import {
  BackHomeButton,
  CommandPalletteButton,
  MinimalPage,
  PageHeading,
} from "ui";
import { VesselInfoForm } from "@/components/forms/vesselInfoForm";
import { BugReportButton, CommandInterface, Navigation } from "@/components";

const RegularVessel: NextPage = () => {
  return (
    <MinimalPage
      pageTitle={"Regular Vessel Info | Vessel Interface"}
      pageDescription={"Vessel Interface | Regular Vessel Info"}
      commandPrompt
    >
      <div className="flex w-full flex-row justify-between pl-1 pt-1">
        <div>
          <BackHomeButton />
        </div>
        <Navigation />
        <div className="flex flex-row gap-4">
          <BugReportButton />
          <CommandPalletteButton />
          <CommandInterface />
        </div>
      </div>
      <PageHeading text="Regular Vessel Info" />
      <VesselInfoForm />
    </MinimalPage>
  );
};

export default RegularVessel;
var jwt = require('jsonwebtoken');

function auth(req, res, next) {
    // Extract the token from the Authorization header
    const authHeader = req.headers.authorization;

    if (!authHeader) {
        return res.status(401).send('Authorization header is missing');
    }

    // Ensure the token is a Bearer token
    const tokenParts = authHeader.split(' ');

    if (tokenParts.length !== 2 || tokenParts[0] !== 'Bearer') {
        return res.status(401).send('Invalid Authorization header format');
    }

    const token = tokenParts[1];

    // Verify the token
    jwt.verify(token, 'sid', function(err, decoded) {
        if (err) {
            return res.status(401).send('Failed to authenticate token');
        } else {
            // Optionally, you can attach the decoded information to the request object
            req.user = decoded;
            next();
        }
    });
}

module.exports = auth;
devtools::install_github("bioFAM/MOFA2", build_opts = c("--no-resave-data --no-build-vignettes"))
{
    "email": "harsh14@gmail.com",
    "password": "StrongPassword123!"
}
Int ledpin=2;
Void setup(){
	pinMode(ledpin,OUTPUT);
Serial.begin(9600);
}
Void loop(){
	digitalWrite(ledpin,HIGH);
	delay(1000);
	digitalWrite(ledpin,LOW);
	delay(1000);
}
#include “DHT.h”
DHT dht 2(2,DHT11);
Void setup(){
Serial.begin(9600);
}
Void loop(){
Serial.print(F(“Humidity in c: “));
Serial.print(dht.readHumidity());
Serial.print(F(“% temperature : “));
Serial.print(dht2.readTemperature());
Delay(1000);
}
int trig=D6
int echo=D5
float duration,dist_cm,dist_in
void setup(){
	pinMode(trig,OUTPUT)
	pinMode(echo,INPUT)
	Serial.begin(9600)
}
Void loop(){
	digitalWrite(trig,LOW);
	delay Microseconds(2);
	digitalWrite(trig,HIGH);
	delay Microseconds(10);
	digitalWrite(trig,LOW);
	duration=pulseIn(echo,HIGH);
	dist_cm=duration*0.0343/2.0;
	dist_in=duration*0.0135/2.0;
	Serial.print(“Distance”);
	Serial.print(dist_cm,1);
	Serial.print(“cm/ ”);
	Serial.print(dist_in,1);
	delay(300);
}
Void setup(){
	pinMode(LED_BUILTIN,OUTPUT);
}
Void loop(){
	digitalWrite(LED_BUILTIN,HIGH);
	delay(1000);
	digitalWrite(LED_BUILTIN,LOW);
	delay(1000);
}
#include <DHT.h>

#define DHTPIN 2
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("Dht test!!");
}

void loop() {
  delay(2000);
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);

  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print("% Temperature: ");
  Serial.print(t);
  Serial.print("C ");
  Serial.println(f);
}
int trig=12
int echo=11
float duration,dist_cm,dist_in
void setup(){
	pinMode(trig,OUTPUT)
	pinMode(echo,INPUT)
	Serial.begin(9600)
}
Void loop(){
	digitalWrite(trig,LOW);
	delay Microseconds(2);
	digitalWrite(trig,HIGH);
	delay Microseconds(10);
	digitalWrite(trig,LOW);
	duration=pulseIn(echo,HIGH);
	dist_cm=duration*0.0343/2.0;
	dist_in=duration*0.0135/2.0;
	Serial.print(“Distance”);
	Serial.print(dist_cm,1);
	Serial.print(“cm/ ”);
	Serial.print(dist_in,1);
	delay(300);
}
From gpiozero import LED
From time import sleep
Led=LED(17)
While True:
	Led.on()
	Sleep(1)
	Led.off
	Sleep(1)
Standard program:
import RPi.GPIO as GPIO
from time import sleep
 GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
 
led_pin = 17
Blink_count=3
Count=0
While(Count<Blink_count):
	GPIO.output(led_pin,true)
	Print(“led on!!”)
	Sleep(3)
	Count+=1
	GPIO.output(led_pin,false)
	Print(“led off!!”)
	Sleep(1)
	Count+=1
Finally:  GPIO.cleanup()
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO_TRIG = 11
GPIO_ECHO = 18
GPIO.setup(GPIO_TRIG, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)

GPIO.output(GPIO_TRIG, GPIO.LOW)
time.sleep(2)

GPIO.output(GPIO_TRIG, GPIO.HIGH)
time.sleep(0.00001)
GPIO.output(GPIO_TRIG, GPIO.LOW)

while GPIO.input(GPIO_ECHO) == 0:
    start_time = time.time()

while GPIO.input(GPIO_ECHO) == 1:
    bounce_back_time = time.time()

pulse_duration = bounce_back_time - start_time
distance = round(pulse_duration * 17150, 2)
print(f"Distance: {distance}cm")

GPIO.cleanup()
// first parameter is the Accumulator and 2nd is the current value
let result = [1, 2, 3, 4].reduce(function (a, b) {
    //console.log(a, b)
    return a + b;
});

result

// get total of the all items
let products = [
    { name: "Cucumber", type: "vegetable", price: 45.0 },
    { name: "Banana", type: "fruit", price: 20.0 },
    { name: "Carrot", type: "vegetable", price: 20.0 },
    { name: "Apple", type: "fruit", price: 75.0 }
];


let total = products.reduce((total, product) => {
    return total + product.price
}, 0)

total

// create a dictionary of the products by name

let lookup = products.reduce((dictionary, product) => {
    dictionary[product.name] = product; // fixed the syntax error
    return dictionary;
}, {});

console.log(lookup["Banana"].type) // lookup["Banana"].price


let people = [
    { name: "Jane", age: 34 },
    { name: "Mark", age: 20 },
    { name: "Abby", age: 20 },  
]


// group by age

let groupedByAge = people.reduce((dictionary, person) => {
    dictionary[person.age] = dictionary[person.age] || []; // fixed the syntax error
    dictionary[person.age].push(person);
    return dictionary;
}, {});


groupedByAge


// Extra parameters

let test = [1, 2, 3, 4].reduce(function (accumulator, item, index, array) {
    console.log(index)
    console.log(array)
    return accumulator + item;
}, 0);
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  height: 100vh;
  display: grid;
  place-items: center;
  overflow: hidden;
}

main {
  position: relative;
  width: 100%;
  height: 100%;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.3);
}

.item {
  width: 200px;
  height: 300px;
  list-style-type: none;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  z-index: 1;
  background-position: center;
  background-size: cover;
  border-radius: 20px;
  box-shadow: 0 20px 30px rgba(255, 255, 255, 0.3) inset;
  transition: transform 0.1s, left 0.75s, top 0.75s, width 0.75s, height 0.75s;

  &:nth-child(1),
  &:nth-child(2) {
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    transform: none;
    border-radius: 0;
    box-shadow: none;
    opacity: 1;
  }

  &:nth-child(3) {
    left: 50%;
  }
  &:nth-child(4) {
    left: calc(50% + 220px);
  }
  &:nth-child(5) {
    left: calc(50% + 440px);
  }
  &:nth-child(6) {
    left: calc(50% + 660px);
    opacity: 0;
  }
}

.content {
  width: min(30vw, 400px);
  position: absolute;
  top: 50%;
  left: 3rem;
  transform: translateY(-50%);
  font: 400 0.85rem helvetica, sans-serif;
  color: white;
  text-shadow: 0 3px 8px rgba(0, 0, 0, 0.5);
  opacity: 0;
  display: none;

  & .title {
    font-family: "arial-black";
    text-transform: uppercase;
  }

  & .description {
    line-height: 1.7;
    margin: 1rem 0 1.5rem;
    font-size: 0.8rem;
  }

  & button {
    width: fit-content;
    background-color: rgba(0, 0, 0, 0.1);
    color: white;
    border: 2px solid white;
    border-radius: 0.25rem;
    padding: 0.75rem;
    cursor: pointer;
  }
}

.item:nth-of-type(2) .content {
  display: block;
  animation: show 0.75s ease-in-out 0.3s forwards;
}

@keyframes show {
  0% {
    filter: blur(5px);
    transform: translateY(calc(-50% + 75px));
  }
  100% {
    opacity: 1;
    filter: blur(0);
  }
}

.nav {
  position: absolute;
  bottom: 2rem;
  left: 50%;
  transform: translateX(-50%);
  z-index: 5;
  user-select: none;

  & .btn {
    background-color: rgba(255, 255, 255, 0.5);
    color: rgba(0, 0, 0, 0.7);
    border: 2px solid rgba(0, 0, 0, 0.6);
    margin: 0 0.25rem;
    padding: 0.75rem;
    border-radius: 50%;
    cursor: pointer;

    &:hover {
      background-color: rgba(255, 255, 255, 0.3);
    }
  }
}

@media (width > 650px) and (width < 900px) {
  .content {
    & .title {
      font-size: 1rem;
    }
    & .description {
      font-size: 0.7rem;
    }
    & button {
      font-size: 0.7rem;
    }
  }
  .item {
    width: 160px;
    height: 270px;

    &:nth-child(3) {
      left: 50%;
    }
    &:nth-child(4) {
      left: calc(50% + 170px);
    }
    &:nth-child(5) {
      left: calc(50% + 340px);
    }
    &:nth-child(6) {
      left: calc(50% + 510px);
      opacity: 0;
    }
  }
}

@media (width < 650px) {
  .content {
    & .title {
      font-size: 0.9rem;
    }
    & .description {
      font-size: 0.65rem;
    }
    & button {
      font-size: 0.7rem;
    }
  }
  .item {
    width: 130px;
    height: 220px;

    &:nth-child(3) {
      left: 50%;
    }
    &:nth-child(4) {
      left: calc(50% + 140px);
    }
    &:nth-child(5) {
      left: calc(50% + 280px);
    }
    &:nth-child(6) {
      left: calc(50% + 420px);
      opacity: 0;
    }
  }
}
ol.custom-ordered-list{
       counter-reset: list-counter; /* Initialize the counter */
        list-style: none; /* Remove default list styling */
        padding-left: 0; /* Remove default padding */       
    li{
            counter-increment: list-counter; /* Increment the counter */
            position: relative; /* Positioning for the pseudo-element */
            padding-left: 60px; /* Space for the counter */
            padding-bottom: 12px;
            line-height: 30px;
            left: 0;
        
        &:before{
            content: counter(list-counter, decimal-leading-zero) ""; /* Display the counter with leading zeros */
            position: absolute; /* Position it absolutely within the list item */
            left: 0; /* Align it to the left */
            width: 2em; /* Width for the counter */
            text-align: right; /* Align text to the right */
            font-size: 24px;
            font-weight: bold;
            color: #2E844B;
        }
    }
}
 ListNode *hasCycle(ListNode *head) {
        ListNode *slow=head;
        ListNode *fast=head;
      while(fast!=NULL && fast->next!=NULL)
      {
        slow=slow->next;
        fast=fast->next->next;
        if(fast==slow)
        return slow;
      }
     return NULL;
    }
    ListNode *detectCycle(ListNode *head) {
         ListNode *t1=hasCycle(head);
         if(t1==NULL)return NULL;
        ListNode *t=head;
       

        while(t!=t1)
        {
            t=t->next;
            t1=t1->next;
        }
        return t;
        
    }
import tensorflow as tf
mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
  loss='sparse_categorical_crossentropy',
  metrics=['accuracy'])

model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test)
bool hasCycle(ListNode *head) {
        ListNode *slow=head;
        ListNode *fast=head;
      while(fast!=NULL && fast->next!=NULL)
      {
        slow=slow->next;
        fast=fast->next->next;
        if(fast==slow)
        return true;
      }
      return false;
    }
 bool hasCycle(ListNode *head) {
        ListNode* temp = head;
        unordered_map<ListNode*,int> m;
         while(temp != NULL) {
            m[temp]++;
            if(m[temp] == 2) {
                return true;
            }
            temp = temp->next;
        }

        return false;
    }
from pymongo import MongoClient

# Configure MongoDB connection
client = MongoClient('mongodb://localhost:27017/')
db = client['twitter_database']
collection = db['tweets']

# Find the last tweet in the collection
last_tweet = collection.find_one({}, sort=[('$natural', -1)])


# Print the last tweet
print(last_tweet)
from pymongo import MongoClient

mongo_uri = "mongodb://localhost:27017/"
database_name = "twitter_database"

source_collection_name = "tweets"
target_collection_name = "tweet_data"

fields_to_extract = [
    "json_data.id",
    "json_data.user.id",
    "json_data.created_at",
    "json_data.in_reply_to_status_id",
    "json_data.in_reply_to_user_id",
    "json_data.lang",
    "json_data.place",
    "json_data.user.location",
    "json_data.is_quote_status"
]

# not sure why but it works :)
def get_nested_field(data, field_path):
    keys = field_path.split('.')
    for key in keys:
        data = data.get(key)
        if data is None:
            return None
    return data
client = MongoClient(mongo_uri)
db = client[database_name]
source_collection = db[source_collection_name]
target_collection = db[target_collection_name]

cursor = source_collection.find()
for doc in cursor:
    lang = get_nested_field(doc, "json_data.lang")
    
    # Check if lang
    if lang in ["en", "nl", "es"]:
        # Create a new document with only the specified fields
        new_doc = {field: get_nested_field(doc, field) for field in fields_to_extract}
        new_doc["_id"] = doc["_id"]  # Keep the original _id
                target_collection.insert_one(new_doc)

client.close()
print("Data successfully transferred to new collections.")
from pymongo import MongoClient

# MongoDB connection details
mongo_uri = "mongodb://localhost:27017/"
database_name = "twitter_database"

# Source and target collections
source_collection_name = "tweets"
target_collection_name = "tweet_data"

# columns to get
fields_to_extract = [
    "json_data.id",
    "json_data.user.id",
    "json_data.created_at",
    "json_data.in_reply_to_status_id",
    "json_data.in_reply_to_user_id",
    "json_data.lang",
    "json_data.place",
    "json_data.user.location",
    "json_data.is_quote_status"
]

# for the nested thing-didnt really get it but it works :)
def get_nested_field(data, field_path):
    keys = field_path.split('.')
    for key in keys:
        data = data.get(key)
        if data is None:
            return None
    return data

# Connect to MongoDB
client = MongoClient(mongo_uri)
db = client[database_name]
source_collection = db[source_collection_name]
target_collection = db[target_collection_name]

# Loop through each document in the source collection
cursor = source_collection.find()
for doc in cursor:
    # Create a new document with only the specified fields
    new_doc = {field: get_nested_field(doc, field) for field in fields_to_extract}
    new_doc["_id"] = doc["_id"]  # Keep the original _id
    
    # Insert the new document into the target collection
    target_collection.insert_one(new_doc)

client.close()
print("Data successfully transferred to new collections.")
# ignore all .a files
*.a

# but do track lib.a, even though you're ignoring .a files above
!lib.a

# only ignore the TODO file in the current directory, not subdir/TODO
/TODO

# ignore all files in any directory named build
build/

# ignore doc/notes.txt, but not doc/server/arch.txt
doc/*.txt

# ignore all .pdf files in the doc/ directory and any of its subdirectories
doc/**/*.pdf
#include "DHT.h"

#define DHTPIN 2  // GPIO Pin D4  

#define DHTTYPE DHT11

// DHT Class dht Object with parameters - assigned Pin and DHt Type

DHT dht(DHTPIN, DHTTYPE);

void setup() {

  // Begin - start communicating with monitor - with Baud rate 9600 serial commn

  Serial.begin(9600);

  // Display test message 

  Serial.println(F("DHTxx test!"));

  dht.begin();

}

void loop() {

  

// 2000 ms - 2 Sec gap for display 

  delay(2000);

  // Read humidity and put in h

  float h = dht.readHumidity();

    // read temperature and put in t in clecius , if nothing in brackets default -False indicating Celcius

  float t = dht.readTemperature();

  // Read temperature as Fahrenheit (isFahrenheit = true)

  //read temperature and put in f in clecius , if true in brackets default -False is overwritten  indicating farenheit

  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).

  if (isnan(h) || isnan(t) || isnan(f)) {

    Serial.println(F("Failed to read from DHT sensor!"));

    return;

  }

  Serial.print(F("Humidity: "));

  Serial.print(h);

  Serial.print(F("%  Temperature: "));

  Serial.print(t);

  Serial.print(F("°C "));

  Serial.print(f);

  Serial.print(F("°F "));

  Serial.println(" ");

}

int Led Pin =2;    // D4 Pin also refereed as pin no2 in Node MCU 

void setup() 

{   

    pinMode(LedPin, OUTPUT);

    Serial.begin(9600);   

}

void loop() {

digitalWrite(LedPin, HIGH); 

delay(1000); 

digitalWrite(LedPin, LOW); 

delay(1000);              

}

int trig=12;     // GPIO Pin D6

int echo=14;     //GPIO Pin D5

int time_microsec;

int time_ms;

int dist_cm;

void setup() {

  // put your setup code here, to run once:

  Serial.begin(9600);

  pinMode(12,OUTPUT);

  pinMode(14,INPUT);

}

void loop() {

  // put your main code here, to run repeatedly:

digitalWrite(trig,LOW);

delayMicroseconds(2);

digitalWrite(trig,HIGH);

delayMicroseconds(10);

digitalWrite(trig,LOW);

//pulseIn gives time in micro seconds, 1Sec= 1000000 microseconds

time_microsec= pulseIn(echo,HIGH);

time_ms=time_microsec/1000;

dist_cm= (34*time_ms)/2;

Serial.print("Time to travel: ");

Serial.println(time_ms,1);

Serial.print("ms / ");

Serial.print("Distance: ");

Serial.print(dist_cm,1);

Serial.print("cm ");

delay(2000);

DIAGRAM
star

Wed May 29 2024 12:18:34 GMT+0000 (Coordinated Universal Time) https://www.prplbx.com/resources/blog/aws-sdk-python-boto3-cheat-sheet/

@krishna01

star

Wed May 29 2024 10:18:09 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 10:00:58 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 09:59:37 GMT+0000 (Coordinated Universal Time)

@krishna01 ##read_s3 ##read_s3_pdf ##read_s3_files

star

Wed May 29 2024 09:53:52 GMT+0000 (Coordinated Universal Time)

@krishna01 ##read_s3 ##read_files_from_s3_json ##read_ocr_from_s3

star

Wed May 29 2024 09:51:14 GMT+0000 (Coordinated Universal Time) https://codepen.io/radeguzvic/pen/bGZorja

@radeguzvic #undefined

star

Wed May 29 2024 09:51:05 GMT+0000 (Coordinated Universal Time) https://codepen.io/radeguzvic/pen/bGZorja

@radeguzvic #undefined

star

Wed May 29 2024 09:51:00 GMT+0000 (Coordinated Universal Time) https://codepen.io/radeguzvic/pen/bGZorja

@radeguzvic #undefined

star

Wed May 29 2024 09:41:52 GMT+0000 (Coordinated Universal Time)

@exam123

star

Wed May 29 2024 09:39:15 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 09:34:54 GMT+0000 (Coordinated Universal Time)

@exam123

star

Wed May 29 2024 09:30:08 GMT+0000 (Coordinated Universal Time)

@exam123

star

Wed May 29 2024 09:26:42 GMT+0000 (Coordinated Universal Time)

@exam123

star

Wed May 29 2024 09:21:13 GMT+0000 (Coordinated Universal Time)

@exam123

star

Wed May 29 2024 09:16:38 GMT+0000 (Coordinated Universal Time)

@exam123

star

Wed May 29 2024 09:16:02 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 09:14:55 GMT+0000 (Coordinated Universal Time)

@exam123

star

Wed May 29 2024 09:02:58 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed May 29 2024 09:02:16 GMT+0000 (Coordinated Universal Time)

@huyrtb123 #c++

star

Wed May 29 2024 08:50:22 GMT+0000 (Coordinated Universal Time)

@Manoj1207

star

Wed May 29 2024 08:39:38 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Wed May 29 2024 08:33:30 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Wed May 29 2024 08:33:08 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Wed May 29 2024 07:45:07 GMT+0000 (Coordinated Universal Time)

@sid_balar

star

Wed May 29 2024 06:19:30 GMT+0000 (Coordinated Universal Time) https://biofam.github.io/MOFA2/installation.html

@kris96tian

star

Wed May 29 2024 06:15:34 GMT+0000 (Coordinated Universal Time)

@deepakm__

star

Wed May 29 2024 01:21:26 GMT+0000 (Coordinated Universal Time)

@login

star

Wed May 29 2024 01:21:03 GMT+0000 (Coordinated Universal Time)

@login

star

Wed May 29 2024 01:20:42 GMT+0000 (Coordinated Universal Time)

@login

star

Wed May 29 2024 01:20:20 GMT+0000 (Coordinated Universal Time)

@login

star

Wed May 29 2024 01:20:03 GMT+0000 (Coordinated Universal Time)

@login

star

Wed May 29 2024 01:19:41 GMT+0000 (Coordinated Universal Time)

@login

star

Wed May 29 2024 01:19:07 GMT+0000 (Coordinated Universal Time)

@login

star

Wed May 29 2024 01:16:37 GMT+0000 (Coordinated Universal Time)

@login

star

Wed May 29 2024 01:09:41 GMT+0000 (Coordinated Universal Time)

@RahmanM

star

Wed May 29 2024 00:02:10 GMT+0000 (Coordinated Universal Time) https://salak-bouw.nl/wp-admin/themes.php?page

@radeguzvic #undefined

star

Tue May 28 2024 23:21:01 GMT+0000 (Coordinated Universal Time)

@davidmchale #counter #css

star

Tue May 28 2024 22:54:02 GMT+0000 (Coordinated Universal Time)

@ayushg103 #c++

star

Tue May 28 2024 22:32:51 GMT+0000 (Coordinated Universal Time) https://www.tensorflow.org/

@calazar23

star

Tue May 28 2024 22:21:18 GMT+0000 (Coordinated Universal Time)

@ayushg103 #c++

star

Tue May 28 2024 21:55:39 GMT+0000 (Coordinated Universal Time)

@ayushg103 #c++

star

Tue May 28 2024 21:39:14 GMT+0000 (Coordinated Universal Time)

@madgakantara

star

Tue May 28 2024 21:37:36 GMT+0000 (Coordinated Universal Time)

@madgakantara

star

Tue May 28 2024 21:33:09 GMT+0000 (Coordinated Universal Time)

@madgakantara

star

Tue May 28 2024 21:24:40 GMT+0000 (Coordinated Universal Time) https://git-scm.com/book/en/v2/Git-Basics-Recording-Changes-to-the-Repository#_ignoring

@calazar23

star

Tue May 28 2024 21:22:28 GMT+0000 (Coordinated Universal Time) https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files

@calazar23

star

Tue May 28 2024 21:14:04 GMT+0000 (Coordinated Universal Time) https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files

@calazar23

star

Tue May 28 2024 17:14:11 GMT+0000 (Coordinated Universal Time)

@user21

star

Tue May 28 2024 17:12:57 GMT+0000 (Coordinated Universal Time)

@user21

star

Tue May 28 2024 17:11:44 GMT+0000 (Coordinated Universal Time)

@user21

Save snippets that work with our extensions

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