Snippets Collections
# UI support
pip install "praisonai[ui]"

# Chat interface
pip install "praisonai[chat]"

# Code interface
pip install "praisonai[code]"

# Realtime voice interaction
pip install "praisonai[realtime]"

# Call feature
pip install "praisonai[call]"
pip install "praisonai[crewai,autogen]"
//activity_main.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"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/bt1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="click here"
        android:textSize="25dp"
        android:textColor="@color/design_default_color_primary"
        />


</LinearLayout>
//MainActivity.kt


import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val b1:Button = findViewById(R.id.bt1)

        b1.setOnClickListener {
            val intent = Intent(this, DetailsActivity::class.java)

            Toast.makeText(this, "Hello Details Activity", Toast.LENGTH_SHORT).show()
            startActivity(intent)
        }
    }
}
//DetailsActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class DetailsActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_details)
    }
}

//activity_details.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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DetailsActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome to second activity"
        android:textSize="35dp"
        android:textColor="@color/black"
        />

</LinearLayout>

//In the manifest.xml file below the <activity/> insert the code
<activity android:name=".DetailsActivity"></activity>
//activity_main.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"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/bt1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="click here"
        android:textSize="25dp"
        android:textColor="@color/design_default_color_primary"
        />


</LinearLayout>
//MainActivity.kt


import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val b1:Button = findViewById(R.id.bt1)

        b1.setOnClickListener {
            val intent = Intent(this, DetailsActivity::class.java)

            Toast.makeText(this, "Hello Details Activity", Toast.LENGTH_SHORT).show()
            startActivity(intent)
        }
    }
}
//DetailsActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class DetailsActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_details)
    }
}

//activity_details.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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DetailsActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome to second activity"
        android:textSize="35dp"
        android:textColor="@color/black"
        />

</LinearLayout>

//In the manifest.xml file below the <activity/> insert the code
<activity android:name=".DetailsActivity"></activity>
//Explicit Intent

MainActivity.kt

package com.example.intent

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val b1:Button = findViewById(R.id.bt1)

        b1.setOnClickListener {
            val intent = Intent(this, DetailsActivity::class.java)

            Toast.makeText(this, "Hello Details Activity", Toast.LENGTH_SHORT).show()
            startActivity(intent)
        }
    }
}

activity_main.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"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/bt1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="click here"
        android:textSize="25dp"
        android:textColor="@color/teal_200"
        />


</LinearLayout>

DetailsActivity.kt

package com.example.intent

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class DetailsActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_details)
    }
}

activity_deatils.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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DetailsActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome to second activity"
        android:textSize="35dp"
        android:textColor="@color/purple_700"
        />

</LinearLayout>


/*
Add this line below </activity> in AndroidManifest.xml

<activity android:name=".DetailsActivity"></activity>

*/
package com.example.external

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp
import com.example.external.ui.theme.ExternalTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            Surface(modifier=Modifier.fillMaxSize(),color = Color.White) {
                Box(contentAlignment = Alignment.Center,modifier = Modifier.fillMaxSize()){
                    Text(text = "HelloWorld", color = Color.Red, fontSize = 32.sp)
                }
            }
        }
    }
}

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello $name!",
        modifier = modifier
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    ExternalTheme {
        Greeting("World")
    }
}
hello world
package com.example.tipcalculatorkt

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.unit.times
import com.example.tipcalculatorkt.ui.theme.TipCalculatorktTheme
import kotlin.time.times

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            TipCalculatorktTheme {
               calc()
            }
        }
    }
}
@Composable
fun calc(){
    var totalbill by remember{
        mutableStateOf("0")
    }
    var tipp by remember {
        mutableStateOf("0")
    }
    var ans by remember {
        mutableStateOf("0.0")
    }
    Column (modifier = Modifier.fillMaxSize().padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center){
        TextField(value = totalbill, onValueChange = {totalbill =it},
            label = {Text(text = "Enter the total bill amount")})
        TextField(value = tipp, onValueChange = {tipp =it},
            label = {Text(text = "Enter the tip percentage")})
        Spacer(modifier = Modifier.height(16.dp))
        Button(onClick = {var bill = totalbill.toDouble()
                            var tip = tipp.toDouble()
                            ans = (bill*(tip/100)).toString()
               }){
            Text(text="Calculate the tip")
        }
        if(ans=="0.0"){
            Text(text="Tip amount is $ans", fontSize = 30.sp)
        }
        else{
            Text(text = "Tip amount is $ans",fontSize = 20.sp)
        }
    }
}
//.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scientific Calculator</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="calculator">
        <input type="text" id="display" disabled>
        <div class="buttons">
            <button onclick="clearDisplay()">C</button>
            <button onclick="appendToDisplay('7')">7</button>
            <button onclick="appendToDisplay('8')">8</button>
            <button onclick="appendToDisplay('9')">9</button>
            <button onclick="appendToDisplay('/')">/</button>
            <button onclick="appendToDisplay('4')">4</button>
            <button onclick="appendToDisplay('5')">5</button>
            <button onclick="appendToDisplay('6')">6</button>
            <button onclick="appendToDisplay('')"></button>
            <button onclick="appendToDisplay('1')">1</button>
            <button onclick="appendToDisplay('2')">2</button>
            <button onclick="appendToDisplay('3')">3</button>
            <button onclick="appendToDisplay('-')">-</button>
            <button onclick="appendToDisplay('0')">0</button>
            <button onclick="appendToDisplay('.')">.</button>
            <button onclick="calculateResult()">=</button>
            <button onclick="appendToDisplay('+')">+</button>
            <button onclick="appendToDisplay('Math.sqrt(')">√</button>
            <button onclick="appendToDisplay('Math.pow(')">x²</button>
            <button onclick="appendToDisplay('Math.sin(')">sin</button>
            <button onclick="appendToDisplay('Math.cos(')">cos</button>
            <button onclick="appendToDisplay('Math.tan(')">tan</button>
            <button onclick="appendToDisplay('Math.PI')">π</button>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>


//.css
body {
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
}

.calculator {
    background: white;
    border-radius: 10px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    padding: 20px;
    width: 300px;
}

#display {
    width: 100%;
    height: 40px;
    font-size: 24px;
    margin-bottom: 10px;
    text-align: right;
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

.buttons {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 10px;
}

button {
    padding: 15px;
    font-size: 18px;
    border: none;
    border-radius: 5px;
    background-color: #007bff;
    color: white;
    cursor: pointer;
    transition: background-color 0.3s;
}

button:hover {
    background-color: #0056b3;
}


//.js
function appendToDisplay(value) {
    const display = document.getElementById('display');
    display.value += value;
}

function clearDisplay() {
    const display = document.getElementById('display');
    display.value = '';
}

function calculateResult() {
    const display = document.getElementById('display');
    try {
        display.value = eval(display.value);
    } catch (e) {
        display.value = 'Error';
    }
}
//,html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Grid & Flexbox Example</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <header>
        <h1>My Web Page</h1>
    </header>
    <main>
        <section class="grid-container">
            <div class="grid-item">Item 1</div>
            <div class="grid-item">Item 2</div>
            <div class="grid-item">Item 3</div>
            <div class="grid-item">Item 4</div>
            <div class="grid-item">Item 5</div>
            <div class="grid-item">Item 6</div>
        </section>
        <section class="flex-container">
            <div class="flex-item">Flex Item 1</div>
            <div class="flex-item">Flex Item 2</div>
            <div class="flex-item">Flex Item 3</div>
        </section>
    </main>
    <footer>
        <p>© 2024 My Web Page</p>
    </footer>
</body>
</html>
 
 
 
 
 
 
//.cc
* {
    box-sizing: border-box;
}
 
body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    background-color: #f0f0f0;
}
 
header {
    background: #4CAF50;
    color: white;
    padding: 20px;
    text-align: center;
}
 
main {
    padding: 20px;
}
 
.grid-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 15px;
}
 
.grid-item {
    background: #ffeb3b;
    padding: 20px;
    text-align: center;
    transition: transform 0.3s ease, background-color 0.3s ease;
}
 
.grid-item:hover {
    transform: scale(1.05);
    background-color: #ffc107;
}
 
.flex-container {
    display: flex;
    justify-content: space-around;
    margin-top: 20px;
}
 
.flex-item {
    background: #2196F3;
    color: white;
    padding: 20px;
    transition: transform 0.3s ease, opacity 0.3s ease;
    opacity: 0.8;
}
 
.flex-item:hover {
    transform: translateY(-5px);
    opacity: 1;
}
 
footer {
    background: #4CAF50;
    color: white;
    text-align: center;
    padding: 10px;
    position: relative;
    bottom: 0;
    width: 100%;
}
MainActivity.kt

package com.example.intent

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)

        val button : Button = findViewById(R.id.button)
        button.setOnClickListener {
            val intent = Intent(this, DetailsActivity::class.java)
//            intent.putExtra("message", "hello details activity")
            Toast.makeText(this, "hello details activity", Toast.LENGTH_LONG).show()
            startActivity(intent)
        }
    }
}



DetailsActivity.kt

package com.example.intent

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class DetailsActivity: AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_details)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.details)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }
}



activity_main.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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Go to 2nd activity"
        android:textSize="35sp"
        android:textColor="@color/design_default_color_error"
        />
</LinearLayout>


activit_details.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/details"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DetailsActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Display Message here"
        android:textSize="35sp"
        android:textColor="@color/black"
        />

</LinearLayout>
HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Registration</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>Register</h1>
    <form id="registrationForm">
        <input type="text" id="username" placeholder="Username" required>
        <input type="email" id="email" placeholder="Email" required>
        <input type="password" id="password" placeholder="Password" required>
        <button type="submit">Register</button>
        <div id="message" class="error-message"></div>
    </form>
    <script src="script.js"></script>
</body>
</html>

script.js
document.getElementById("registrationForm").addEventListener("submit", function(event) {
    event.preventDefault(); // Prevent form submission
    validateRegistration();
});

function validateRegistration() {
    const username = document.getElementById("username").value;
    const email = document.getElementById("email").value;
    const password = document.getElementById("password").value;
    const messageDiv = document.getElementById("message");
    messageDiv.textContent = "";

    // Simple validation
    if (username.length < 3) {
        messageDiv.textContent = "Username must be at least 3 characters.";
        return;
    }
    if (!/\S+@\S+\.\S+/.test(email)) {
        messageDiv.textContent = "Email is not valid.";
        return;
    }
    if (password.length < 6) {
        messageDiv.textContent = "Password must be at least 6 characters.";
        return;
    }

    messageDiv.textContent = "Registration successful!";
    // You can proceed to send the data to the server here
}

User Login Page(HTML)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>Login</h1>
    <form id="loginForm">
        <input type="email" id="loginEmail" placeholder="Email" required>
        <input type="password" id="loginPassword" placeholder="Password" required>
        <button type="submit">Login</button>
        <div id="loginMessage" class="error-message"></div>
    </form>
    <script src="script.js"></script>
</body>
</html>
script.js
document.getElementById("loginForm").addEventListener("submit", function(event) {
    event.preventDefault(); // Prevent form submission
    validateLogin();
});

function validateLogin() {
    const email = document.getElementById("loginEmail").value;
    const password = document.getElementById("loginPassword").value;
    const loginMessageDiv = document.getElementById("loginMessage");
    loginMessageDiv.textContent = "";

    // Simple validation
    if (!/\S+@\S+\.\S+/.test(email)) {
        loginMessageDiv.textContent = "Email is not valid.";
        return;
    }
    if (password.length < 6) {
        loginMessageDiv.textContent = "Password must be at least 6 characters.";
        return;
    }

    loginMessageDiv.textContent = "Login successful!";
    // You can proceed to authenticate the user here
}

 User Profile Page(HTML)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Profile</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>User Profile</h1>
    <form id="profileForm">
        <input type="text" id="profileUsername" placeholder="Username" required>
        <input type="email" id="profileEmail" placeholder="Email" required>
        <button type="submit">Update Profile</button>
        <div id="profileMessage" class="error-message"></div>
    </form>
    <script src="script.js"></script>
</body>
</html>

script.js
document.getElementById("profileForm").addEventListener("submit", function(event) {
    event.preventDefault(); // Prevent form submission
    validateProfile();
});

function validateProfile() {
    const username = document.getElementById("profileUsername").value;
    const email = document.getElementById("profileEmail").value;
    const profileMessageDiv = document.getElementById("profileMessage");
    profileMessageDiv.textContent = "";

    // Simple validation
    if (username.length < 3) {
        profileMessageDiv.textContent = "Username must be at least 3 characters.";
        return;
    }
    if (!/\S+@\S+\.\S+/.test(email)) {
        profileMessageDiv.textContent = "Email is not valid.";
        return;
    }

    profileMessageDiv.textContent = "Profile updated successfully!";
    // You can proceed to update the user profile on the server here
}
Payment page(HTML)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>Payment</h1>
    <form id="paymentForm">
        <input type="text" id="cardNumber" placeholder="Card Number" required>
        <input type="text" id="expiryDate" placeholder="MM/YY" required>
        <input type="text" id="cvv" placeholder="CVV" required>
        <button type="submit">Pay</button>
        <div id="paymentMessage" class="error-message"></div>
    </form>
    <script src="script.js"></script>
</body>
</html>

script.js
document.getElementById("paymentForm").addEventListener("submit", function(event) {
    event.preventDefault(); // Prevent form submission
    validatePayment();
});

function validatePayment() {
    const cardNumber = document.getElementById("cardNumber").value;
    const expiryDate = document.getElementById("expiryDate").value;
    const cvv = document.getElementById("cvv").value;
    const paymentMessageDiv = document.getElementById("paymentMessage");
    paymentMessageDiv.textContent = "";

    // Simple validation
    if (!/^\d{16}$/.test(cardNumber)) {
        paymentMessageDiv.textContent = "Card number must be 16 digits.";
        return;
    }
    if (!/^(0[1-9]|1[0-2])\/\d{2}$/.test(expiryDate)) {
        paymentMessageDiv.textContent = "Expiry date must be in MM/YY format.";
        return;
    }
    if (!/^\d{3}$/.test(cvv)) {
        paymentMessageDiv.textContent = "CVV must be 3 digits.";
        return;
    }

    paymentMessageDiv.textContent = "Payment successful!";
    // You can proceed to process the payment here
}
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
 
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            val database = UserDatabase.getInstance(this)
            insertRecord(database)
        }
    }
}
 
@Composable
fun insertRecord(database: UserDatabase) {
    val context = LocalContext.current
    val userDao = database.userDao()
    var name by remember { mutableStateOf("") }
    var phone by remember { mutableStateOf("") }
    val scope = rememberCoroutineScope()
 
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp)
    ) {
        Text(text = "Enter your details here")
        Spacer(modifier = Modifier.height(16.dp))
        OutlinedTextField(
            value = name,
            onValueChange = { name = it },
            label = { Text(text = "Enter your name") },
            modifier = Modifier.fillMaxWidth()
        )
        Spacer(modifier = Modifier.height(8.dp))
        OutlinedTextField(
            value = phone,
            onValueChange = { phone = it },
            label = { Text(text = "Enter your phone number") },
            modifier = Modifier.fillMaxWidth()
        )
        Spacer(modifier = Modifier.height(16.dp))
        Button(
            onClick = {
                scope.launch(Dispatchers.IO) {
                    userDao.insert(User(userName = name, userPhone = phone))
                }
                Toast.makeText(context, "Record Inserted successfully", Toast.LENGTH_LONG).show()
            }
        ) {
            Text(text = "Insert Now")
        }
    }
}
//User.kt(create Data Class )
import androidx.room.Entity
import androidx.room.PrimaryKey
 
@Entity(tableName = "user_table")
data class User(
    @PrimaryKey(autoGenerate = true) val id: Int = 0,
    val userName: String,
    val userPhone: String
)
// UserDAO.kt(create interface)
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.*
@Dao
interface UserDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(user: User)
}
//class UserDatabase.kt
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
 
@Database(entities = [User::class], version = 1, exportSchema = false)
abstract class UserDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
 
    companion object {
        @Volatile
        private var INSTANCE: UserDatabase? = null
 
        fun getInstance(context: Context): UserDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    UserDatabase::class.java,
                    "user_database"
                ).build()
                INSTANCE = instance
                instance
            }
        }
    }
}
//dependencies
plugins-kotlin("kapt")
val room_version="2.6.1"
    implementation("androidx.room:room-runtime:$room_version")
    kapt("androidx.room:room-compiler:$room_version") // for annotation processing
    implementation("androidx.room:room-ktx:$room_version")
package com.example.image

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.image.ui.theme.ImageTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {



                    ImageAndText()

            
        }
    }
}





@Composable
fun ImageAndText() {
    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Image(
            painter = painterResource(id = R.drawable.rev),
            contentDescription = "Image description",
            modifier = Modifier.fillMaxWidth().padding(16.dp)
        )
        Spacer(modifier = Modifier.height(16.dp))
        Text(text = "Description about the image", fontSize = 30.sp)
    }
}


//MainActivity.kt

package com.example.lifecycle

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.lifecycle.R

class MainActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main) // Set the content view to the layout file
        Toast.makeText(applicationContext, "ONCREATE() CALLED", Toast.LENGTH_SHORT).show()
    }


    override fun onStart() {
        super.onStart()
        Toast.makeText(applicationContext, "ONSTART() CALLED", Toast.LENGTH_SHORT).show()
    }


    override fun onRestart() {
        super.onRestart()
        Toast.makeText(applicationContext, "ONRESTART() CALLED", Toast.LENGTH_SHORT).show()
    }


    override fun onResume() {
        super.onResume()
        Toast.makeText(applicationContext, "ONRESUME() CALLED", Toast.LENGTH_SHORT).show()
    }


    override fun onStop() {
        super.onStop()
        Toast.makeText(applicationContext, "ONSTOP() CALLED", Toast.LENGTH_SHORT).show()
    }

    override fun onDestroy() {
        super.onDestroy()
        Toast.makeText(applicationContext, "ONDESTROY() CALLED", Toast.LENGTH_SHORT).show()
    }
}


//activity_main.xml

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


    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Demonstration of ACTIVITY LIFE CYCLE Methods"
        android:textSize="18sp"
        android:textColor="@android:color/black"
        android:layout_marginBottom="16dp" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Me" />

</LinearLayout>
//mainactivity.kt
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            val database = UserDatabase.getInstance(this)
            insertRecord(database)
        }
    }
}

@Composable
fun insertRecord(database: UserDatabase) {
    val context = LocalContext.current
    val userDao = database.userDao()
    var name by remember { mutableStateOf("") }
    var phone by remember { mutableStateOf("") }
    val scope = rememberCoroutineScope()

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp)
    ) {
        Text(text = "Enter your details here")
        Spacer(modifier = Modifier.height(16.dp))
        OutlinedTextField(
            value = name,
            onValueChange = { name = it },
            label = { Text(text = "Enter your name") },
            modifier = Modifier.fillMaxWidth()
        )
        Spacer(modifier = Modifier.height(8.dp))
        OutlinedTextField(
            value = phone,
            onValueChange = { phone = it },
            label = { Text(text = "Enter your phone number") },
            modifier = Modifier.fillMaxWidth()
        )
        Spacer(modifier = Modifier.height(16.dp))
        Button(
            onClick = {
                scope.launch(Dispatchers.IO) {
                    userDao.insert(User(userName = name, userPhone = phone))
                }
                Toast.makeText(context, "Record Inserted successfully", Toast.LENGTH_LONG).show()
            }
        ) {
            Text(text = "Insert Now")
        }
    }
}
//User.kt(create Data Class )
import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity(tableName = "user_table")
data class User(
    @PrimaryKey(autoGenerate = true) val id: Int = 0,
    val userName: String,
    val userPhone: String
)
// UserDAO.kt(create interface)
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.*
@Dao
interface UserDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(user: User)
}
//class UserDatabase.kt
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase

@Database(entities = [User::class], version = 1, exportSchema = false)
abstract class UserDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao

    companion object {
        @Volatile
        private var INSTANCE: UserDatabase? = null

        fun getInstance(context: Context): UserDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    UserDatabase::class.java,
                    "user_database"
                ).build()
                INSTANCE = instance
                instance
            }
        }
    }
}
//dependencies
plugins-kotlin("kapt")
val room_version="2.6.1"
    implementation("androidx.room:room-runtime:$room_version")
    kapt("androidx.room:room-compiler:$room_version") // for annotation processing
    implementation("androidx.room:room-ktx:$room_version")
//Empty Activity
 
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp
import com.example.myapplication.ui.theme.MyApplicationTheme
 
 
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            Surface(modifier = Modifier.fillMaxSize(),
                color = Color.White
 
            ) {
                Box(
                    contentAlignment = Alignment.Center,
                    modifier = Modifier.fillMaxSize()
                ){
                    Text(text = "Hello World",
                        color = Color.Red,
                        fontSize = 32.sp
                    )
 
                }
 
            }
        }
 
    }
}
package com.example.dice
 
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.dice.ui.theme.DiceTheme
 
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            DiceRoller()
        }
    }
}
 
@Composable
fun DiceRoller(modifier: Modifier = Modifier){
    var result by remember { mutableStateOf(1) }
 
    val imageResource = when(result){
        1 -> R.drawable.dice_1
        2 -> R.drawable.dice_2
        3 -> R.drawable.dice_3
        4 -> R.drawable.dice_4
        5 -> R.drawable.dice_5
        else -> R.drawable.dice_6
    }
 
    Column(
        modifier = modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ){
        Image(painter = painterResource(imageResource), contentDescription = result.toString())
        Spacer(modifier = Modifier.height(16.dp))
        Button(onClick = {result = (1..6).random()}){
            Text(text = "Roll  Dice"+result)
 
        }
        Text(text = "Number"+result)
    }
}
////Then extract it
//Now come to android studio
//In Android Studio, click View > Tool Windows > Resource Manager.
//Click + > Import Drawables to open a file browser.
//Click Next.
//Click Import to confirm that you want to import the six images
//Empty Activity
 
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp
import com.example.myapplication.ui.theme.MyApplicationTheme
 
 
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            Surface(modifier = Modifier.fillMaxSize(),
                color = Color.White
 
            ) {
                Box(
                    contentAlignment = Alignment.Center,
                    modifier = Modifier.fillMaxSize()
                ){
                    Text(text = "Hello World",
                        color = Color.Red,
                        fontSize = 32.sp
                    )
 
                }
 
            }
        }
 
    }
}
class Greeting {
    var name:String=" "
    get() = field
    set(value){
        field = value
    }
    
    var msg:String=" "
    get() = field
    set(value){
        field = value
    }
}

fun main(args: Array<String>) {
    val obj = Greeting()
    obj.name = "abc"
    obj.msg = "Hello"
    println(obj.msg)
    println(obj.name)
}
fun greet(name:String,msg:String="Hello"){
    println(" $msg   $name")
}
fun main() {
    
    greet("cse","welcome")
    greet("mad")
}
import kotlin.random.Random
fun main() {
    
    var guess:Int?
    var targetNum=Random.nextInt(1,100)
    var attempts=0
    do{
        guess=readLine()?.toIntOrNull();
        attempts++
        if(guess==null){
            println("Enter valid number")
            
        }
        else{
        when{
            guess < targetNum -> println("Too low")
            guess > targetNum -> println("To high")
            else->println("Your have guess the nummber in $attempts attempts")
        }
        }
        
    }
    while(guess!=targetNum && guess != null)
    
}
fun main() {
    val inp:Int?=readLine()?.toIntOrNull();
    if(inp!=null){
        val sqr=inp*inp;
        println("Ssquare of given number is:$sqr")
    }
    else{
        println("Input is null");
    }
}
SELECT
EmailAddress, SubscriberKey, Consent_Level_Summary__c,
Business_Unit__c, Region, Cat_Campaign_Most_Recent__c , Mailing_Country__c, LastModifiedDate, System_Language__c, CreatedDate,
FirstName
 
FROM (
SELECT
DISTINCT LOWER(Email__c) AS EmailAddress, i.Region__c AS Region, c.Id AS SubscriberKey, c.Consent_Level_Summary__c, i.Business_Unit__c,i.Cat_Campaign_Most_Recent__c , i.Mailing_Country__c, i.LastModifiedDate, i.System_Language__c, i.CreatedDate,
c.FirstName,
 
ROW_NUMBER() OVER(PARTITION BY c.Id ORDER BY i.LastModifiedDate DESC) as RowNum
 
FROM ent.Interaction__c_Salesforce i
JOIN ent.Contact_Salesforce_1 c ON LOWER(c.Email) = LOWER(i.Email__c)
JOIN TEST_ps_an_en_us_s190010_Retail_TA_Segment_sendable_NEW new ON LOWER(new.EmailAddress) = LOWER(i.Email__c)
INNER JOIN ent.ContactPointConsent_Salesforce AS cpc ON c.Id = cpc.Contact__c
INNER JOIN ent.DataUsePurpose_Salesforce AS dup ON cpc.DataUsePurposeId = dup.Id

WHERE
     Email__c IS NOT NULL
    AND i.Business_Unit__c IN  ('CISD','GASD','Product Support','PS')
    AND Email__c NOT LIKE '%@cat.com'
    AND i.Mailing_Country__c IS NOT NULL
    AND cpc.CaptureContactPointType = 'Email'
    AND cpc.MATM_Owner__c = 'Caterpillar'
    AND dup.Name = 'Caterpillar Marketing'
    AND cpc.PrivacyConsentStatus = 'OptIn' 
    AND (cpc.EffectiveTo IS NULL OR cpc.EffectiveTo < GetDate())
 
    AND ((c.AMC_Last_Activity_Record_ID__c IS NULL) OR (c.AMC_Last_Activity_Record_ID__c <> 'Not Marketable'))
    AND (i.Mailing_State_Province__c != 'QC' OR (i.Mailing_Country__c != 'CA' AND i.Mailing_State_Province__c IS NULL))
    AND  (i.System_Language__c like 'en_%' OR (i.Mailing_Country__c != 'CA' AND i.System_Language__c is null))
    AND c.AMC_Status__c = 'Active'
    AND i.Cat_Campaign_Most_Recent__c NOT IN (
'PCC eNews',
'OHTE Offers',
'Mid America Trucking Show',
'Product Support On-Highway Legacy Engines Initiate Dealer',
'Million Miler',
'Iron Planet Auction - On Highway Legacy Machine',
'Product_Support_ECommerce_Contact',
'Iron Planet Auction - On Highway Legacy Engine',
'EP Spec Sizer Nurture',
'Parts.cat.com Account Registration',
'EP General Nurture',
'Drivecat.com - Mini Survey',
'OHTE Independent Shop Sweepstakes',
'Product Support Million Miler',
'OHTE Trucking Is Life eNews'
)

        )t2
 
WHERE RowNum = 1
SELECT i.SubscriberKey
	,i.EmailAddress
	,i.System_Language__c
	,i.Mailing_Country__c
	,i.First_Name__c
	,i.Cat_Campaign_Most_Recent__c
	,i.Business_Unit__c
	,i.System_Opt_in_for_eMail__c
	,i.DateAdded
	,i.PCCReg
FROM [Proposed_Retail_TA_News_2024_INCLUDE] i
WHERE 1 = 1
    AND NOT EXISTS (
        SELECT NULL
        FROM [Proposed_Retail_TA_News_2024_EXCLUDE] ex
        WHERE 1 = 1
            AND i.SubscriberKey = ex.SubscriberKey
    )
 
SELECT a.SubscriberKey,
       a.reason
FROM (
        SELECT s.SubscriberKey,
            'Undeliverable' as reason
        FROM ENT._Subscribers s
        JOIN Proposed_Retail_TA_News_2024_INCLUDE c on c.SubscriberKey = s.SubscriberKey
        WHERE 1 = 1
            AND s.status in ('held', 'bounced', 'unsubscribe', 'unsubscribed')
            AND s.SubscriberKey IN (
                SELECT x.SubscriberKey
                FROM [Proposed_Retail_TA_News_2024_INCLUDE] x
                WHERE 1 = 1
            )
             
    ) a

    
UNION ALL
SELECT a.SubscriberKey,
       a.reason
FROM (
        SELECT b.SubscriberKey,  
              'Dealer Exclusion' as reason
        FROM [Proposed_Retail_TA_News_2024_INCLUDE] b
        WHERE 1 = 1
            AND LOWER(
                RIGHT (
                    b.EmailAddress,
                    LEN(b.EmailAddress) - CHARINDEX('@', b.EmailAddress)
                )
            ) IN (
                SELECT LOWER(x.Domain)
                FROM ent.[Dealer Domains] x
            )
    ) a
UNION ALL
SELECT a.SubscriberKey,
       a.reason
FROM (
        SELECT b.SubscriberKey,
            'Hard bounce DE' as reason
        FROM [Proposed_Retail_TA_News_2024_INCLUDE] b
        WHERE 1 = 1
            AND b.SubscriberKey IN (
                SELECT x.SubscriberKey
                FROM ent.[Hard Bounces - Exclusion] x
            )
    ) a
UNION ALL
SELECT a.SubscriberKey,
       a.reason
FROM (
        SELECT b.SubscriberKey,
            'Cat Agency Exclusion' as reason
        FROM [Proposed_Retail_TA_News_2024_INCLUDE] b
        WHERE 1 = 1
            AND LOWER(
                RIGHT (
                    b.EmailAddress,
                    LEN(b.EmailAddress) - CHARINDEX('@', b.EmailAddress)
                )
            ) IN (
                SELECT LOWER(x.Domain)
                FROM ent.[Cat_Agency_Domains] x
            )
    ) a
UNION ALL
SELECT a.SubscriberKey,
       a.reason
FROM (
        SELECT b.SubscriberKey,
            'Competitor Exclusion' as reason
        FROM [Proposed_Retail_TA_News_2024_INCLUDE] b
        WHERE 1 = 1
            AND LOWER(
                RIGHT (
                    b.EmailAddress,
                    LEN(b.EmailAddress) - CHARINDEX('@', b.EmailAddress)
                )
            ) IN (
                SELECT LOWER(x.Domain)
                FROM ent.[Competitor Domains] x
            )
    ) a 
    
    UNION ALL
SELECT a.SubscriberKey,
       a.reason
FROM (
        SELECT b.SubscriberKey,
            'AMC Status' as reason
        FROM [Proposed_Retail_TA_News_2024_INCLUDE] b
        WHERE 1 = 1
         AND   b.AMC_Status__c IN ('Inactive', 'Expired')
    ) a 

       UNION ALL
SELECT a.SubscriberKey,
       a.reason
FROM (
        SELECT b.SubscriberKey,
            'AMC Not Marketable' as reason
        FROM [Proposed_Retail_TA_News_2024_INCLUDE] b
        WHERE 1 = 1
         AND   b.AMC_Last_Activity_Record_ID__c LIKE 'Not Marketable' 
         AND (b.AMC_Status__c LIKE 'Active' OR b.AMC_Status__c IS NULL)
    ) a 
SELECT 
c.ID as SubscriberKey,
i.Cat_Campaign_Most_Recent__c,
i.Email__c as EmailAddress,
i.ID as Interaction_ID,
i.CreatedDate,
i.First_Name__c,
i.Last_Name__c,
i.Business_Phone__c,
i.Company_Name__c,
i.Mailing_Country__c,
i.Mailing_Zip_Postal_Code__c,
i.Purchase_Timeframe__c,
i.Level_of_Interest__c,
i.System_Opt_in_for_eMail__c,
i.Contact_Source_Details_Most_Recent__c,
i.System_Language__c,
i.Industry__c,
i.Industry_Level_2_Master__c,
i.Job_Role__c,
i.Serial_Number__c,
i.Ci_Fleet_Size__c,
i.Business_Unit__c,
c.AMC_Status__c,
c.AMC_Last_Activity_Record_ID__c

FROM ent.interaction__c_salesforce i
JOIN ent.Contact_Salesforce_1 c ON c.Email = i.Email__c
WHERE i.Email__c IS NOT NULL
AND (i.System_Language__c LIKE 'en_%' OR i.System_Language__c IS NULL)
AND (i.Mailing_Country__c = 'US' OR i.Mailing_Country__c = 'CA')
AND (i.Mailing_State_Province__c NOT LIKE 'QC' OR i.Mailing_State_Province__c IS NULL)
AND i.Business_Unit__c IN  (
    'CISD',
    'GASD',
    'Product Support',
    'PS'
    )
AND i.Cat_Campaign_Most_Recent__c NOT IN (
'PCC eNews',
'OHTE Offers',
'Mid America Trucking Show',
'Product Support On-Highway Legacy Engines Initiate Dealer',
'Million Miler',
'Iron Planet Auction - On Highway Legacy Machine',
'Product_Support_ECommerce_Contact',
'Iron Planet Auction - On Highway Legacy Engine',
'EP Spec Sizer Nurture',
'Parts.cat.com Account Registration',
'EP General Nurture',
'Drivecat.com - Mini Survey',
'OHTE Independent Shop Sweepstakes',
'Product Support Million Miler',
'OHTE Trucking Is Life eNews'
)

AND i.Id IN (
    SELECT max(i2.Id)
    FROM ent.interaction__c_salesforce i2
    GROUP BY i2.Email__c
)




/** 
 * log("sample logging statement") --> can be used to print any data in the browser console.
 * ZDK module can be used for customising the UI and other functionalities.
 * return false to prevent <SAVE> action
**/

console.log("running client script");
var accountId = ZDK.Page.getField("Operating_Company").getValue().id;
const accountDetails = ZDK.Apps.CRM.Accounts.fetchById(accountId);
const relatedContacts = ZDK.Apps.CRM.Accounts.fetchRelatedRecords(accountId, 'Contacts')
if (relatedContacts.length) {
    for (const contact of relatedContacts) {
        var mp = {
            'id': contact.id,
            'name': contact.Full_Name
        }
    }
        ZDK.Page.getField('Requested_By').setValue(mp);
}
var vendor = {
    'id': accountDetails.Referred_By().id,
    'name': accountDetails.Referred_By().Vendor_Name
}

if (vendor.id != null)  
{
    ZDK.Page.getField("Vendor").setValue(vendor);
}

ZDK.Page.getField("Request_Status").setValue("Customer Requested");
const today = new Date();
const formattedDate = today.toISOString().split('T')[0];
console.log(formattedDate);
ZDK.Page.getField("Requested_Date").setValue(formattedDate);
accountId = "575609000057932130";
/////// Fetching From Zoho Analytics ////////
var functionResp = ZDK.Apps.CRM.Functions.execute("fetch_available_tokens", { "accountId": accountId });
// console.log(response);

var message = functionResp.message;
if (message == "function executed successfully");
{
    const parsedOutput = JSON.parse(functionResp._details.output);
    const columnOrder = parsedOutput.response.result.column_order;
    const rows = parsedOutput.response.result.rows;
    console.log(columnOrder)
    console.log(rows);

    tokenDetialsList = new Array();
    
    //////////////////        ///////////////////
    for (let i = 0; i < rows.length; i++)
    {
        var row = rows[i];
        let promoterId = row[columnOrder.indexOf("Promoter Id")];
        let promoterName = row[columnOrder.indexOf("Promoter Name")];
        let tokens = parseFloat(row[columnOrder.indexOf("Tokens")]);
        let tokenValue = parseFloat(row[columnOrder.indexOf("Token Value")]);

        let amount = (tokens * tokenValue).toFixed(2); 
        console.log(amount);

        var promoterMap= {
            'id': promoterId,
            'name': promoterName
        };

        var rowMap = {
            "Promoter": promoterMap,
            "Tokens": tokens,
            "Amount": amount
        };
        
        tokenDetialsList.push(rowMap);
        ////
        
    }
    console.log(tokenDetialsList);

    ZDK.Page.getForm().setValues({
        'Token_Details': tokenDetialsList
    });
    
}
Task-9
Implement Kruskal algorithm
Algorithm:
Algorithm Kruskal(E, cost, n, t)
// E is the set of edges in G. G has n vertices. cost[u, v] is the
// cost of edge (u, v). t is the set of edges in the minimum-
// spanning tree. The final cost is returned.

{
    Construct a heap out of the edge costs using Heapify;
    for i := 1 to n do parent[i] := −1;
    // Each vertex is in a different set.
    i := 0; mincost := 0.0;
    while ((i < n − 1) and (heap not empty)) do
    {
        Delete a minimum cost edge (u, v) from the heap
        and reheapify using Adjust;
        j := Find(u); k := Find(v);
        if (j ≠ k) then
        {
            i := i + 1;
            t[i, 1] := u; t[i, 2] := v;
            mincost := mincost + cost[u, v];
            Union(j, k);
        }
    }
    if (i ≠ n − 1) then write ("No spanning tree");
    else return mincost;
}
Program:
# KRUSKAL.PY

import heapq

class Graph():
  def __init__(self, v):
    self.V = v
    # graph contains list of edges ** (u, v, w)
    # u -> src, v -> destination, w -> weight/cost
    self.edges = []

  def add_edge(self,u,v,w):
    # add edge and override cost
    self.edges.append([u,v,w])

  def kruskal(self):
    
    # helper functions

    def find(parent, i):
      if parent[i]==i:
        return i
      # path compression technique
      return find(parent, parent[i])

    def union(parent, rank, x, y):
      # union by rank

      # finding roots of disjoint sets x and y
      x_root = find(parent,x)
      y_root = find(parent,y)

      # Attach smaller rank tree under root of 
        # high rank tree (Union by Rank)
      if rank[x_root]<rank[y_root]:
        parent[x_root] = y_root
      elif rank[x_root]>rank[y_root]:
        parent[y_root] = x_root   
      else:
        # If ranks are same, then make one as root 
        # and increment its rank by one 
        parent[y_root] = x_root
        rank[x_root] += 1

    def cout(t):
      print()
      print("Selected Edges:")
      for edge in t:
        print(edge[0]+1,edge[1]+1,edge[2])

    
    # The main function to construct MST using Kruskal's algorithm 

    # t[1:n-1,1:3] : selected edges, exactly n-1
    t = [[0,0,0] for i in range(self.V-1)]

    # Create a min-heap of edges
    min_heap = []
    for u, v, w in self.edges:
        heapq.heappush(min_heap, (w, u, v))

    parent = [i for i in range(self.V)]
    rank = [0]*self.V

    # count of edges in t / MST
    i = 0
    mincost = 0

    while i<self.V-1 and  min_heap:
      w,u,v = heapq.heappop(min_heap)
      j = find(parent,u)
      k = find(parent,v)

      if j!=k:
        t[i][0],t[i][1],t[i][2] = u,v,w
        i+=1
        mincost += w
        union(parent,rank,j,k)
    
    cout(t)
    print("mincost : ",mincost)

if __name__ == '__main__':
  v = int(input("Enter number of vertices :"))
  g = Graph(v)
  e = int(input("Enter number of Edges :"))
  for _ in range(e):
    u,v,w = map(int, input().split())
    g.add_edge(u-1,v-1,w)

  g.kruskal()


  '''

INPUT:

7
9
1 6 10
6 5 25
5 4 22
5 7 24
4 3 12
4 7 18
7 2 14
2 3 16
2 1 28

OUTPUT:

Selected Edges:
1 6 10
4 3 12
7 2 14
2 3 16
5 4 22
6 5 25
mincost :  99

'''
Task-8
Implement Prim's algorithm
Algorithm:
Algorithm Prim(E, cost, n, t)
// E is the set of edges in G. cost[1 : n, 1 : n] is the cost 
//adjacency matrix of an n-vertex graph such that cost[i, j] is 
//either a positive real number or ∞ if no edge (i, j) exists.
// A minimum spanning tree is computed and stored as a set of edges in the array t[1 : n − 1, 1 : 2].
// (t[i, 1], t[i, 2]) is an edge of 
//the minimum-cost spanning tree. The final cost is returned.
{
Let (k, l) be an edge of minimum cost in E;
mincost := cost[k, l];
t[1, 1] := k; t[1, 2] := l;

For i := 1 to n do // Initialize near.

if (cost[i, l] < cost[i, k]) then near[i] := l;  
else near[i] := k;  
near[k] := near[l] := 0;

For i := 2 to n − 1 do
{
// Find n − 2 additional edges for t.  
Let j be an index such that near[j] ≠ 0 and cost[j, near[j]] is minimum;  
t[i, 1] := j; t[i, 2] := near[j];  
mincost := mincost + cost[j, near[j]];  
near[j] := 0;  
for k := 1 to n do  
    if ((near[k] ≠ 0) and (cost[k, near[k]] > cost[k, j]))  
        then near[k] := j;  
}
Return mincost;
}

Program:
#PRIM.PY

class Graph():
  def __init__(self, v):
    self.V = v
    # graph[][] ~~~ cost [][]
    # cost = inf ~~ 1000000007 if no edge between pair
    # initially no edges
    self.cost = [[1000000007 for cols in range(v)] for rows in range(v)]

  def add_edge(self,u,v,w):
    # add edge and override cost
    self.cost[u][v] = self.cost[v][u] = w


  def prim(self):

    # helper functions

    def find_min_edge():
      min_edge = 1000000007 #~~ inf
      # initilize (k,l) to (-1,-1)
      k,l = -1,-1
      for i in range(self.V):
        for j in range(self.V):
          if i!=j and self.cost[i][j]<min_edge:
            min_edge = self.cost[i][j]
            k,l = i,j
      return k,l

    def find_next_edge(near):
      j = -1
      min_cost = 1000000007 # ~inf
      for i in range(self.V):
        if near[i]!=-1 and self.cost[i][near[i]]<min_cost:
          min_cost = self.cost[i][near[i]]
          j = i
      return j

    def update_near(near, j):
      for k in range(self.V):
        if near[k]!=-1 and self.cost[k][near[k]] > self.cost[k][j]:
          near[k] = j

    def cout(t):
      print()
      print("selected edges :")
      for edge in t:
        print(edge[0]+1,edge[1]+1,self.cost[edge[0]][edge[1]])



    # The main function to construct MST using prim's algorithm 



    # t[1:n-1,1:2] : selected edges, exactly n-1
    t = [[0,0] for i in range(self.V-1)]

    # find (k,l) an edge with minimum cost
    k,l = find_min_edge()
    mincost = self.cost[k][l]
    t[0][0], t[0][1] = k,l

    # define near[]
    near = [-1]*self.V

    for i in range(self.V):
      if self.cost[i][l]<self.cost[i][k]:
        near[i] = l
      else:
        near[i] = k
    
    near[k] = near[l] = -1

    for i in range(1,self.V-1):
      # j is the next vertex where near[j]!=0 and cost[j][near[j]] is minimum
      j = find_next_edge(near)
      # add to selected edges
      t[i][0],t[i][1] = j,near[j]
      mincost += self.cost[j][near[j]]
      # set near[j] to 0
      near[j] = -1

      # update near
      update_near(near,j)

    # print selected edges and mincost
    
    cout(t)
    print("mincost : ",mincost)
  

if __name__ == '__main__':
  v = int(input("Enter number of vertices :"))
  g = Graph(v)
  e = int(input("Enter number of Edges :"))
  for _ in range(e):
    u,v,w = map(int, input().split())
    g.add_edge(u-1,v-1,w)
  
  g.prim()

  '''

INPUT:

7
9
1 6 10
6 5 25
5 4 22
5 7 24
4 3 12
4 7 18
7 2 14
2 3 16
2 1 28

OUTPUT:

selected edges :
1 6 10
5 6 25
4 5 22
3 4 12
2 3 16
7 2 14
mincost :  99

'''

#EX1
import random
class Domino:
    def __init__(self,a,b):
        self.a=a
        self.b=b
    def affiche_points(self):
        return("face a :",self.a,"face b" , self.b)

def generer_dominos(n):
    L=[]
    for i in range (n):
        L.append(Domino.affiche_points(Domino(random.randint(1,6),random.randint(1,6))))
    return L


def afficher_dominos(L):
    for i in range(len(L)):
        print("domino Num",i,"face a" ,L[i][1],"face b", L[i][3])
    return None

def tri_dominos(L):
    for i in range (len(L)):
        for j in range(0,len(L)-i-1):
            if (L[j][1]+L[j][3])>(L[j+1][1]+L[j+1][3]):
                L[j], L[j+1] = L[j+1], L[j]
    return L
def final():
    L=generer_dominos(int(input("donner le nombre de dominos")))
    print(afficher_dominos(L))
    print(tri_dominos(L))

print(final())

#EX2
import random
class satellite():
    def __init__(self,nom,masse,vitesse):
        self.nom=nom
        self.masse=masse
        self.vitesse=vitesse
    def impulsion(self,force,duree):
        self.vitesse=self.vitesse+((force*duree)/self.masse)
        return self
    def affiche_vitesse(self):
        return("nom : ", self.nom ,"son vitesse est  : ", self.vitesse)
        
    def energie(self):
        return(0,5*(self.masse)*((self.vitesse)**2))
        
def genere_liste():
    L=[]
    for i in range(5):
        a=input("donner le nom de satellite : ")
        L.append(satellite(a,random.randint(1,50),random.randint(1,500)))
    return L

def afficher (L):
    for i in range(len(L)):
        print(satellite.affiche_vitesse(L[i]))
    return None
def ajouter_impulsion(L):
    for i in range(len(L)):
        print(satellite.affiche_vitesse(satellite.impulsion(L[i],500,15)))
    return None
def aff(L):
    for i in range (L):
        print(satellite.affiche_vitesse(L[i]),satellite.energie(L[i]))


L=genere_liste()
print(afficher(L))
print(ajouter_impulsion(L))
print(aff(L))
       
       
export function removeChar(str: string): string {
 let newString = str.split("");
  newString = newString.slice(1,-1);
 return newString.join("");
}


// Another better option:

export function removeChar(str: string): string {
  return str.slice(1,-1);
}
import os
import time
import cv2
from baseline import find_baseline
from tangent_point import find_tangent_point
from lower_limb import find_lower_limb

masks_dir = "./app/angle_utils/masks"
output_file = "./app/angle_utils/function_timings.csv"
max_masks = 100


def time_function(func, *args):
    start_time = time.time()
    try:
        func(*args)
    except Exception as e:
        print(f"Error in {func.__name__}: {e}")
    end_time = time.time()
    return end_time - start_time


results = {
    "find_baseline": [],
    "find_lower_limb": [],
    "find_tangent_point": []
}

mask_files = [f for f in os.listdir(masks_dir) if f.endswith(".png")]

for i, mask_file in enumerate(mask_files[:max_masks]):
    mask_path = os.path.join(masks_dir, mask_file)
    mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)

    if mask is None:
        print(f"Unable to read mask {mask_file}")
        continue

    print(f"Processing {i+1}/{min(len(mask_files), max_masks)}: {mask_file}")

    baseline_time = time_function(find_baseline, mask)
    results["find_baseline"].append(baseline_time)

    lower_limb_time = time_function(find_lower_limb, mask, mask_file)
    results["find_lower_limb"].append(lower_limb_time)

    tangent_time = time_function(
        find_tangent_point, mask, mask, mask.shape, (0, 0), None, mask_file
    )
    results["find_tangent_point"].append(tangent_time)

with open(output_file, "w") as f:
    f.write("Function,Average Time (s),Max Time (s),Min Time (s)\n")

    for func_name, times in results.items():
        avg_time = sum(times) / len(times) if times else 0
        max_time = max(times) if times else 0
        min_time = min(times) if times else 0
        f.write(f"{func_name},{avg_time},{max_time},{min_time}\n")

print(f"Timing results saved to {output_file}")
import os
import time
import cv2
from baseline import find_baseline
from lower_limb_sensitivity import verify_lower_limb_sensitivity
from class_small_areas import verify_class_small_areas
from bony_roof_length import verify_bony_roof_length
from baseline_horizontality import verify_baseline_horizontality

masks_dir = "./app/angle_utils/masks"
output_file = "./app/scoring_utils/scoring_time.csv"
max_masks = 100


def time_function(func, *args):
    """Pomiar czasu działania funkcji."""
    start_time = time.time()
    try:
        result = func(*args)
    except Exception as e:
        print(f"Error in {func.__name__}: {e}")
        result = None
    end_time = time.time()
    return end_time - start_time, result


# Wyniki pomiarów
results = {
    "verify_lower_limb_sensitivity": [],
    "verify_class_small_areas": [],
    "verify_bony_roof_length": [],
    "verify_baseline_horizontality": []
}

# Pobranie plików masek
mask_files = [f for f in os.listdir(masks_dir) if f.endswith(".png")]

for i, mask_file in enumerate(mask_files[:max_masks]):
    mask_path = os.path.join(masks_dir, mask_file)
    mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)

    if mask is None:
        print(f"Unable to read mask {mask_file}")
        continue

    print(f"Processing {i+1}/{min(len(mask_files), max_masks)}: {mask_file}")

    # Najpierw obliczenie punktów baseline
    baseline_time, baseline_points = time_function(find_baseline, mask)
    if baseline_points is None or len(baseline_points) != 2:
        print(f"Skipping {mask_file} due to invalid baseline points")
        continue

    # Czas dla funkcji verify_lower_limb_sensitivity
    sensitivity_time, _ = time_function(verify_lower_limb_sensitivity, mask, baseline_points)
    results["verify_lower_limb_sensitivity"].append(sensitivity_time)

    # Czas dla funkcji verify_class_small_areas
    class_small_areas_time, _ = time_function(verify_class_small_areas, mask)
    results["verify_class_small_areas"].append(class_small_areas_time)

    # Czas dla funkcji verify_bony_roof_length
    bony_roof_time, _ = time_function(verify_bony_roof_length, mask)
    results["verify_bony_roof_length"].append(bony_roof_time)

    # Czas dla funkcji verify_baseline_horizontality
    horizontality_time, _ = time_function(verify_baseline_horizontality, baseline_points)
    results["verify_baseline_horizontality"].append(horizontality_time)

# Zapis wyników do pliku CSV
with open(output_file, "w") as f:
    f.write("Function,Average Time (s),Max Time (s),Min Time (s)\n")

    for func_name, times in results.items():
        avg_time = sum(times) / len(times) if times else 0
        max_time = max(times) if times else 0
        min_time = min(times) if times else 0
        f.write(f"{func_name},{avg_time},{max_time},{min_time}\n")

print(f"Timing results saved to {output_file}")
public Static HcmPositionId EmpPositionId(RecId  _RecId)
    {
        HcmPosition HcmPosition;

        HcmPositionWorkerAssignment HcmPositionWorkerAssignment;

        select  HcmPosition
   join HcmPositionWorkerAssignment where HcmPositionWorkerAssignment.Position==HcmPosition.RecId
    && HcmPositionWorkerAssignment.ValidTo>=DateTimeUtil::getSystemDateTime()
    && HcmPositionWorkerAssignment.Worker==_RecId ;

        return  HcmPosition.PositionId;
    }
public static DirPartyRelationship findByChildParty(DirPartyRecId             _parentParty,
                                                    DirPartyRecId             _childParty,
                                                    boolean _forupdate = false)
    {
        DirPartyRelationship  partyRelationship = null;
        ;

        partyRelationship.selectForUpdate(_forupdate);

        select firstonly partyRelationship
        index hint TypeParentChildIdx
        where partyRelationship.ParentParty == _parentParty &&
              partyRelationship.ChildParty == _childParty;

        return partyRelationship;
    }

    public static void lookupDependentsByParentParty(FormStringControl _formControl, DirPartyRecId _ParentParty)
    {

        SysTableLookup          sysTableLookup = SysTableLookup::newParameters(tableNum(DirPartyRelationship),_formControl);
        Query                   query = new Query();
        QueryBuildDataSource    queryBuildDataSource = query.addDataSource(tableNum(DirPartyRelationship));
        QueryBuildRange         queryBuildRangeJournalType = queryBuildDataSource.addRange(fieldNum(DirPartyRelationship, ParentParty));

        sysTableLookup.addLookupfield(fieldNum(DirPartyRelationship, RelationshipTypeId));
        sysTableLookup.addLookupfield(fieldNum(DirPartyRelationship, ChildParty));

        queryBuildRangeJournalType.value(queryValue(_ParentParty));

        sysTableLookup.parmQuery(query);
        sysTableLookup.performFormLookup();
    }
1.	Create a web page using the advanced features of CSS Grid. Apply transitions and animations to the contents of the web page.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Minimal CSS Grid</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    body {
      font-family: Arial, sans-serif;
      background: #f4f4f4;
      color: #333;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
    }
    .container {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 10px;
      width: 80%;
      max-width: 800px;
    }

    .item {
      background: #ffffff;
      border: 1px solid #ddd;
      border-radius: 5px;
      padding: 20px;
      text-align: center;
      transition: transform 0.3s ease, background-color 0.3s ease;
    }
    .item:hover {
      transform: scale(1.05);
      background-color: #f0f8ff;
    }
    @keyframes fadeIn {
      from {
        opacity: 0;
      }
      to {
        opacity: 1;
      }
    }
    .container {
      animation: fadeIn 1s ease-in-out;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="item">Item 1</div>
    <div class="item">Item 2</div>
    <div class="item">Item 3</div>
    <div class="item">Item 4</div>
    <div class="item">Item 5</div>
    <div class="item">Item 6</div>
  </div>
</body>
</html>
2.	Create a web page using the advanced features of CSS Flexbox. Apply transitions and animations to the contents of the web page.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Basic Flexbox with Animation</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background: #f0f0f0;
            font-family: Arial, sans-serif;
        }

        .container {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-around;
            gap: 20px;
        }
        .card {
            background: #fff;
            padding: 20px;
            text-align: center;
            border-radius: 8px;
            width: 200px;
            transition: transform 0.3s ease;
        }
        .card:hover {
            transform: scale(1.05);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
            <h3>Card 1</h3>
            <p>Some interesting text.</p>
        </div>
        <div class="card">
            <h3>Card 2</h3>
            <p>More details here.</p>
        </div>
        <div class="card">
            <h3>Card 3</h3>
            <p>Additional content.</p>
        </div>
    </div>
</body>
</html>
3.	Demonstrate pop-up box alerts, confirm, and prompt using JavaScript.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JavaScript Pop-ups</title>
</head>
<body>
  <button onclick="showAlert()">Show Alert</button>
  <button onclick="showConfirm()">Show Confirm</button>
  <button onclick="showPrompt()">Show Prompt</button>
  <script>
    function showAlert() {
      alert("This is a simple alert box!");
    }
    function showConfirm() {
      const result = confirm("Do you want to proceed?");
      if (result) {
        alert("You chose to proceed!");
      } else {
        alert("You chose to cancel.");
      }
    }
    function showPrompt() {
      const name = prompt("What is your name?");
      if (name) {
        alert(`Hello, ${name}! Welcome!`);
      } else {
        alert("You didn't enter a name.");
      }
    }
  </script>
</body>
</html>
4.	Demonstrate Responsive Web Design using Media Queries to create a webpage.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Simple Media Query</title>
  <style>
    body {
      color: black;
    }
    @media (max-width: 600px) {
      body {
        color: blue;
      }
    }
  </style>
</head>
<body>
  Resize the browser to see the text color change!
</body>
</html>
5.	Write a JavaScript program to demonstrate the working of callbacks, promises, and async/await.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JavaScript Callbacks, Promises, Async/Await</title>
</head>
<body>
  <h1>JavaScript Callbacks, Promises, and Async/Await Demo</h1>
  <script>
    // Callback Example
    function doSomething(callback) {
      setTimeout(() => {
        callback("Callback done!");
      }, 1000);
    }
    doSomething(console.log);
    // Promise Example
    let promise = new Promise((resolve, reject) => {
      setTimeout(() => resolve("Promise resolved!"), 1000);
    });
    promise.then(console.log);
    // Async/Await Example
    async function asyncFunction() {
      let result = await promise;
      console.log(result);
    }
    asyncFunction();
  </script>
</body>
</html>
6.	Write an XML file that displays book information with the following fields: Title of the book, Author Name, ISBN number, Publisher name, Edition, and Price. Define a Document Type Definition (DTD) to validate the XML document created above.
Book.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE books SYSTEM "books.dtd">
<books>
  <book>
    <title>The Great Gatsby</title>
    <author>F. Scott Fitzgerald</author>
    <isbn>9780743273565</isbn>
    <publisher>Scribner</publisher>
    <edition>1st</edition>
    <price>10.99</price>
.
  </book>
  <book>
    <title>1984</title>
    <author>George Orwell</author>
    <isbn>9780451524935</isbn>
    <publisher>Signet Classic</publisher>
    <edition>Revised</edition>
    <price>9.99</price>
  </book>
</books>

Book.dtd

<!ELEMENT books (book+)>
<!ELEMENT book (title, author, isbn, publisher, edition, price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT isbn (#PCDATA)>
<!ELEMENT publisher (#PCDATA)>
<!ELEMENT edition (#PCDATA)>
<!ELEMENT price (#PCDATA)>
7.	Write an XML file that displays book information with the following fields: Title of the book, Author Name, ISBN number, Publisher name, Edition, and Price. Define an XML schema to validate the XML document created above.
Books.xml
<?xml version="1.0" encoding="UTF-8"?>
<books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://example.com/books books.xsd">
  <book>
    <title>The Great Gatsby</title>
    <author>F. Scott Fitzgerald</author>
    <isbn>9780743273565</isbn>
    <publisher>Scribner</publisher>
    <edition>1st</edition>
    <price>10.99</price>
  </book>
  <book>
    <title>1984</title>
    <author>George Orwell</author>
    <isbn>9780451524935</isbn>
    <publisher>Signet Classic</publisher>
    <edition>Revised</edition>
    <price>9.99</price>
  </book>
</books>

Books.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com/books" targetNamespace="http://example.com/books" elementFormDefault="qualified">
  
  <!-- Define the root element -->
  <xs:element name="books">
    <xs:complexType>
      <xs:sequence>
        <!-- The 'book' element can occur one or more times -->
        <xs:element name="book" maxOccurs="unbounded">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="title" type="xs:string"/>
              <xs:element name="author" type="xs:string"/>
              <xs:element name="isbn" type="xs:string"/>
              <xs:element name="publisher" type="xs:string"/>
              <xs:element name="edition" type="xs:string"/>
              <xs:element name="price" type="xs:decimal"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

8.	Write a Java application to validate the XML document using the DOM parser.
import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import org.w3c.dom.Document; import org.xml.sax.SAXException;  
import java.io.File; public class DOMDTDValidator {     
public static void main(String[] args) {         
try {             
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();             
factory.setValidating(true);              
factory.setNamespaceAware(false);              
DocumentBuilder builder = factory.newDocumentBuilder();             
File xmlFile = new File("books.xml");             
builder.parse(xmlFile);             
System.out.println("The XML document is valid.");         
} catch (SAXException e) {             
System.out.println("Validation error: " + e.getMessage());         
} catch (Exception e) {             
System.out.println("Error: " + e.getMessage());         
}     } }
 
books.xml

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE books SYSTEM "books.dtd"> 
<books>     
<book>         
<title>The Great Gatsby</title>         
<author>F. Scott Fitzgerald</author>         
<isbn>9780743273565</isbn>         
<price>10.99</price>     
</book>     
<book>         
<title>1984</title>         
<author>George Orwell</author>         
<isbn>9780451524935</isbn>         
<price>9.99</price>     
</book> 
</books> 


Books.dtd

<!ELEMENT books (book+)> 
<!ELEMENT book (title, author, isbn, price)> 
<!ELEMENT title (#PCDATA)> 
<!ELEMENT author (#PCDATA)> 
<!ELEMENT isbn (#PCDATA)> 
<!ELEMENT price (#PCDATA)> 





9.	Write a Java application to validate the XML document using the SAX parser.


Java code

import org.xml.sax.SAXException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;

public class SAXValidationExample {
    public static void main(String[] args) {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setValidating(true); 
            factory.setNamespaceAware(true); 
            SAXParser saxParser = factory.newSAXParser();
            saxParser.parse(new File("example.xml"), new SimpleHandler());
            System.out.println("XML is valid.");
        } catch (SAXException e) {
            System.out.println("Validation error: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


books.xml
<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE books SYSTEM "books.dtd"> 
<books>     
<book>         
<title>The Great Gatsby</title>         
<author>F. Scott Fitzgerald</author>        
<isbn>9780743273565</isbn>         
<price>10.99</price>     
</book>     
<book>         
<title>1984</title>         
<author>George Orwell</author>         
<isbn>9780451524935</isbn>         
<price>9.99</price>     
</book> </books>


Books.dtd
<!ELEMENT books (book+)> <!ELEMENT book (title, author, isbn, price)> <!ELEMENT title (#PCDATA)> <!ELEMENT author (#PCDATA)> <!ELEMENT isbn (#PCDATA)> <!ELEMENT price (#PCDATA)> 
All three in same folder complie and run the java file

   
10. Write a Java program to access the metadata of an SQL database.
import java.sql.*;

public class DatabaseMetadataDemo {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/your_database_name"; // Replace with your DB name
        String user = "root"; // Replace with your DB username
        String password = "your_password"; // Replace with your DB password

        try (Connection conn = DriverManager.getConnection(url, user, password)) {
            DatabaseMetaData metaData = conn.getMetaData();
            System.out.println("Database: " + metaData.getDatabaseProductName());
            System.out.println("Version: " + metaData.getDatabaseProductVersion());

            System.out.println("\nTables:");
            ResultSet tables = metaData.getTables(null, null, "%", new String[]{"TABLE"});
            while (tables.next()) {
                System.out.println("- " + tables.getString("TABLE_NAME"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

11.Java script scientific Calculator
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Calculator</title>
</head>
<body>
    <h2>Simple Calculator</h2>
    <input type="text" id="result" disabled>
    <br>
    <button onclick="appendToResult('1')">1</button>
    <button onclick="appendToResult('2')">2</button>
    <button onclick="appendToResult('3')">3</button>
    <button onclick="appendToResult('+')">+</button>
    <br>
    <button onclick="appendToResult('4')">4</button>
    <button onclick="appendToResult('5')">5</button>
    <button onclick="appendToResult('6')">6</button>
    <button onclick="appendToResult('-')">-</button>
    <br>
    <button onclick="appendToResult('7')">7</button>
    <button onclick="appendToResult('8')">8</button>
    <button onclick="appendToResult('9')">9</button>
    <button onclick="appendToResult('*')">*</button>
    <br>
    <button onclick="appendToResult('0')">0</button>
    <button onclick="clearResult()">C</button>
    <button onclick="calculateResult()">=</button>
    <button onclick="appendToResult('/')">/</button>

    <script>
        function appendToResult(value) {
            document.getElementById('result').value += value;
        }

        function clearResult() {
            document.getElementById('result').value = '';
        }

        function calculateResult() {
            const resultField = document.getElementById('result');
            try {
                resultField.value = eval(resultField.value);
            } catch (e) {
                resultField.value = 'Error';
            }
        }
    </script>
</body>
</html>

12.Demonstrate Servlet Lifecyle by implementing Servlet Interface
import javax.servlet.*; 
import java.io.IOException; 
import java.io.PrintWriter;  
public class MyServlet implements Servlet {   
public void init(ServletConfig config) throws ServletException {}   
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {     
PrintWriter out = res.getWriter();     
out.println("Hello Servlet Lifecycle!");   }   
public void destroy() {}   
public ServletConfig getServletConfig() { return null; }   
public String getServletInfo() { return null; } } 



13.Demonstrate Creation of Servlet program using Http Servlet class.

import javax.servlet.*; 
import javax.servlet.http.*; 
import java.io.IOException; 
import java.io.PrintWriter;  
public class HelloServlet extends HttpServlet {   
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {     
PrintWriter out = response.getWriter();     out.println("Hello from HttpServlet!");   } }




14.Write a java program to establish a connection to a database and execute simple SQL queries.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class SimpleDatabaseConnection {
    public static void main(String[] args) {
        // Database credentials
        String url = "jdbc:mysql://localhost:3306/your_database_name"; // Replace 'your_database_name'
        String user = "root"; // Replace 'root' with your username
        String password = "your_password"; // Replace 'your_password'

        // SQL query
        String query = "SELECT * FROM your_table_name"; // Replace 'your_table_name'

        // Establish connection and execute query
        try (Connection conn = DriverManager.getConnection(url, user, password);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(query)) {

            System.out.println("Connected to the database!");

            // Process the result set
            while (rs.next()) {
                int id = rs.getInt("id"); // Replace 'id' with your column name
                String name = rs.getString("name"); // Replace 'name' with your column name
                System.out.println("ID: " + id + ", Name: " + name);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

15.Write a java program to demonstrate the usage of JDBC in performing various DML statements using prepared statements.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JdbcDmlDemo {
    public static void main(String[] args) {
        // Database connection details
        String url = "jdbc:mysql://localhost:3306/your_database_name"; // Replace with your DB name
        String user = "root"; // Replace with your DB username
        String password = "your_password"; // Replace with your DB password

        // SQL queries
        String insertQuery = "INSERT INTO users (name, email) VALUES (?, ?)";
        String updateQuery = "UPDATE users SET email = ? WHERE id = ?";
        String deleteQuery = "DELETE FROM users WHERE id = ?";

        try (Connection conn = DriverManager.getConnection(url, user, password)) {
            System.out.println("Connected to the database!");

            // INSERT operation
            try (PreparedStatement insertStmt = conn.prepareStatement(insertQuery)) {
                insertStmt.setString(1, "John Doe");
                insertStmt.setString(2, "john.doe@example.com");
                int rowsInserted = insertStmt.executeUpdate();
                System.out.println(rowsInserted + " row(s) inserted.");
            }

            // UPDATE operation
            try (PreparedStatement updateStmt = conn.prepareStatement(updateQuery)) {
                updateStmt.setString(1, "john.newemail@example.com");
                updateStmt.setInt(2, 1); // Assuming user with ID 1 exists
                int rowsUpdated = updateStmt.executeUpdate();
                System.out.println(rowsUpdated + " row(s) updated.");
            }

            // DELETE operation
            try (PreparedStatement deleteStmt = conn.prepareStatement(deleteQuery)) {
                deleteStmt.setInt(1, 1); // Assuming user with ID 1 exists
                int rowsDeleted = deleteStmt.executeUpdate();
                System.out.println(rowsDeleted + " row(s) deleted.");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

16.Write a java based application to demonstrate the Scrollable Result sets.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ScrollableResultSetDemo {
    public static void main(String[] args) {
        // Database connection details
        String url = "jdbc:mysql://localhost:3306/your_database_name"; // Replace with your DB name
        String user = "root"; // Replace with your DB username
        String password = "your_password"; // Replace with your DB password

        // SQL query
        String query = "SELECT * FROM users";

        try (Connection conn = DriverManager.getConnection(url, user, password);
             Statement stmt = conn.createStatement(
                     ResultSet.TYPE_SCROLL_INSENSITIVE, // Allows scrolling
                     ResultSet.CONCUR_READ_ONLY          // Read-only ResultSet
             );
             ResultSet rs = stmt.executeQuery(query)) {

            System.out.println("Connected to the database!");

            // Move to the last row
            if (rs.last()) {
                System.out.println("Last Record:");
                System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
            }

            // Move to the first row
            if (rs.first()) {
                System.out.println("\nFirst Record:");
                System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
            }

            // Move to a specific row (e.g., second row)
            if (rs.absolute(2)) {
                System.out.println("\nSecond Record:");
                System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
            }

            // Iterate backward from the end
            System.out.println("\nIterating Backward:");
            rs.afterLast(); // Move to after the last row
            while (rs.previous()) {
                System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

17.Write a program to accept request parameters from a form and generate the response.

<!DOCTYPE html>
<html>
<head>
    <title>Form Example</title>
</head>
<body>
    <h1>Enter Your Details</h1>
    <form action="FormHandler" method="POST">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
        <br><br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
        <br><br>
        <button type="submit">Submit</button>
    </form>
</body>
</html>

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Map the servlet to a URL
@WebServlet("/FormHandler")
public class FormHandler extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Set the response content type
        response.setContentType("text/html");
        // Retrieve form parameters
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        // Generate the response
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head><title>Form Response</title></head>");
        out.println("<body>");
        out.println("<h1>Form Submitted Successfully</h1>");
        out.println("<p>Name: " + name + "</p>");
        out.println("<p>Email: " + email + "</p>");
        out.println("</body>");
        out.println("</html>");
    }
}
Jdbc
folder->settings icon->commad pallete->in search bar java: create project..->no build tools->a window will be opend selcr the option “select project location”->type project name(click enter new window will be opened)->in src folder you’ll have app.java file->rename the file and give the java code here (in app.java)->id run not suitable exception found error(mysql is not connected)->in search “mysql 8.0 command client”->java projects in vs code palette->select reference libraries->this pc,program files*86,my sql foler,connector (select t he jar file)->run the java code
Talabat app includes multiple on-demand delivery options in their platforms. A lot of young entrepreneurs want to integrate these features into their food and grocery delivery apps. For that, they need customization options in the competitive market for anybody to reform their platform with their developers. At this time Appticz acknowledges and addresses the user's demand in all aspects of customization options they deliver a lot of possibilities for their users. Our Talabat clone scripts come with multifarious levels of customizations that can be done effortlessly. Here, we list out the customization options for the users
◦ Implement your own logo, branding, color, web/app design
◦ customize your platform menus, and options, alter discounts and offers at any time, and Add or modify features such as order history, favorites, and quick reorder options.
◦ Include multiple languages for broader accessibility, accommodating diverse customer bases.
◦ Customize payment options by integrating various payment gateways that best suit your target market (e.g., Stripe, PayPal).
◦ Personalize push notifications for order updates, promotions, and customer engagement based on user preferences.
◦ Customize the admin dashboard to provide tailored insights and controls over orders, user management, and analytics.
◦ Adjust UI elements like buttons, fonts, and icons to create a user-friendly experience that reflects your brand.
◦ Implement unique features such as loyalty programs, referral systems, or in-app chat support for enhanced customer interaction.
◦ Integrate custom analytics tools to monitor performance metrics like sales trends and user behavior tailored to your business needs.
◦ Customize geolocation features to define delivery zones or areas effectively.

These are the list of customization possibilities using the Talabat clone script to expand your business.
# Import required libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.cluster import KMeans

# Given Data
data = {
    'Feature1': [10, 20, 30, 40, 50],
    'Feature2': [100, 200, 300, 400, 500]
}

# Step 1: Create a DataFrame
df = pd.DataFrame(data)

# Step 1.1: Apply Standard Scaler
scaler_standard = StandardScaler()
df_standard = scaler_standard.fit_transform(df)

# Step 1.2: Apply Min-Max Scaler
scaler_minmax = MinMaxScaler()
df_minmax = scaler_minmax.fit_transform(df)

# Step 2: Apply KMeans Clustering (2 clusters for demonstration)
kmeans = KMeans(n_clusters=2, random_state=42)

# Fitting KMeans on both scaled datasets
kmeans_standard = kmeans.fit_predict(df_standard)
kmeans_minmax = kmeans.fit_predict(df_minmax)

# Step 3: Pie Chart Visualization for KMeans (using standard scaled data as an example)
# Count the occurrences of each cluster
labels_standard = pd.Series(kmeans_standard).value_counts()

# Plot the pie chart
plt.figure(figsize=(6, 6))
plt.pie(labels_standard, labels=[f"Cluster {i}" for i in labels_standard.index], autopct='%1.1f%%', startangle=90)
plt.title('Pie Chart of KMeans Clusters (Standard Scaled Data)')
plt.show()
# Import necessary libraries
import pandas as pd
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer
import matplotlib.pyplot as plt

# Step 1: Create the DataFrame
data = {
    'name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Frank', 'Grace', 'Hannah', 'Ian', 'Jane'],
    'score': [85, 92, 88, 74, 95, 67, 78, 81, 89, 90],
    'sport': ['Basketball', 'Soccer', 'Tennis', 'Cricket', 'Baseball', 'Swimming', 'Soccer', 'Basketball', 'Tennis', 'Cricket'],
    'sex': ['F', 'M', 'M', 'M', 'F', 'M', 'F', 'F', 'M', 'F']
}

df = pd.DataFrame(data)
print("Original DataFrame:\n", df)

# Step 2: Add extra columns (gender and age)
df['gender'] = df['sex'].map({'F': 'Female', 'M': 'Male'})  # Map 'F' to 'Female' and 'M' to 'Male'
df['age'] = [20, 22, 19, 21, 23, 18, 22, 20, 24, 21]  # Adding age column
print("\nDataFrame after adding gender and age columns:\n", df)

# Step 3: Create custom index
df.index = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]
print("\nDataFrame with custom index:\n", df)

# Step 4: Apply Label Encoding on 'gender' column
label_encoder = LabelEncoder()
df['gender_encoded'] = label_encoder.fit_transform(df['gender'])
print("\nDataFrame after Label Encoding:\n", df)

# Step 5: Apply One Hot Encoding using OneHotEncoder on 'sport' column
one_hot_encoder = OneHotEncoder(sparse_output=False)  # Use sparse=False to get a dense array
sport_encoded = one_hot_encoder.fit_transform(df[['sport']])  # Fit and transform 'sport' column

# Create a DataFrame for the encoded data
sport_encoded_df = pd.DataFrame(sport_encoded, columns=one_hot_encoder.get_feature_names_out(['sport']), index=df.index)

# Combine with the original DataFrame
df = pd.concat([df, sport_encoded_df], axis=1)
print("\nDataFrame after One Hot Encoding using OneHotEncoder:\n", df)

# Step 6: Bar Plot for Categorical Data
# Count the occurrences of each sport
sport_counts = df['sport'].value_counts()

# Plot the bar chart
plt.figure(figsize=(8, 6))
sport_counts.plot(kind='bar', color='skyblue')
plt.title('Frequency of Sports Participation')
plt.xlabel('Sport')
plt.ylabel('Frequency')


plt.show()
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
 
# Creating a DataFrame with Name, Age, and City
data = {
    "Name": ["Alice", "Bob", "Charlie", "David", "Eve"],
    "Age": [25, 30, 35, 40, 28],
    "City": ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"],
}
df = pd.DataFrame(data)
 
# Display the DataFrame
print("DataFrame:")
print(df)
 
# 1.1 Box Plot for Age
plt.figure(figsize=(8, 6))
sns.boxplot(x=df["Age"], color="skyblue")
plt.title("Box Plot of Age", fontsize=14)
plt.xlabel("Age", fontsize=12)
plt.show()
 
# Example Data for Heatmap
sales = [12000, 15000, 17000, 13000, 16000, 19000]
profit = [3000, 5000, 7000, 4000, 6000, 8000]
products_sold = [200, 250, 300, 220, 280, 310]
 
# Creating a DataFrame for the heatmap
heatmap_data = {
    "Sales": sales,
    "Profit": profit,
    "Products Sold": products_sold,
}
df_heatmap = pd.DataFrame(heatmap_data)
 
# 1.2 Heatmap of Correlations
plt.figure(figsize=(8, 6))
correlation_matrix = df_heatmap.corr()
sns.heatmap(correlation_matrix, annot=True)
plt.title("Heatmap of Correlations", fontsize=14)
plt.show()
# Import necessary libraries
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
 
# Step 1: Create a dataset (sample data for house rentals)
data = {
    'Size (sq ft)': [850, 900, 1200, 1500, 1800, 2000, 2300, 2500, 2700, 3000],
    'Bedrooms': [2, 2, 3, 3, 4, 4, 5, 5, 5, 6],
    'Age (years)': [5, 10, 3, 20, 15, 10, 8, 12, 30, 20],
    'Location Score': [8, 7, 9, 6, 8, 8, 9, 9, 7, 6],
    'Rental Price (USD)': [1500, 1700, 2500, 3000, 3500, 3700, 4200, 4500, 4700, 5000]
}
 
df = pd.DataFrame(data)
 
# Step 2: Split the data into features (X) and target (y)
X = df[['Size (sq ft)', 'Bedrooms', 'Age (years)', 'Location Score']]
y = df['Rental Price (USD)']
 
# Step 3: Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
 
# Step 4: Train the Multiple Linear Regression model
model = LinearRegression()
model.fit(X_train, y_train)
 
# Step 5: Make predictions on the test set
y_pred = model.predict(X_test)
 
# Step 6: Evaluate the model
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
 
print("Model Evaluation:")
print(f"Mean Squared Error (MSE): {mse:.2f}")
print(f"R² Score: {r2:.2f}")
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, confusion_matrix,classification_report

# Step 1: Load Iris dataset
file_path = "/content/iris.csv"  # Replace with the actual file path
iris_data = pd.read_csv(file_path)

# Separate features (X) and target (y)
X = iris_data.drop(["Species"], axis=1)  # Drop unnecessary columns
y = iris_data["Species"]

# Step 2: Split the dataset
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Step 3: Apply StandardScaler
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.fit_transform(X_test)

# Step 4: Load KNN model
knn = KNeighborsClassifier(n_neighbors=5)  # Default k=5

# Step 5: Train the model and make predictions
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)

# Step 6: Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
conf_matrix = confusion_matrix(y_test, y_pred)
classification_report=classification_report(y_test,y_pred)

# Display results
print("Accuracy Score:", accuracy)
print("Confusion Matrix:\n", conf_matrix)
print("Confusion Matrix:\n", classification_report)
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
 
# Load the Iris dataset
data = load_iris()
X = data.data  # Features
 
# Initialize the KMeans model with 3 clusters (since there are 3 species in the Iris dataset)
kmeans = KMeans(n_clusters=3, random_state=42)
 
# Fit the model to the data
kmeans.fit(X)
 
# Predict the cluster labels
y_pred = kmeans.predict(X)
 
# Create a DataFrame for visualization
df = pd.DataFrame(X, columns=data.feature_names)
df['Cluster'] = y_pred
 
# Plot the clusters (using only the first two features for simplicity)
plt.figure(figsize=(8, 6))
sns.scatterplot(data=df, x=data.feature_names[0], y=data.feature_names[1], hue='Cluster')#, palette='viridis', s=100)
plt.title('K-Means Clustering on Iris Dataset (2D)')
plt.xlabel(data.feature_names[0])
plt.ylabel(data.feature_names[1])
plt.show()
 
# Print the cluster centers
print("Cluster Centers (Centroids):")
print(kmeans.cluster_centers_)
import pandas as pd
 
# Step 1.1: Convert the dictionary to a DataFrame
data = {
    'Category': ['A', 'B', 'A', 'C', 'B']
}
df = pd.DataFrame(data)
 
# Step 1.2: Apply One-Hot Encoding
df_encoded = pd.get_dummies(df, columns=['Category'])
 
# Step 1.3: Print the DataFrame with One-Hot Encoding
print(df_encoded)
import pandas as pd
import matplotlib.pyplot as plt
 
# Create the DataFrame
data = {
    'Feature1': [10, 20, 30, 40, 50],
    'Feature2': [100, 200, 300, 400, 500]
}
df = pd.DataFrame(data)
 
# Calculate the sum of each feature for pie chart visualization
sizes = [df['Feature1'].sum(), df['Feature2'].sum()]
 
# Labels for the pie chart
labels = ['Feature1', 'Feature2']
 
# Plotting the Pie Chart
plt.pie(sizes, labels=labels)
plt.title("Proportion of Feature1 and Feature2")
plt.show()
# Import necessary libraries
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score

# Load the dataset
data = pd.read_csv('/content/Soybean (1).csv')  # Replace 'soybean.csv' with your actual file name

# Split the data into features (X) and target (y)
X = data.drop(columns=['Class'])  # 'Class' is the target column
y = data['Class']

# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Create and train the Decision Tree model
model = DecisionTreeClassifier(random_state=42)
model.fit(X_train, y_train)

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

# Calculate and print the accuracy
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy of the Decision Tree model: {accuracy * 100:.2f}%")
# Import necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
 
# Sample Dataset (replace this with your actual dataset)
# Let's assume we have a dataset with features: 'height', 'weight', and 'experience'
data = {
    'height': [150, 160, 170, 180, 190],
    'weight': [50, 60, 70, 80, 90],
    'experience': [2, 3, 4, 5, 6],
    'age': [25, 28, 30, 35, 40]  # This is the target variable
}
 
# Create a DataFrame
df = pd.DataFrame(data)
 
 
 
# Step 2: Data Preprocessing
# Define features (X) and target (y)
X = df[['height', 'weight', 'experience']]  # Independent variables
y = df['age']  # Dependent variable (age)
 
# Step 3: Train-Test Split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
 
# Step 4: Train the Regression Model (Linear Regression)
model = LinearRegression()
model.fit(X_train, y_train)
 
# Step 5: Make Predictions
y_pred = model.predict(X_test)
 
# Step 6: Model Evaluation
# Calculate Mean Squared Error (MSE)
mse = mean_squared_error(y_test, y_pred)
print(f"Mean Squared Error: {mse}")
 
# Calculate R-squared (R²) value
r2 = r2_score(y_test, y_pred)
print(f"R-squared value: {r2}")
 
star

Wed Nov 20 2024 16:43:49 GMT+0000 (Coordinated Universal Time) https://docs.praison.ai/installation/

@sweetmagic

star

Wed Nov 20 2024 16:43:14 GMT+0000 (Coordinated Universal Time) https://docs.praison.ai/installation/

@sweetmagic

star

Wed Nov 20 2024 16:00:10 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Wed Nov 20 2024 16:00:10 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Wed Nov 20 2024 15:46:44 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

Wed Nov 20 2024 15:11:53 GMT+0000 (Coordinated Universal Time)

@hi

star

Wed Nov 20 2024 15:11:24 GMT+0000 (Coordinated Universal Time)

@hi

star

Wed Nov 20 2024 15:10:55 GMT+0000 (Coordinated Universal Time)

@sem

star

Wed Nov 20 2024 15:10:19 GMT+0000 (Coordinated Universal Time)

@sem

star

Wed Nov 20 2024 15:10:05 GMT+0000 (Coordinated Universal Time)

@hi

star

Wed Nov 20 2024 15:09:28 GMT+0000 (Coordinated Universal Time)

@sem

star

Wed Nov 20 2024 15:04:44 GMT+0000 (Coordinated Universal Time)

@signup1

star

Wed Nov 20 2024 13:51:07 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Wed Nov 20 2024 13:15:25 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

Wed Nov 20 2024 13:14:24 GMT+0000 (Coordinated Universal Time) https://www.windows8facile.fr/powershell-execution-de-scripts-est-desactivee-activer/

@Hack3rmAn

star

Wed Nov 20 2024 12:54:39 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Wed Nov 20 2024 12:07:05 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Wed Nov 20 2024 10:45:18 GMT+0000 (Coordinated Universal Time)

@abcd

star

Wed Nov 20 2024 10:38:32 GMT+0000 (Coordinated Universal Time)

@abcd

star

Wed Nov 20 2024 10:20:51 GMT+0000 (Coordinated Universal Time)

@abcd

star

Wed Nov 20 2024 10:14:21 GMT+0000 (Coordinated Universal Time)

@abcd

star

Wed Nov 20 2024 10:13:50 GMT+0000 (Coordinated Universal Time)

@abcd

star

Wed Nov 20 2024 10:13:06 GMT+0000 (Coordinated Universal Time)

@abcd

star

Tue Nov 19 2024 21:29:30 GMT+0000 (Coordinated Universal Time)

@shirnunn

star

Tue Nov 19 2024 19:23:10 GMT+0000 (Coordinated Universal Time)

@shirnunn

star

Tue Nov 19 2024 19:22:32 GMT+0000 (Coordinated Universal Time)

@shirnunn

star

Tue Nov 19 2024 19:21:48 GMT+0000 (Coordinated Universal Time)

@shirnunn

star

Tue Nov 19 2024 16:39:06 GMT+0000 (Coordinated Universal Time)

@varuntej #python

star

Tue Nov 19 2024 16:38:14 GMT+0000 (Coordinated Universal Time)

@varuntej #python

star

Tue Nov 19 2024 14:18:27 GMT+0000 (Coordinated Universal Time)

@Radhwen_hajri

star

Tue Nov 19 2024 14:09:25 GMT+0000 (Coordinated Universal Time)

@esmeecodes

star

Tue Nov 19 2024 13:31:33 GMT+0000 (Coordinated Universal Time)

@usertest123890

star

Tue Nov 19 2024 11:09:48 GMT+0000 (Coordinated Universal Time)

@mateusz021202

star

Tue Nov 19 2024 11:08:59 GMT+0000 (Coordinated Universal Time)

@mateusz021202

star

Tue Nov 19 2024 11:07:59 GMT+0000 (Coordinated Universal Time)

@mkhassan

star

Tue Nov 19 2024 11:04:14 GMT+0000 (Coordinated Universal Time)

@mkhassan

star

Tue Nov 19 2024 06:22:21 GMT+0000 (Coordinated Universal Time) https://www.coinsclone.com/create-nft-marketplace-like-opensea/

@LilianAnderson #nftmarketplacedevelopment #buildnftplatform #openseaclonescript #blockchainbusinessideas #createnftmarketplace

star

Tue Nov 19 2024 06:09:21 GMT+0000 (Coordinated Universal Time)

@cseb26

star

Tue Nov 19 2024 05:15:40 GMT+0000 (Coordinated Universal Time) https://appticz.com/talabat-clone

@aditi_sharma_

star

Tue Nov 19 2024 04:48:08 GMT+0000 (Coordinated Universal Time)

@login123

star

Tue Nov 19 2024 04:47:25 GMT+0000 (Coordinated Universal Time)

@login123

star

Tue Nov 19 2024 04:47:03 GMT+0000 (Coordinated Universal Time)

@login123

star

Tue Nov 19 2024 04:46:34 GMT+0000 (Coordinated Universal Time)

@login123

star

Tue Nov 19 2024 04:45:56 GMT+0000 (Coordinated Universal Time)

@login123

star

Tue Nov 19 2024 04:45:19 GMT+0000 (Coordinated Universal Time)

@login123

star

Tue Nov 19 2024 04:44:40 GMT+0000 (Coordinated Universal Time)

@login123

star

Tue Nov 19 2024 04:44:01 GMT+0000 (Coordinated Universal Time)

@login123

star

Tue Nov 19 2024 04:43:02 GMT+0000 (Coordinated Universal Time)

@login123

star

Tue Nov 19 2024 04:42:19 GMT+0000 (Coordinated Universal Time)

@login123

Save snippets that work with our extensions

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