Snippets Collections
getUrl("https://httpstat.us/200?sleep=7000");
import React from 'react';

/**
 * Toggles the presence of a number in the selectedNumbers array state.
 *
 * @param number - The number to toggle in the selection.
 * @param setSelectedNumbers - The state setter function from useState.
 */
const toggleNumber = (
  number: number,
  setSelectedNumbers: React.Dispatch<React.SetStateAction<number[]>>
): void => {
  setSelectedNumbers((prevSelectedNumbers) => {
    if (prevSelectedNumbers.includes(number)) {
      // Number is already selected; remove it from the array
      return prevSelectedNumbers.filter((n) => n !== number);
    } else {
      // Number is not selected; add it to the array
      return [...prevSelectedNumbers, number];
    }
  });
};

// Initialize State in Your Component
const [selectedNumbers, setSelectedNumbers] = useState<number[]>([]);

// Use the toggleNumber Function
// Example usage within a component event handler
const handleNumberClick = (number: number): void => {
  toggleNumber(number, setSelectedNumbers);
};

// Implement in JSX
<button onClick={() => handleNumberClick(5)}>
  {selectedNumbers.includes(5) ? 'Deselect 5' : 'Select 5'}
</button>
ctivity_main.xml:
?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical"
        app:layoutManager="LinearLayoutManager" />

</FrameLayout>



MainActivity.kt

package com.polymath.affirmations

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.polymath.affirmations.adapter.ItemAdapter
import com.polymath.affirmations.data.Datasource

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val myDataSet = Datasource().loadAffirmations()        
       // getting the recycler view by its id
       val recyclerView: RecyclerView = findViewById(R.id.recycler_view)
       // this will pass the arraylist to our adapter
        recyclerView.adapter = ItemAdapter(this, myDataSet)
        recyclerView.setHasFixedSize(true)
    }
}

Steps to create a new layout resource file:

Right click on “layout” -- click on “new” -   select “Layout Resource File” and give file name as list_item.xml.  Finally, a new xml file is created in layout folder.





list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/item_image"
            android:layout_width="match_parent"
            android:layout_height="194dp"
            android:importantForAccessibility="no"
            android:scaleType="centerCrop" />

        <TextView
            android:id="@+id/item_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="16dp"
            android:textAppearance="?attr/textAppearanceHeadline6" />
    </LinearLayout>

Steps to create a class file in studio:

Right click on “res”  select “new”   select “kotlin class/file”






Affirmations.kt

package com.polymath.affirmations.model

import androidx.annotation.DrawableRes
import androidx.annotation.StringRes

data class Affirmation(
    @StringRes val stringResourceId: Int,
    @DrawableRes val imageResourceId: Int) {
}



DataSource class file


package com.polymath.affirmations.data

import com.polymath.affirmations.R
import com.polymath.affirmations.model.Affirmation

class Datasource {
    fun loadAffirmations(): List<Affirmation>
    {
        return listOf<Affirmation>(
            Affirmation(R.string.affirmation1, R.drawable.image1),
            Affirmation(R.string.affirmation2, R.drawable.image2),
            Affirmation(R.string.affirmation3, R.drawable.image3),
            Affirmation(R.string.affirmation4, R.drawable.image4),
            Affirmation(R.string.affirmation5, R.drawable.image5),
            Affirmation(R.string.affirmation6, R.drawable.image6),
            Affirmation(R.string.affirmation7, R.drawable.image7),
            Affirmation(R.string.affirmation8, R.drawable.image8),
            Affirmation(R.string.affirmation9, R.drawable.image9),
            Affirmation(R.string.affirmation10, R.drawable.image10),
        )
    }
}


ItemAdapter.kt

package com.polymath.affirmations.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.polymath.affirmations.R
import com.polymath.affirmations.model.Affirmation

class ItemAdapter(
    private val context: Context,
    private val dataset: List<Affirmation>
    ) : RecyclerView.Adapter<ItemAdapter.ItemViewHolder>() {

    class ItemViewHolder(private val view: View) : RecyclerView.ViewHolder(view) {
        val textView : TextView = view.findViewById(R.id.item_title)
        val imageView: ImageView = view.findViewById(R.id.item_image)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        //Create a new view
        val adapterLayout = LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, false)

        return ItemViewHolder(adapterLayout)
    }

    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
        val item = dataset[position]
        holder.textView.text = context.resources.getString(item.stringResourceId)
        holder.imageView.setImageResource(item.imageResourceId)

    }

    override fun getItemCount() = dataset.size
}
Develop Tip Calculator App with a working Calculate button.

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="186dp"
        android:layout_height="45dp"
        android:text=""
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.816" />

    <EditText
        android:id="@+id/cost"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Cost"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.417"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.023"
        tools:ignore="TouchTargetSizeCheck" />

    <RadioGroup
        android:id="@+id/RG"
        android:layout_width="200dp"
        android:layout_height="144dp"
        app:layout_constraintBottom_toTopOf="@+id/switch1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.44"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/cost"
        app:layout_constraintVertical_bias="0.385">

        <RadioButton
            android:id="@+id/radio15"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Awesome (20)" />

        <RadioButton
            android:id="@+id/radio18"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Good (18)" />

        <RadioButton
            android:id="@+id/radio20"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Average (15)" />
    </RadioGroup>


//for round tip enable/disable

    <Switch
        android:id="@+id/switch1"
        android:layout_width="409dp"
        android:layout_height="56dp"
        android:layout_marginTop="240dp"
        android:text="Round Up Tip"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/cost"
        app:layout_constraintVertical_bias="0.0"
        tools:ignore="HardcodedText,UseSwitchCompatOrMaterialXml" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Calculate Tip"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/switch1" />

</androidx.constraintlayout.widget.ConstraintLayout>


MainActivity.kt
package com.example.calculatetip

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.calculatetip.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.button.setOnClickListener() {
            calculateTip()
        }
    }
    fun calculateTip()
    {
        val cost=(binding.cost.text.toString()).toDouble()
        val selected=binding.RG.checkedRadioButtonId
        val tipPercent=when(selected)
        {
            R.id.radio15 -> 0.15
            R.id.radio18 -> 0.18
            else -> 0.20
        }
        var tip=tipPercent*cost
        if(binding.switch1.isChecked)
        {
            tip=kotlin.math.ceil(tip)
        }
        binding.textView.text=tip.toString()
    }
}



build.gradle:

In  gradle  scripts -> select build.gradle(Module:app) file -> update the higlighted build features lines of code.
Finally Sync Now .

Then Run the emulator


plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
}

android {
    namespace 'com.example.calculatetip'
    compileSdk 33

    defaultConfig {
        applicationId "com.example.calculatetip"
        minSdk 24
        targetSdk 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    buildFeatures{
        viewBinding="true"
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'com.google.android.material:material:1.9.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
STEP 1: Create an Empty Activity
STEP 2: Create a raw resource folder
Create a raw resource folder under the res folder and copy one of 
the .mp3 file extension.
Right Click on "raw" folder ----> select "new" ---> click on "Android 
Resource Directory" ----> Change resource type values to "raw" ----> 
then finally click "OK".
Download required audio MP3 file (Size <500kb approximately) from 
Internet , right click and Paste it in "raw" folder whatever newly created.
--------------------------------------------------------------------
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity"
 tools:ignore="HardcodedText">
 <TextView
 android:id="@+id/headingText"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="32dp"
 android:text="MEDIA PLAYER"
 android:textSize="18sp"
 android:textStyle="bold" />
 <LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_below="@id/headingText"
 android:layout_marginTop="16dp"
 android:gravity="center_horizontal">
 <Button
 android:id="@+id/stopButton"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginEnd="8dp"
 android:backgroundTint="@color/colorPrimary"
 android:text="STOP"
 android:textColor="@android:color/white"
 tools:ignore="ButtonStyle,TextContrastCheck" />
 <Button
 android:id="@+id/playButton"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginEnd="8dp"
 android:backgroundTint="@color/colorPrimary"
 android:text="PLAY"
 android:textColor="@android:color/white"
 tools:ignore="ButtonStyle,TextContrastCheck" />
 <Button
 android:id="@+id/pauseButton"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:backgroundTint="@color/colorPrimary"
 android:text="PAUSE"
 android:textColor="@android:color/white"
 tools:ignore="ButtonStyle,TextContrastCheck" />
 </LinearLayout>
</RelativeLayout>
MainActivity.kt
// As per your application (or) file name package name will displayed
package com.example.mediaplayer 
import android.media.MediaPlayer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
class MainActivity : AppCompatActivity() {
 override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)
 setContentView(R.layout.activity_main)
 // create an instance of mediplayer for audio playback
 val mediaPlayer: MediaPlayer = 
MediaPlayer.create(applicationContext, R.raw.music)
 // register all the buttons using their appropriate IDs
 val bPlay: Button = findViewById(R.id.playButton)
 val bPause: Button = findViewById(R.id.pauseButton)
 val bStop: Button = findViewById(R.id.stopButton)
 // handle the start button to
 // start the audio playback
 bPlay.setOnClickListener {
 // start method is used to start
 // playing the audio file
 mediaPlayer.start()
 }
 // handle the pause button to put the
 // MediaPlayer instance at the Pause state
 bPause.setOnClickListener {
 // pause() method can be used to
 // pause the mediaplyer instance
 mediaPlayer.pause()
 }
 // handle the stop button to stop playing
 // and prepare the mediaplayer instance
 // for the next instance of play
 bStop.setOnClickListener {
 // stop() method is used to completely
 // stop playing the mediaplayer instance
 mediaPlayer.stop()
 // after stopping the mediaplayer instance
 // it is again need to be prepared
 // for the next instance of playback
 mediaPlayer.prepare()
 }
 }
}
7.  Create a Dice Roller application that has a button to roll a dice and update the image on the screen.

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

    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/dice_1" />

    <Button
        android:id="@+id/b1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ROLL"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/iv" />

</androidx.constraintlayout.widget.ConstraintLayout>


MainActivity.kt
package com.example.roll_dice

//import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView

class MainActivity : AppCompatActivity() {
   // @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
       val btn:Button=findViewById(R.id.b1)

        btn.setOnClickListener {
            rollDice()
        }
    }
    private fun rollDice(){
        val dice=Dice(6)
        val diceRoll=dice.roll()
        val imgv:ImageView=findViewById(R.id.iv)
        val drawableResource=when(diceRoll){
            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
        }
        imgv.setImageResource(drawableResource)
    }
}
class Dice(private val numSides:Int){
    fun roll():Int{
        return (1..numSides).random()
    }
}
1.Develop an Android  Application to display message using Toast Class.

Activity_main.xml file

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


    <!--  android:inputType="textPersonName|textPassword"    It will take text as password with asterisk symbol and combination of characters and numbers -->

    <EditText
        android:id="@+id/etView"
        android:layout_width="380dp"
        android:layout_height="62dp"
        android:layout_marginTop="84dp"
        android:layout_marginBottom="147dp"
        android:ems="10"
        android:hint="Enter Name"
        android:inputType="textPersonName|textPassword"
        android:textColor="#9C27B0"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@+id/btn1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.483"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="400dp"
        android:text="Click Here"
        android:gravity="center_horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.435"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/etView"
        app:layout_constraintVertical_bias="1.0" />

    <TextView
        android:id="@+id/txtView"
        android:layout_width="361dp"
        android:layout_height="70dp"
        android:text="Text View"
        android:textColor="#E91E63"
        android:textSize="30dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn1" />


</androidx.constraintlayout.widget.ConstraintLayout>



MainActivity.kt

package com.example.myapp_lakshmi

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast

class MainActivity : AppCompatActivity() {

    //Declaration of Widgets

    lateinit var editText:EditText
    lateinit var btn:Button
    lateinit var textView:TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

       //findViewById() method is used to find an existing view in your XML layout by its android:id attribute.

        editText=findViewById(R.id.etView)
        btn=findViewById(R.id.btn1)
        textView=findViewById(R.id.txtView)
        btn.setOnClickListener(){

            // A toast provides simple feedback about an operation in a small popup.

            Toast.makeText(this,"button Clicked",Toast.LENGTH_LONG).show()

              //Reading/Copying the text from edit text and writing/displaying/Pasting into the textview

            textView.text=editText.text.toString()
        }
    }
}



Output:





2. Develop an Android  Application showing clipboard by performing Copy and Paste Operations.

Activity_main.xml file

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


    <!--  android:inputType="textPersonName|textPassword"    It will take text as password with asterisk symbol and combination of characters and numbers -->

    <EditText
        android:id="@+id/etView"
        android:layout_width="380dp"
        android:layout_height="62dp"
        android:layout_marginTop="84dp"
        android:layout_marginBottom="147dp"
        android:ems="10"
        android:hint="Enter Name"
        android:inputType="textPersonName|textPassword"
        android:textColor="#9C27B0"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@+id/btn1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.483"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="400dp"
        android:text="Click Here"
        android:gravity="center_horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.435"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/etView"
        app:layout_constraintVertical_bias="1.0" />

    <TextView
        android:id="@+id/txtView"
        android:layout_width="361dp"
        android:layout_height="70dp"
        android:text="Text View"
        android:textColor="#E91E63"
        android:textSize="30dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn1" />


</androidx.constraintlayout.widget.ConstraintLayout>



MainActivity.kt

package com.example.myapp_lakshmi

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast

class MainActivity : AppCompatActivity() {

    //Declaration of Widgets

    lateinit var editText:EditText
    lateinit var btn:Button
    lateinit var textView:TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

       //findViewById() method is used to find an existing view in your XML layout by its android:id attribute.

        editText=findViewById(R.id.etView)
        btn=findViewById(R.id.btn1)
        textView=findViewById(R.id.txtView)
        btn.setOnClickListener(){

            // A toast provides simple feedback about an operation in a small popup.

            Toast.makeText(this,"button Clicked",Toast.LENGTH_LONG).show()

            //Reading/Copying the text from edit text and writing/displaying/Pasting into the textview

            textView.text=editText.text.toString()
        }
    }
}
activity_main.xml:

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


    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CLICK HERE"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView2"
        app:layout_constraintVertical_bias="0.5"
        tools:ignore="MissingConstraints" />

    <EditText
        android:id="@+id/editTextText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="text"
        android:minHeight="48dp"
        android:text="Name"
        app:layout_constraintBottom_toTopOf="@+id/imageView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/birthday1"
        app:layout_constraintBottom_toTopOf="@+id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextText"
        app:layout_constraintVertical_bias="0.5" />

</androidx.constraintlayout.widget.ConstraintLayout>


MainActivity.kt:
package com.example.firstapp

import android.annotation.SuppressLint
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.collection.emptyLongSet
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.firstapp.ui.theme.FirstappTheme

class MainActivity : ComponentActivity() {
    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        //declaration
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //initialize

        val btn: Button =findViewById(R.id.button)
        val edt: EditText=findViewById(R.id.editTextText)
        val img: ImageView=findViewById(R.id.imageView2)
        btn.setOnClickListener {
              var choice=edt.text.toString()
               when(choice)
               {
                   "birthday1"->img.setImageResource(R.drawable.birthday1)
                   "birthday2"->img.setImageResource(R.drawable.birthday2)
                   else->img.setImageResource(R.drawable.birthday3)
               }
              Toast.makeText(this, "image loading please wait", Toast.LENGTH_SHORT).show()


        }

    }

}
activity_main.xml

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

    <EditText
        android:id="@+id/editTextTextPersonName"
        android:layout_width="303dp"
        android:layout_height="66dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name"
        app:layout_constraintBottom_toTopOf="@+id/editTextTextPersonName2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editTextTextPersonName2"
        android:layout_width="300dp"
        android:layout_height="72dp"
        android:layout_marginBottom="136dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name"
        app:layout_constraintBottom_toTopOf="@+id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.486"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="232dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>



MainActivity.kt

package com.example.newlogin

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

class MainActivity : AppCompatActivity() {
    private lateinit var userET: EditText
    private lateinit var passET: EditText
    //private lateinit var resetBtn: Button
    private lateinit var loginBtn: Button
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        userET = findViewById(R.id.editTextTextPersonName)
        passET = findViewById(R.id.editTextTextPersonName2)
        loginBtn=findViewById(R.id.button)
        loginBtn.setOnClickListener {
            if(userET.text.toString()=="cvr" && passET.text.toString()=="cvr123")
            {
                val intent=Intent(this,MainActivity2::class.java)
                intent.putExtra("Username",userET.text.toString())
                intent.putExtra("Password",passET.text.toString())
                startActivity(intent)
                Toast.makeText(this,"login success",Toast.LENGTH_LONG).show()
            }
            else
            {
                Toast.makeText(this,"error login ",Toast.LENGTH_LONG).show()
            }
        }
    }
}


activity_main2.xml

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="162dp"
        android:layout_height="59dp"
        android:text="Welcome"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>


MainActivity2.kt

package com.example.newlogin

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView

class MainActivity2 : AppCompatActivity() {
    private lateinit var resultTV:TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)

        resultTV=findViewById(R.id.textView1)
        val intent: Intent =intent
        var user=intent.getStringExtra("Username")
        var pass=intent.getStringExtra("Password")
        resultTV.text=user+" " +pass

    }
}

Note: In AndroidManifest.xml file ,update the content as follows:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.Loginintent"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".HomeActivity1"/>
    </application>

</manifest>
ACTIVITY_MAIN.XML:

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

<TextView
        android:id="@+id/textview"
        android:layout_width="303dp"
        android:layout_height="66dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="ACTIVITY LIFE CYCLE METHODS"
       app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

MAINACTIVITY.kt 

package com.example.myapp_activitylifecyclemethods 
import androidx.appcompat.app.AppCompatActivity 
import android.os.Bundle 
import android.widget.Toast 
class MainActivity : AppCompatActivity() 
{ 
override fun onCreate(savedInstanceState: Bundle?)
 { 
super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) 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 onPause() 
{ 
super.onPause()
 Toast.makeText(applicationContext,"ONPAUSE() CALLED",Toast.LENGTH_SHORT).show() 
} 
override fun onStop() 
{ 
super.onStop() 
Toast.makeText(applicationContext,"ONSTOP() CALLED",Toast.LENGTH_SHORT).show()
 } 
fun onDestroy() 
{ 
super.onDestroy() 
Toast.makeText(applicationContext,"ONDESTROY() CALLED",Toast.LENGTH_SHORT).show() 
} 
} 
3.Create “Hello World” application. That will display “Hello World” in the middle of the screen in the red color with white background.

ACTIVITY_MAIN.XML:

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

<TextView
        android:id="@+id/textview"
        android:layout_width="303dp"
        android:layout_height="66dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="MAD LAB”
        android:textColor=”#289428”  
        android:textAllCaps=”true”
        android:textSize=”20dp” 
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

MAINACTIVITY.kt 

package com.example.helloworld 
import androidx.appcompat.app.AppCompatActivity 
import android.os.Bundle 
//Bundle is a class in android studio used to transfer data from one UI component activity to another UI component activity to another UI component activity.

import android.widget.Toast 
class MainActivity : AppCompatActivity() 
{ 
  override fun onCreate(savedInstanceState: Bundle?)
 { 
//Bundle defines 2 methods onFreeze() and onCreate() 
onFreeze() assigns value to UI component in design phase and
onCreate() takes parameter of component during runtime
super.onCreate(savedInstanceState) setContentView(R.layout.activity_main)
//R is a resource set in activity_main.xml and used in kt file with resource id
}
}
Q) Create an app to navigate from one activity to another activity using intent.
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome to MAD Lab"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5"
        tools:ignore="HardcodedText" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/floatingActionButton"
        android:layout_width="56dp"
        android:layout_height="76dp"
        android:clickable="true"
        app:fabSize="auto"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.5"
        app:maxImageSize="30dp"
        app:srcCompat="@drawable/baseline_add_24"
        tools:ignore="ContentDescription,KeyboardInaccessibleWidget,SpeakableTextPresentCheck" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt:
package com.example.intentdemoandroidapp

import android.content.Intent
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.floatingactionbutton.FloatingActionButton

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        var t:TextView=findViewById(R.id.textView)
        var f:FloatingActionButton=findViewById(R.id.floatingActionButton)
        f.setOnClickListener()
        {
            var i=Intent(this,MainActivity2::class.java)
            startActivity(i)
        }
    }
}

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

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CSE-A"
        android:textSize="34sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5"
        tools:ignore="HardcodedText" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity2.kt:
package com.example.intentdemoandroidapp

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

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

1)Create empty Activity

2)Create layout folder and add “activity_main.xml” file in it

3)How to create Navigation folder and navigation graph:
i)Add dependencies in build.gradle file
implementation("androidx.constraintlayout:constraintlayout-compose:1.0.0-alpha08")
implementation("androidx.navigation:navigation-fragment-ktx:2.3.5")
implementation("androidx.navigation:navigation-ui-ktx:2.3.5")
implementation("androidx.navigation:navigation-dynamic-features-fragment:2.3.5")

ii)Create navigation folder and add nav_graph.xml in it
iii)Create “new destination” in nav_graph.xml then select 2 blank fragments and name it as “HomeFragment” and “DataFragment”

4)Add the following steps in activity_main.xml:
i)Add constraint layout
ii)Drag and drop fragment container view and select “HomeFragment.kt”
add:navGraph=”@navigation/nav_graph”

5)Add the following steps in HomeFragment in xml:
i)Add Constraint View
ii)Add Text View
iii)Add Button 

6)Add the following steps in DataFragment in xml:
i)Add Constraint View
ii)Add Text View
iii)Add Button 
package com.example.birthdayapp

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


class MainActivity: AppCompatActivity(){

    lateinit var btn : Button
    lateinit var editText: EditText
    lateinit var img :ImageView

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

        btn = findViewById(R.id.button)
        editText = findViewById(R.id.editTextText)
        img = findViewById(R.id.imageView)

        btn.setOnClickListener(){
            Toast.makeText(this,"Button clicked",Toast.LENGTH_LONG).show()

            when(editText.text.toString()){
                "HappyBDAY"->img.setImageResource(R.drawable.happybday)
                "HappyBDAY2"->img.setImageResource(R.drawable.happybday2)
            }

        }
    }


}
import 'dart:async';
import 'package:chopper/chopper.dart';
import 'dart:io';

import 'api_errors.dart';


class ErrorHandlerInterceptor implements Interceptor {
  @override
  FutureOr<Response<BodyType>> intercept<BodyType>(
      Chain<BodyType> chain) async {
    try {
      final response = await chain.proceed(chain.request);

      if (!response.isSuccessful) {
        final statusCode = response.statusCode;
        switch (statusCode) {
          case 400:
          case 403:
          case 405:
          case 409:
            throw ExceptionWithMessage("Ошибка: ${response.error.toString()}");
          case 401:
            throw UnauthorisedException();
          default:
            throw Exception("Неизвестная ошибка: ${response.error}");
        }
      }

      return response;
    } on SocketException {
      throw const ExceptionWithMessage(
          "Сетевая ошибка: Проверьте подключение.");
    } on ExceptionWithMessage catch (e) {
      throw ExceptionWithMessage("Сообщение об ошибке: ${e.message}");
    } on Exception catch (e) {
      throw Exception("Общая ошибка: $e");
    }
  }
}
1.	Sample Program
fun main() 
{
    println("Hello, world!!!")
}
2.main() function with parameters
fun main(args : Array<String>) {
println("Hello World")
}
3. val / var demonstration
fun main()
{
var name = "Kotlin"          // String (text)
val birthyear = 2023         // Int (number)

println(name)          // Print the value of name
println(birthyear)     // Print the value of birthyear

}
OR
// val / var demonstration
fun main()
{
var name: String = "KOTLIN CSE B" // String
val birthyear: Int = 2023 // Int

println(name)
println(birthyear)

}
OR
// val / var demonstration
fun main()
{
var name: String 
    name= "KOTLIN CSE B" // String
val birthyear: Int = 2023 // Int
println(name)
println(birthyear)
}
//  var demonstration
fun main()
{
var name= "CSE B"
 name = "CVR"  //  can be reassigned
println(name)   
}


//  val demonstration
fun main()
{
val name= "CSE B"
 name = "CVR"  //  cannot be reassigned
println(name)   
}

4.DATA TYPE demonstration
fun main()
{
val a: Int = 5                // Int
val b: Double = 5.99        // Double
val c: Char = 'v'          // Char
val d: Boolean = true     // Boolean
val e: String = "CSE B"      // String
val f: Float = 100.00f      // float
println("a value is:" +a)
println("b value is:" +b)
println("c value is:" +c)
println("d value is:" +d)
println("e value is:" +e) 
println("f value is:" +f)
}
5.escape sequences of character demonstration
fun main()
{
println('\n') //prints a newline character
println('\t') //prints a  tab character
println('\b') //prints a backspace character
println('\r') //prints a form feed character
println('\'') //prints a single quote character
println('\"') //prints a double quote character
println('\$') //prints a dollar $ character
println('\\') //prints a back slash \ character
}
6.ARRAY  demonstration
fun main()
{
  val  n:IntArray = intArrayOf(1, 2, 3, 4, 5)
 println("Value at 3rd position : " + n[2])
}
7.TYPE CONVERSION demonstration
fun main()
{
    val x: Int = 100
   val y: Long = x.toLong()
   println(y)
}
8.ARTHIMETIC OPERATOR demonstration
fun main()
{
    var sum1 = 100 + 50       // 150 (100 + 50)
var sum2 = sum1 + 250     // 400 (150 + 250)
var sum3 = sum2 + sum2    // 800 (400 + 400)
println(sum3)
}
9.ASSIGNMENT OPERATOR demonstration
fun main()
{
    var sum1 = 100       // ASSIGN A VALUE
    println(sum1)
}
10.COMPARISION  OPERATOR demonstration
fun main() {  
  var x = 5
 var y = 3
  println(x > y) // returns true because 5 is greater than 3
}
11.logical  OPERATOR demonstration
fun main() {  
    var x = 5
  println(x > 3 && x < 10) // returns true because 5 is greater than 3 AND 5 is less than 10

}
12.STRING demonstration
fun main() {  
    var a:String="CSE B"
  println(a[2]) // DISPLAYS CHARACTER AT LOACTION OR INDEX 2

}
13.IF ELSE demonstration
fun main() {  
  val x = 20
val y = 18
if (x > y) {
  println( "x is greater than y" )
}
else {
        println( "x is lesser than y" ) 
    } }
14.WHEN demonstration
fun main() {  
  val day = 4
  val result = when (day) {
  1 -> "Monday"
  2 -> "Tuesday"
  3 -> "Wednesday"
  4 -> "Thursday"
  5 -> "Friday"
  6 -> "Saturday"
  7 -> "Sunday"
  else -> "Invalid day."
}
println(result)         // DISPLAYS OUTPUT AS "Thursday"
}
15.WHILE Loop demonstration
fun main() {  
  var i = 0
while (i < 5) {
  println(i)
  i++
} 
}
16.DO WHILE LOOP  demonstration
fun main() { 
    var i=0
 do {
  println(i)
  i++
  }
while (i < 5) 
}
17.FOR  LOOP  demonstration
fun main() { 
    val cse = arrayOf("CSE A", "CSE B", "CSE C", "CSE D")
for (x in cse) {
  println(x)
} 
}
18.BREAK  demonstration
fun main() { 
   var i = 0
while (i < 10) {
  println(i)
  i++
  if (i == 4) {
    break
  }
}
19.CONTINUE  demonstration
fun main() { 
  var i = 0
while (i < 10) 
    {
  if (i == 4) 
    {
    i++
    continue   
  }
  println(i)
  i++
}  
}
20.RANGE  demonstration
fun main() { 
for (n in 5..15) {
  println(n)
} 
}
21.ARRAY  demonstration
fun main() { 
val  cse = arrayOf("CSE A", "CSE B", "CSE C", "CSE D")
println(cse.size)  // check array length or size
for (x in cse) 
{
  println(x)          
 }
println(cse[0])    // You can access an array element by referring to the index number, inside square brackets

if ("CSE B" in cse) 
{
  println("It exists!") 
} 
    else 
{
  println("It does not exist.")  
 }    
 }
section {
  margin-top: 20px;
  margin-bottom: 20px;
}

/* If there's only one section, remove margins */
section:first-of-type:last-of-type {
  margin-top: 0;
  margin-bottom: 0;
}
public class Person {
    // Attributs privés
    private String name;
    private int age;

    // Constructeur
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getter pour l'attribut 'name'
    public String getName() {
        return name;
    }

    // Setter pour l'attribut 'name'
    public void setName(String name) {
        this.name = name;
    }

    // Getter pour l'attribut 'age'
    public int getAge() {
        return age;
    }

    // Setter pour l'attribut 'age'
    public void setAge(int age) {
        if (age > 0) { // Exemple de vérification
            this.age = age;
        }
    }
}
public class Person {
    // Attributs privés
    private String name;
    private int age;

    // Constructeur
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getter pour l'attribut 'name'
    public String getName() {
        return name;
    }

    // Setter pour l'attribut 'name'
    public void setName(String name) {
        this.name = name;
    }

    // Getter pour l'attribut 'age'
    public int getAge() {
        return age;
    }

    // Setter pour l'attribut 'age'
    public void setAge(int age) {
        if (age > 0) { // Exemple de vérification
            this.age = age;
        }
    }
}
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 {
            ImageTheme {

                Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
                    ImageAndText()
                }
            }
        }
    }
}
private val LightColorScheme = lightColorScheme()

@Composable
fun ImageTheme(content: @Composable () -> Unit) {
    MaterialTheme(
        colorScheme = LightColorScheme,
        content = content
    )
}


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


@Preview(showBackground = true)
@Composable
fun PreviewImageAndText() {
    ImageAndText()
}
const pluckDeep = key => obj => key.split('.').reduce((accum, key) => accum[key], obj)
​
const compose = (...fns) => res => fns.reduce((accum, next) => next(accum), res)
​
const unfold = (f, seed) => {
  const go = (f, seed, acc) => {
    const res = f(seed)
    return res ? go(f, res[1], acc.concat([res[0]])) : acc
  }
  return go(f, seed, [])
}
const pluckDeep = key => obj => key.split('.').reduce((accum, key) => accum[key], obj)
​
const compose = (...fns) => res => fns.reduce((accum, next) => next(accum), res)
​
const unfold = (f, seed) => {
  const go = (f, seed, acc) => {
    const res = f(seed)
    return res ? go(f, res[1], acc.concat([res[0]])) : acc
  }
  return go(f, seed, [])
}
/// <summary>
    /// This is the custom lookup code for the LocationSite financial dimension field on the user prompt dialog
    /// </summary>
    /// <param name = "_control"></param>
    private void dimLookup(FormStringControl _control)
    {
        
        Query query = new Query();
        QueryBuildDataSource qbdsDimensionFinancialTag = query.addDataSource(tableNum(DimensionFinancialTag));
        QueryBuildRange qbrFinancialTagCategory = qbdsDimensionFinancialTag.addRange(fieldNum(DimensionFinancialTag, FinancialTagCategory));
        qbrFinancialTagCategory.value(strFmt('%1', DimensionAttribute::findByName(dimName, false).financialTagCategory()));

        SysTableLookup sysTableLookup = sysTableLookup::newParameters(tableNum(DimensionFinancialTag), _control,true);
        sysTableLookup.addLookupfield(fieldNum(DimensionFinancialTag, Value), true);
        sysTableLookup.addLookupfield(fieldNum(DimensionFinancialTag, Description));
        sysTableLookup.addSelectionField(fieldNum(DimensionFinancialTag, FinancialTagCategory));
        sysTableLookup.parmQuery(query);

        sysTableLookup.performFormLookup();
    }
docker-compose -f /Users/azizi/Sites/labelident/.ddev/.ddev-docker-compose-full.yaml down
docker container prune -f
docker image prune -f
docker volume prune -f
COMPOSE_PROJECT_NAME=ddev-labelident docker-compose -f /Users/azizi/Sites/labelident/.ddev/.ddev-docker-compose-full.yaml up -d
class Greeting {
    companion object {
        var name: String = ""
            get() = field
            set(value) {
                field = value
            }
        var message: String = ""
            get() = field
            set(value) {
                field = value
            }
    }
}

fun main(args: Array<String>) {
    Greeting.name = "h"
    Greeting.message = "y"
    println(Greeting.name)
    println(Greeting.message)
}
import kotlin.math.PI
import kotlin.math.sqrt

fun main() {
    val squareCabin = SquareCabin(6, 50.0)
    val roundHut = RoundHut(3, 10.0)
    val roundTower = RoundTower(4, 15.5)

    println("\nSquare Cabin\n============")
    squareCabin.printDetails()

    println("\nRound Hut\n=========")
    roundHut.printDetails()
    println("Has room? ${roundHut.hasRoom()}")
    roundHut.getRoom()
    println("Has room? ${roundHut.hasRoom()}")
    println("Carpet size: ${roundHut.calculateMaxCarpetLength()}")

    println("\nRound Tower\n==========")
    roundTower.printDetails()
    println("Carpet Length: ${roundTower.calculateMaxCarpetLength()}")
}

// Base class for all dwellings
abstract class Dwelling(private var residents: Int) {
    abstract val buildingMaterial: String
    abstract val capacity: Int

    abstract fun floorArea(): Double

    fun hasRoom(): Boolean = residents < capacity

    fun getRoom() {
        if (hasRoom()) {
            residents++
            println("You got a room!")
        } else {
            println("Sorry, no rooms left.")
        }
    }

    fun printDetails() {
        println("Material: $buildingMaterial")
        println("Capacity: $capacity")
        println("Floor area: ${floorArea()}")
    }
}

// SquareCabin subclass
class SquareCabin(residents: Int, val length: Double) : Dwelling(residents) {
    override val buildingMaterial = "Wood"
    override val capacity = 6

    override fun floorArea(): Double = length * length
}

// RoundHut subclass
open class RoundHut(residents: Int, val radius: Double) : Dwelling(residents) {
    override val buildingMaterial = "Straw"
    override val capacity = 4

    override fun floorArea(): Double = PI * radius * radius

    fun calculateMaxCarpetLength(): Double = sqrt(2.0) * radius
}

// RoundTower subclass
class RoundTower(residents: Int, radius: Double, val floors: Int = 2) : RoundHut(residents, radius) {
    override val buildingMaterial = "Stone"
    override val capacity = floors * 4

    override fun floorArea(): Double = super.floorArea() * floors
}
// ReversePartial reverses a portion of a slice in place from start to end (-1 for end of list) indices.
func ReversePartial[T any](arr []T, start, end int) error {
	if end == -1 {
		end = len(arr) - 1
	}
	// Validate indices
	if start < 0 || end >= len(arr) || start >= end {
		return fmt.Errorf("Invalid start or end indices")
	}

	for start < end {
		arr[start], arr[end] = arr[end], arr[start] // Swap elements
		start++
		end--
	}
	return nil
}
// Reverse returns a new slice with the elements of the input slice in reverse order.
func Reverse[T any](arr []T) []T {
	n := len(arr)
	reversed := make([]T, n) // Create a new slice of the same length

	for i := 0; i < n; i++ {
		reversed[i] = arr[n-1-i] // Copy elements from end to start
	}

	return reversed
}
// Reverse reverses any slice of any type.
func ReverseInplace[T any](arr []T) {
	n := len(arr)
	for i := 0; i < n/2; i++ {
		arr[i], arr[n-1-i] = arr[n-1-i], arr[i]
	}
}
$ipAuth = $_SERVER['REMOTE_ADDR'];


        $firstName = 'trialMahesh';
        $lastName = 'test';
        $email = 'maheshtrialnew@gmail.com';
        $organisation = htmlspecialchars('mytrialorg');
        $phone = htmlspecialchars('0405550505');


        $username = $organisation;
        $username = mb_strtolower($username);
        $username = preg_replace('/[^a-zA-Z]+/', '', $username);

        $extraNumber = 1;

        while (User::findByUsernameOrAlias($username)) {
            $extraNumber++;
            preg_match('~^[^-]+~', $username, $matches);
            $username = $matches[0].'-'.$extraNumber;
        }

        $length = 9;
        $str = '';
        $characters = array_merge(range('A', 'Z'), range('a', 'z'), range('0', '9'));
        $max = count($characters) - 1;

        for ($i = 0; $i < $length; $i++) {
            $rand = mt_rand(0, $max);
            $str .= $characters[$rand];
        }

        $password = 'Mahesh123#';
        $expiryDate = Carbon::today()->addDays(31)->format('Y-m-d');

        $userDetails = [
            'username' => $username,
            'email' => $email,
            'password' => Hash::make($password),
            'phone' => $phone,
            'name' => $firstName . ' ' . $lastName,
            'organisation' => $organisation,
            'plan' => 'trial',
            'status' => 'active',
            'uuid' => (string) Str::uuid(),
            'expiry' => $expiryDate,
        ];

        $user = User::create($userDetails);
        $user->createOwnOrganisation();

        event(new Registered($user));

        $trialFormStatus = new UserTrialFormstatus;
        $trialFormStatus->user_id = $user->id;
        $trialFormStatus->formstatus = 'good';
        $trialFormStatus->save();


        $trialDevice = new UserTrialDevice;
        $trialDevice->user_id = $user->id;
        $trialDevice->device = '127.7.7.1';
        $trialDevice->save();

       

        dd($user);
>
jQuery(function($){
    $("#filterApply").on("click", ()=>{
        $("#off-canvas-a3ae61b").removeClass("show").addClass("hide");
        setTimeout(function() {
            $("#off-canvas-a3ae61b").hide();
        }, 1000);
    })
    
    $("#openFilter").on("click", ()=>{
        $("#off-canvas-a3ae61b").removeClass("hide").addClass("show");
        $("#off-canvas-a3ae61b").show();
    })
});



<script>
jQuery( document ).ready(function($){
   $(document).on('click','.elementor-location-popup a', function(event){
      elementorProFrontend.modules.popup.closePopup( {}, event);
   })
});
</script>
function theme_xyz_header_metadata() {
    
    // Post object if needed
    // global $post;
    
    // Page conditional if needed
    // if( is_page() ){}
    
  ?>
    
    <meta name="abc" content="xyz" />
    
  <?php
    
}
add_action( 'wp_head', 'theme_xyz_header_metadata' );
add_filter('automatic_updater_disabled', '__return_true');
add_filter('auto_update_core', '__return_false');
add_filter('pre_site_transient_update_core', '__return_null');
add_filter('pre_site_transient_update_plugins', '__return_null');
add_filter('pre_site_transient_update_themes', '__return_null');

// Disable plugin updates
remove_action('load-update-core.php', 'wp_update_plugins');
add_filter('pre_site_transient_update_plugins', '__return_null');

// Disable plugin update checks
add_action('admin_init', function() {
    remove_action('admin_init', '_maybe_update_plugins');
    remove_action('wp_update_plugins', 'wp_update_plugins');
    remove_action('load-plugins.php', 'wp_update_plugins');
});

// Disable theme updates
remove_action('load-update-core.php', 'wp_update_themes');
add_filter('pre_site_transient_update_themes', '__return_null');

// Disable theme update checks
add_action('admin_init', function() {
    remove_action('admin_init', '_maybe_update_themes');
    remove_action('wp_update_themes', 'wp_update_themes');
    remove_action('load-themes.php', 'wp_update_themes');
});

// Disable all automatic updates
add_filter('automatic_updater_disabled', '__return_true');

// Disable update notifications
add_filter('admin_init', function() {
    remove_action('admin_notices', 'update_nag', 3);
});
function updateIcons(update) {
    const icons = {
      ppt: "powerpoint",
      pptx: "powerpoint",
      doc: "word",
      docx: "word",
      xls: "xcel",
      xlsx: "xcel",
      pdf: "pdf",
      default: "page",
    };

    return icons[update] ?? "page";
  }
    
     <section class="fileDownload__wrapper">
          <div class="fileDownload__icon icon__${updateIcons(fileType)}"
			aria-hidden="true"></div>
       </section>`;
    
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":xero-unicorn: Reminder: End of Year Celebration – Registrations :xero-unicorn:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "*Hi Melbourne!* \n We hope you're getting excited for a night of magic! \n\n Our event is only *4 WEEKS AWAY!* This is your friendly reminder to make sure you register to our end of year event by the 14th of November 2024! \n\n In today's post we've added in some answers to the commonly asked questions! Please read below."
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"fields": [
				{
					"type": "mrkdwn",
					"text": "*📅 When:*\nThursday 28th November"
				},
				{
					"type": "mrkdwn",
					"text": "*📍 Where:*\n<https://www.google.com/maps/place/The+Timber+Yard/@-37.8331021,144.918894,17z/data=!3m1!4b1!4m6!3m5!1s0x6ad667735e56fcab:0x966480f06c58c00c!8m2!3d-37.8331021!4d144.9214743!16s/g/11gyy7sy4c?entry=ttu&g_ep=EgoyMDI0MDkxOC4xIKXMDSoASAFQAw==/|*The Timber Yard*> \n351 Plummer Street, Port Melbourne"
				},
				{
					"type": "mrkdwn",
					"text": "*⏰ Time:*\n4PM - 10PM"
				}
			]
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "*🎟 RSVP Now:*\nPlease click <https://xero-wx.jomablue.com/reg/store/eoy_mel|here> to RSVP! \nMake sure you RSVP by *_14th November 2024_*"
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":question:Got more questions? See the <https://docs.google.com/document/d/1iygJFHgLBRSdAffNsg3PudZCA45w6Wit7xsFxNc_wKM/edit|FAQs> doc or ask away in this thread!\n\n We can’t wait to celebrate with you! :partying_face: :xero-love:"
			}
		}
	]
}
///////////////***** SCOPES IN JS *************/////////////

let a = 200
if(true){
    let a = 100
    console.log("inner a is  ",a);// 100 (BLOCK SCOPE)
}
console.log("outer a is  ",a); // 200 (GLOBAL SCOPE)

/*

BLOCK SCOPE 
The space inside the curly braces is called a block space.
variable assigned in block scope only accessable in block scope not in global scope.


Global SCOPE 
The space outside the curly braces is called a Global space.
variable assigned in global scope  accessable in both block scope and  global scope.

*/
///////////////****** FUNCTIONS IN JS  ********////////////////////


/// Basic function 
function NAME(){
    console.log("i");
    console.log("love");
    console.log("you");
}
NAME() /// calling the function 

// function of adding two number 
function add2number(number1 , number2){ // number1 , number2 are called parameters
    console.log(number1 + number2);
}
add2number(20,30)  // here what we pass are called arguments , here 20 ,30.




// function of adding two number (SECOND METHOD )
function addtwonumber(number1 , number2){ 
    let result = number1 + number2
    return result
    console.log("om"); /// this will not execute because it is after return function
}

const result = addtwonumber(3,5)
console.log("result is equal to", result); ///8 


/// function of adding two number (THIRD METHOD )

function addtwonumbers(number1 , number2){ 
   return number1 + number2
    
}

const result2 = addtwonumbers(7,5)
console.log("result is equal to", result2); ///12

//////// basic confusion in terms of return function 

function login(username="sammy"){
    if(username === undefined){
        console.log("please enter your name ");
        return
    }
    return `${username} just logged in `
    
}
console.log(login("TANISHQ DHINGRA" )); //TANISHQ DHINGRA just logged in 
console.log(login()); //sammy just logged in 
///////////////****** OBJECTS IN JS (PART 3) ********////////////////////


/// de structuring data 
const course ={
    coursename:"udemy js ",
    price: "999",
    courseIntructor: "hitesh"
    
}

const {courseIntructor: Inst} = course  // getting value of courseInstructor from course and refreing it from Inst key
console.log(Inst); // hitesh


///////////////////////////**** JSON API *******////////////////
  
/// this is Json 
/*{ 
    "name": "om",
    "coursename": "js",
    "price": "free"
}*/

// this Json array
[
    {},
    {},
    {}
]
////////////////**************OBJECTS part 2  IN JS **********////////////////////

////////// singleton objects 

//const tinderuser = new Object()

const tinderUser ={} // assingning a function 

tinderUser.id = "123abc" // putting value in function
tinderUser.name = "sammy " // putting value in function
tinderUser.isloggedin = false // putting value in function

console.log(tinderUser); // { id: '123abc', name: 'sammy ', isloggedin: false }
console.log(tinderUser.name); // sammy



/// nested functions 
const regularuser ={
    email: "some@gmail.com",
    fullname: {
        userfullname: {
            firstname: "hitesh",
            lastname: "sharma"
        }
    }
    
}

//console.log(regularuser);
console.log(regularuser.fullname.userfullname.firstname);/// hitesh


//// combining 2 objects together into a single object 

const obj1 = { 1: "a" , 2: "b" }
const obj2 = { 3: "a" , 4: "b" }
const obj4 = { 5: "a" , 6: "b" }

//// assingnuing function 
////const obj3 = Object.assign({}, obj1 , obj2 , obj4)
// syntax {} means target amd obj1 obj2 obj4 all three are source 

/// drop function
//const obj5 = {...obj1, ...obj2, ...obj4};
//console.log(obj5);

/// methods inside arrays 
const users = [
    {
        id: 1, 
        name: "tanishq dhingra "
    },
    {
        id: 1, 
        name: "tanishq dhingra "
    },
    {
        id: 1, 
        name: "tanishq dhingra "
    }
    ]
    console.log(users[1].id);
    
// function for getting the keys present in objects 
console.log(Object.keys(tinderUser)); 

// function for getting the values present in objects 
console.log(Object.values(tinderUser)); 

// function for getting the entries present in objects 
console.log(Object.entries(tinderUser));

// function for checking properties present in objects  and it will give answer in boolean 
console.log(tinderUser.hasOwnProperty('isLoggedIn'));
activity main.xml
****
  <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="LIFE CYCLE"
        android:textSize="18sp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintVertical_bias="0.5"
        app:layout_constraintHorizontal_bias="0.5"
        tools:ignore="MissingConstraints" />

</androidx.constraintlayout.widget.ConstraintLayout>
*******
     main activity.kt
*****
       package com.example.myapplication



import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        WindowCompat.setDecorFitsSystemWindows(window, false) // Enables edge-to-edge
        setContentView(R.layout.activity_main)
        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 onResume() {
        super.onResume()
        Toast.makeText(applicationContext, "onResume() called", Toast.LENGTH_SHORT).show()
    }

    override fun onPause() {
        super.onPause()
        Toast.makeText(applicationContext, "onPause() 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()
    }
}
******
//main activity.kt

  



import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent

import androidx.compose.foundation.layout.*
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import com.example.myapplication.ui.theme.User
import com.example.myapplication.ui.theme.UserDatabase
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.fillMaxSize().padding(16.dp)) {
        Text(text = "Enter your details here")
        Spacer(modifier = Modifier.height(25.dp))

        OutlinedTextField(
            value = name,
            onValueChange = { name = it },
            label = { Text(text = "Enter your name") },
            modifier = Modifier.fillMaxWidth()
        )
        Spacer(modifier = Modifier.height(25.dp))

        OutlinedTextField(
            value = phone,
            onValueChange = { phone = it },
            label = { Text(text = "Enter your phone number") },
            modifier = Modifier.fillMaxWidth()
        )
        Spacer(modifier = Modifier.height(25.dp))

        Button(onClick = {
            scope.launch(Dispatchers.IO) {
                userDao.insert(User(username = name, phone = phone))
            }
            Toast.makeText(context, "Record Inserted Successfully", Toast.LENGTH_LONG).show()
        }) {
            Text(text = "Insert Now")
        }
    }
}

@Preview(showBackground = true)
@Composable
fun PreviewInsertRecord() {
    val mockDatabase = UserDatabase.getInstance(context = LocalContext.current) // Use a mock database for preview
    InsertRecord(mockDatabase)
}

//  user.kt(create data class file)

  



import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity(tableName = "users")
data class User(
    @PrimaryKey(autoGenerate = true) val uid: Int? = null,
    val username: String,
    val phone: String
)
{
}

//  userdao.kt(create interface)

  package com.example.myapplication.ui.theme



import androidx.room.Dao
import androidx.room.Insert

@Dao
interface UserDAO {
    @Insert
    suspend fun insert(user: User)
}

//  userdatabase.kt(create class file)

  

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase

@Database(entities = [User::class], version = 1)
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
            }
        }
    }
}
//plugins{
//  kotlin("kapt")
//}
//dependendcies{
 // 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.myapplication



import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable

// Base Dwelling Class
open class Dwelling(val residents: Int) {
    open val buildingMaterial: String = "Generic material"
    open val capacity: Int = 0

    fun hasRoom(): Boolean {
        return residents < capacity
    }

    open fun description(): String {
        return "This dwelling is made of $buildingMaterial and has space for $capacity people."
    }
}

// Round Hut Class
class RoundHut(residents: Int) : Dwelling(residents) {
    override val buildingMaterial: String = "Straw"
    override val capacity: Int = 4

    fun floorArea(radius: Double): Double {
        return Math.PI * radius * radius
    }

    override fun description(): String {
        return "This is a round hut made of $buildingMaterial with space for $capacity people."
    }
}

// Square Cabin Class
class SquareCabin(residents: Int) : Dwelling(residents) {
    override val buildingMaterial: String = "Wood"
    override val capacity: Int = 6

    fun floorArea(length: Double): Double {
        return length * length
    }

    override fun description(): String {
        return "This is a square cabin made of $buildingMaterial with space for $capacity people."
    }
}

// Round Tower Class
class RoundTower(residents: Int, val floors: Int) : Dwelling(residents) {
    override val capacity: Int
        get() = 4 * floors

    fun floorArea(radius: Double): Double {
        return Math.PI * radius * radius * floors
    }

    override fun description(): String {
        return "This is a round tower with $floors floors, made of $buildingMaterial and has space for $capacity people."
    }
}

// Main Activity
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            DwellingsTheme {
                Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
                    DwellingApp()
                }
            }
        }
    }

    @Composable
    fun DwellingApp() {
        val roundHut = RoundHut(3)
        val squareCabin = SquareCabin(2)
        val roundTower = RoundTower(4, 3)

        Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
            Text(text = roundHut.description(), style = MaterialTheme.typography.bodyMedium)
            Spacer(modifier = Modifier.height(8.dp))
            Text(text = "Floor Area: ${roundHut.floorArea(4.5)} m²", style = MaterialTheme.typography.bodyMedium)

            Spacer(modifier = Modifier.height(16.dp))

            Text(text = squareCabin.description(), style = MaterialTheme.typography.bodyMedium)
            Spacer(modifier = Modifier.height(8.dp))
            Text(text = "Floor Area: ${squareCabin.floorArea(5.0)} m²", style = MaterialTheme.typography.bodyMedium)

            Spacer(modifier = Modifier.height(16.dp))

            Text(text = roundTower.description(), style = MaterialTheme.typography.bodyMedium)
            Spacer(modifier = Modifier.height(8.dp))
            Text(text = "Floor Area: ${roundTower.floorArea(4.0)} m²", style = MaterialTheme.typography.bodyMedium)
        }
    }

    @Preview(showBackground = true)
    @Composable
    fun DwellingAppPreview() {
        DwellingApp()
    }
}

// Theme
@Composable
fun DwellingsTheme(content: @Composable () -> Unit) {
    val colorScheme = lightColorScheme(
        primary = androidx.compose.ui.graphics.Color(0xFF6200EE),
        onPrimary = androidx.compose.ui.graphics.Color.White,
        secondary = androidx.compose.ui.graphics.Color(0xFF03DAC6),
        onSecondary = androidx.compose.ui.graphics.Color.Black,
    )
    MaterialTheme(
        colorScheme = colorScheme,
        typography = MaterialTheme.typography,
        content = content
    )
}
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.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.intent.ui.theme.IntentTheme

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        val b1:Button=findViewById(R.id.Bt1)
        b1.setOnClickListener {
            val intent = Intent(this,details::class.java)
            Toast.makeText(this,"Hello-Konichiwa",Toast.LENGTH_LONG).show()
            startActivity(intent)


        }

    }
}








details.kt

package com.example.intent

import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.enableEdgeToEdge

class  details: ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main2)
        val b2: Button = findViewById<Button>(R.id.Bt2)
        b2.setOnClickListener {
            Toast.makeText(this,"hi", Toast.LENGTH_LONG).show()
        }
    }
}




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/Bt1"
        android:layout_width="match_parent"
        android:layout_height="98dp"
        android:text="Go to Second Activity"
        android:textColor="@color/black"
        android:textSize="25dp" />


</LinearLayout>






activity_main2.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/Bt2"
        android:layout_width="match_parent"
        android:layout_height="98dp"
        android:text="Go to Second Activity"
        android:textColor="@color/black"
        android:textSize="25dp" />


</LinearLayout>



*****manifest******
<activity android:name=".details" />
manifests
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)
    
}
//Tip Calculator

package com.example.tip

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Column
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.mutableStateOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.tip.ui.theme.TipTheme
import androidx.compose.runtime.remember
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.ui.unit.dp
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.fillMaxWidth


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

@Composable
fun TipCalculator(){
    var amount by remember { mutableStateOf("") }
    var tipPercentage by remember { mutableStateOf("") }
    var tipAmount by remember { mutableStateOf(0) }

    Column(
        modifier = Modifier.fillMaxSize()
                    .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    )
    {
        TextField(value = amount,
            onValueChange = {newAmount -> amount = newAmount},
            modifier = Modifier.fillMaxWidth(),
            label = {Text("Enter your total Bill:")})


        Spacer(modifier = Modifier.height(16.dp))


        TextField(value = tipPercentage,
            onValueChange = {newTipPercentage -> tipPercentage = newTipPercentage},
            modifier = Modifier.fillMaxWidth(),
            label = {Text("Enter tip percentage:")})

        Spacer(modifier = Modifier.height(16.dp))

        Button(
            modifier = Modifier.fillMaxWidth(),
            onClick ={
            val billAmount = amount.toIntOrNull() ?: 0
            val tip = tipPercentage.toIntOrNull() ?: 0

            tipAmount = (tip * billAmount)/100 })
        {
            Text(text = "Calculate Tip")
        }

        Spacer(modifier = Modifier.height(16.dp))

        Text(text = "Your tip amount is: $tipAmount")
    }
}
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
package com.example.calculator

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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
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.Modifier
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.calculator.ui.theme.CalculatorTheme
import java.text.NumberFormat

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
         Surface (modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background){
             TipCalculator()

         }

            }
        }
    }

@Composable
fun TipCalculator(){
    var billAmount by remember{ mutableStateOf(TextFieldValue(" ")) }
    var tipPercentage by remember{ mutableStateOf(TextFieldValue(" ")) }
    var calculatedTip by remember{ mutableStateOf(0.0) }
    var totalAmount by remember{ mutableStateOf(0.0) }

    Column (modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp))
  {
        Text(text = "Tip Calculator", style = MaterialTheme.typography.headlineLarge)

        OutlinedTextField(value = billAmount, onValueChange ={billAmount = it},
            label = { Text(text = "Enter bill amount")}, modifier = Modifier.fillMaxWidth() )

        OutlinedTextField(value = tipPercentage, onValueChange = {tipPercentage = it},
            label = { Text(text = "Enter tip percentage")}, modifier = Modifier.fillMaxWidth())

        Button(onClick = {
            val bill = billAmount.text.toDoubleOrNull()?:0.0
            val tip = tipPercentage.text.toDoubleOrNull()?:0.0

            calculatedTip = (bill * tip ) / 100
            totalAmount = bill+calculatedTip

       				 },
          modifier = Modifier.fillMaxWidth()) {
            Text(text = "Calculate")

       			 }

        if (calculatedTip > 0)
        {
            Text(text = "Tip : ${NumberFormat.getCurrencyInstance().format(calculatedTip)}")
            Text(text = "Total: ${NumberFormat.getCurrencyInstance().format(totalAmount)}")
        }
    }
}

@Preview(showBackground = true)
@Composable
fun TipCalculatorPreview(){
    TipCalculator()
}


//Dependencies
dependencies {
    implementation "androidx.compose.ui:ui:1.3.0"
    implementation "androidx.compose.material3:material3:1.0.0"
    implementation "androidx.navigation:navigation-compose:2.5.3"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.5.1"
    
}
star

Thu Oct 31 2024 13:09:06 GMT+0000 (Coordinated Universal Time)

@usman13

star

Thu Oct 31 2024 10:37:51 GMT+0000 (Coordinated Universal Time)

@desiboli #javascript #typescript #react.js

star

Thu Oct 31 2024 09:59:43 GMT+0000 (Coordinated Universal Time)

@carona

star

Thu Oct 31 2024 09:58:45 GMT+0000 (Coordinated Universal Time)

@carona

star

Thu Oct 31 2024 09:54:32 GMT+0000 (Coordinated Universal Time)

@carona

star

Thu Oct 31 2024 09:52:23 GMT+0000 (Coordinated Universal Time)

@carona

star

Thu Oct 31 2024 09:44:18 GMT+0000 (Coordinated Universal Time)

@carona

star

Thu Oct 31 2024 09:43:01 GMT+0000 (Coordinated Universal Time)

@carona

star

Thu Oct 31 2024 09:40:24 GMT+0000 (Coordinated Universal Time)

@carona

star

Thu Oct 31 2024 09:39:23 GMT+0000 (Coordinated Universal Time)

@carona

star

Thu Oct 31 2024 09:03:15 GMT+0000 (Coordinated Universal Time)

@signup1

star

Thu Oct 31 2024 06:38:16 GMT+0000 (Coordinated Universal Time)

@Samuel1347

star

Thu Oct 31 2024 04:39:36 GMT+0000 (Coordinated Universal Time)

@varuntej #kotlin

star

Wed Oct 30 2024 22:50:25 GMT+0000 (Coordinated Universal Time)

@davidmchale #section #only-child

star

Wed Oct 30 2024 16:13:03 GMT+0000 (Coordinated Universal Time)

@saharmess #java

star

Wed Oct 30 2024 16:13:03 GMT+0000 (Coordinated Universal Time)

@saharmess #java

star

Wed Oct 30 2024 13:15:31 GMT+0000 (Coordinated Universal Time)

@signup1

star

Wed Oct 30 2024 08:51:04 GMT+0000 (Coordinated Universal Time) https://carbon.now.sh/

@hkrishn4a #undefined

star

Wed Oct 30 2024 08:50:06 GMT+0000 (Coordinated Universal Time) https://carbon.now.sh/

@hkrishn4a #undefined

star

Wed Oct 30 2024 08:36:31 GMT+0000 (Coordinated Universal Time) https://d365-solutions.blogspot.com/2021/08/financial-dimension-lookup-using-x-ax.html

@pavankkm

star

Wed Oct 30 2024 08:36:26 GMT+0000 (Coordinated Universal Time) https://stoneridgesoftware.com/create-custom-dialog-on-form-with-customer-lookup-for-a-specific-financial-dimension-in-d365-finops/

@pavankkm #csharp

star

Wed Oct 30 2024 05:51:58 GMT+0000 (Coordinated Universal Time)

@zaki

star

Wed Oct 30 2024 05:27:30 GMT+0000 (Coordinated Universal Time)

@signup1

star

Wed Oct 30 2024 04:50:54 GMT+0000 (Coordinated Universal Time)

@signup1

star

Wed Oct 30 2024 03:59:23 GMT+0000 (Coordinated Universal Time)

@manasm11 #go #golang

star

Wed Oct 30 2024 03:49:20 GMT+0000 (Coordinated Universal Time)

@manasm11 #go #golang

star

Wed Oct 30 2024 03:46:27 GMT+0000 (Coordinated Universal Time)

@manasm11 #go #golang

star

Tue Oct 29 2024 23:53:58 GMT+0000 (Coordinated Universal Time)

@Themaheshe

star

Tue Oct 29 2024 23:10:40 GMT+0000 (Coordinated Universal Time)

@shahmeeriqbal

star

Tue Oct 29 2024 23:09:37 GMT+0000 (Coordinated Universal Time)

@shahmeeriqbal

star

Tue Oct 29 2024 22:11:40 GMT+0000 (Coordinated Universal Time)

@davidmchale #js #dynamic-function

star

Tue Oct 29 2024 21:05:19 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Tue Oct 29 2024 21:05:18 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Tue Oct 29 2024 18:50:37 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Tue Oct 29 2024 18:17:43 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Tue Oct 29 2024 17:55:40 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Tue Oct 29 2024 17:18:04 GMT+0000 (Coordinated Universal Time)

@signup1

star

Tue Oct 29 2024 17:09:30 GMT+0000 (Coordinated Universal Time)

@signup1

star

Tue Oct 29 2024 16:52:27 GMT+0000 (Coordinated Universal Time)

@signup1

star

Tue Oct 29 2024 16:39:17 GMT+0000 (Coordinated Universal Time)

@signup1

star

Tue Oct 29 2024 15:29:40 GMT+0000 (Coordinated Universal Time)

@signup1

star

Tue Oct 29 2024 15:21:05 GMT+0000 (Coordinated Universal Time)

@signup1

star

Tue Oct 29 2024 13:35:36 GMT+0000 (Coordinated Universal Time)

@signup_returns #kotlin

star

Tue Oct 29 2024 13:03:33 GMT+0000 (Coordinated Universal Time)

@signup1

star

Tue Oct 29 2024 12:38:30 GMT+0000 (Coordinated Universal Time)

@signup1

Save snippets that work with our extensions

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