Tuesday, July 16, 2024

How To Create a Dialog in Android

 Creating a Dialog is quite easy in Android.

void showDialogToPurchase()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");
builder.setMessage("Message")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicks OK

}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
        // User cancels the dialog.
             }
            });
builder.create().show();
}

Friday, December 2, 2022

How do i find what my ip address is

All network devices have an unique IP Address. It can be IP4 or IP6 address.


How do i find what my ip address is

To find your IP address on windows desktop or laptop you can use command prompt.

Open Command Prompt and write  "ipconfig"

You will see your IP Details like below

For more details of your IP Address visit website  

 What is my IP Address, IP Address Details




What is server address in vpn

 VPN Offeres a convenient way to hide your IP Address.You can access blocked websites and URLS using VPN.

What is server address in VPN

For more details, you can visit MY IP Tracker and Locator

To find the server Address in VPN you can do the following-

  1. Check with your VPN Service provider. A VPN provider generally provide server address in their documentation.
  2. You can use Traceroute toll. Open command prompt and do a traceroute.This will show you the path that traffic takes to get to the server. If the traceroute succeeds, you’ll see the server’s IP address listed as the last hop.
  3. You can use Ping utility in command prompt. Try pinging the server address or name. If the ping is successful, you’ll see the server’s IP address listed as the destination.

For more details, you visit MY IP Tracker and Locator

Friday, November 4, 2022

PHP code for String Tokenize

 PHP code for String Tokenize


<?php
$string = "Hello Kamal. How are you Doing?";
$token = strtok($string, " ");

while ($token !== false)
{
echo "$token<br>";
$token = strtok(" ");
}
?>

Thursday, September 29, 2022

C++ Code to check two given String are Anagram are not

 

What is Anagram : An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once


C++ Code to check two given String are Anagram are not


#include <iostream>

#include <string.h>

using namespace std;

void checkAnagrams(char str1[],char str2[])

{

     int hash[26];

     int i;

     for( i=0;i<26;i++)

     hash[i]=0;

     

     for(i=0;i<strlen(str1);i++)

     {

         hash[str1[i]-97]++;

     }

      for(i=0;i<strlen(str2);i++)

      {

         hash[str2[i]-97]--;

      }

                    

      for(i=0;i<26;i++)

      {

            if(hash[i]!=0)

            break;

      }

      if(i==26)

      cout<<"Strings are anagrams";

      else

      cout<<"Strings  are not anagrams";

}

                               

int main(int argc, char *argv[])

{

    checkAnagrams("madam curie","radium came");

  

    return EXIT_SUCCESS;

}



Output :

Strings are anagrams

C++ Code for Rat in Maze Problem

 Rat in Maze problem : This is a famous problem solving coding question. There is a grid filled with 1 and 0, There is a rat at position 0,0. He has to reach at the last point of Grid and the Rat can move to block having value 1.

Print the path the will take to reach.


C++ Code for Rat in Maze Problem



#include <iostream>

using namespace std;


#define N  5


int path[N][N]={1,1,1,1,1,

                0,0,1,0,1,

                1,1,1,1,1,

                1,0,1,0,0,

                1,1,1,1,1

               };

                

int sol[N][N];



bool isValid(int row,int col)

{

     if(row>=0&&col>=0&&row<N&&col<N&&path[row][col]==1&&sol[row][col]==0)

     return true;

     else

     return false;

}

bool solveRatInMaze(int row,int col)

{

     if(row==N-1&&col==N-1)

     {

        sol[row][col]=1;

     return true;

     }

    // int i=row,j= col;

     if(isValid(row,col)==true)

     {

         sol[row][col]=1;                      

         //  move right

         

         if(solveRatInMaze(row+1,col)==true)

         return true;

         if(solveRatInMaze(row,col+1)==true)

         return true;

  

         if(solveRatInMaze(row+1,col)==true)

         return true;

         

         if(solveRatInMaze(row-1,col)==true)

         return true;

         if(solveRatInMaze(row,col-1)==true)

         return true;

         sol[row][col]=0; 

     }       

     

     else

     return false;  

     

     return false;

}      

int main(int argc, char *argv[])

{

    int i,j;

    for( i=0;i<N;i++)

    {

            for(j=0;j<N;j++)

            {

                            sol[i][j]=0;

            }

    }

    

    if(solveRatInMaze(0,0)==true)

    {

           for( i=0;i<N;i++)

           {

                for(j=0;j<N;j++)

               {

                            printf("%d  ",sol[i][j]);

               }

               printf("\n");

           }

    }

    

    else

    printf("There is no path");

    

    return EXIT_SUCCESS;

}


Output :


1  1  1  0  0  

0  0  1  0  0  

0  0  1  0  0  

0  0  1  0  0  

0  0  1  1  1  

C++ Code to Add two numbers without using + operator

 C++ Code to Add two numbers without using + operator


    


#include <iostream>

#include <math.h>

using namespace std;


int add(int a,int b)

{

    int num=0,carry=0,p=0;

    int abit,bbit,numbit;

    while(a!=0||b!=0)

    {

                     abit=a&1;

                     bbit=b&1;

                     

                     numbit=abit^bbit^carry;

                     carry=(abit&bbit)||(abit&carry)||(bbit&carry);

                     

                     num=num+numbit*(int)pow(2,p);

                     p++;

                     a=a>>1;

                     b=b>>1;

                     

                  

    }

    

    if(carry==1)

    num=num+(int)pow(2,p);

    return num;

 }



int main(int argc, char *argv[])

{

   printf("%d",add(70,40));

  return 0;

}



Output :

110

C++ Code to Add 1 in a number without using + or -

 C++ Code to Add 1 in a number without using + or -


C++ Code


int add1(int num)

{

    int mask=1;

    if(num>=0)// if number is +ve

    {

       while(true)

      {

         if(num&mask)

         {

             num=num^mask;

         }

         else

         {

             num=num^mask;

             break;

         }

         mask=mask<<1;

      }

      return num;

    }

    else  // if number bis -ve

    {

          num=abs(num);

          while(true)

          {

               if(num&mask)

               {

                   num=num^mask;

                   break;

               }              

               else

               {

                   num=num^mask;

               }

               mask=mask<<1;

          }

          return (-num);

    }

        

}   

                              

int main(int argc, char *argv[])

{

    cout<<add1(12563);

   

    return EXIT_SUCCESS;

}


Output : 

12564

0 at odd places and 1 at even places

 0 at odd places and 1 at even places


C++ Code



#include <iostream>

using namespace std;


void arrange(int a[],int n)

{

     int i=0,zero=-1,one=-1;

     while(i<n&&zero<n&&one<n)

     {

          if(i%2!=0) // if odd place                    

          {

                  if(a[i]!=0)

                  {

                         if(zero==-1)

                         zero=i+1;

                         while(a[zero]!=0&&zero<n)

                         zero++;

                         if(a[zero]==0)

                         {

                             a[zero]=1;

                             a[i]=0;

                             zero++;

                         }

                  }

          }          

          else

          {

                if(a[i]!=1)

                  {

                         if(one==-1)

                         one=i+1;

                         while(a[one]!=1&&one<n)

                         one++;

                         if(a[one]==1)

                         {

                             a[one]=0;

                             a[i]=1;

                           one++;

                         }

                  }

          } 

          i++;

     }         

}

int main(int argc, char *argv[])

{

    int a[]={1,0,1,1,0,0,1,1,1,0};

    int n=10;

    arrange(a,n);

    for(int i=0;i<n;i++)

    cout<<a[i]<<"  ";

 

    return EXIT_SUCCESS;

}


C++ Code A sorted array rotated find the the point from where it is rotated

  A sorted array rotated find the the point from where it is rotated


C ++ Code

#include <iostream>

using namespace std;


int find(int a[],int n)

{

     int low=0,up=n;

     int mid;

     while(low<=up)

     {

           mid=(up+low)/2;

           if(a[mid]<a[mid-1]&&a[mid]<a[mid+1])

              return a[mid];

           else if(a[mid]>a[low])

           low=mid+1;

           else

           up=mid-1;

    

     }

     return 0;

}

int main()

{

     int a[]={14,16,18,2,3,4,5,6};

     int num=find(a,7);

     printf("%d",num);

    

     return 0;

 }




Output :


2



JAVA Code to get Current Date and Time

In JAVA, we can use  GregorianCalendar class to get current Date and Time.


 JAVA Code to get Current Date and Time



Code : 

public class Test {

    

    public static void main(String a[])

    {

        GregorianCalendar gc = new GregorianCalendar();

        System.out.print(gc.getTime());

    

    }

    

}



Output :


Fri Sep 30 10:38:51 IST 2022

Wednesday, September 14, 2022

How to remove extension from string in PHP

 

How to remove extension from string in PHP


There are multiple ways to remove extension from a file name in PHP
 
<?php
  
// Initializing a variable with filename
$file = 'myfilename.jpg';
  
// Extracting only filename using constants
$fileWithoutExt = pathinfo($file, PATHINFO_FILENAME);
  
// Printing the result
echo $fileWithoutExt;
  
?>



Output

filename

Saturday, October 2, 2021

Code to get WiFi MAC Address of Device in Android

 In Android we can get the MAC Address of a Device

Code to get WiFi MAC Address of Device in Android

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// only for gingerbread and newer versions
macAddressOfDevice = getMacAddr();
Log.i("KAMLESH", "MAC Address : " + macAddressOfDevice);
}
else {
WifiManager wifiMan = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInf = wifiMan.getConnectionInfo();
macAddressOfDevice = wifiInf.getMacAddress();
Log.i("KAMLESH", "MAC Address : " + macAddressOfDevice);
}


public  String getMacAddr() {
try {
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return "";
}

StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
res1.append(String.format("%02X:",b));
}

if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {
}
return "02:00:00:00:00:00";
}

Check Internet Connection Type In Android

 In Android we can check whether the Device is Connected to Internet or Not.


If Connected to Internet, we can check the type of connection like Mobile Data, WiFi etc


Add following permission in Manifest file

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Code to Check Internet Connection Type in Android


public boolean isInternetConnected() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
boolean isConncted = activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
return isConncted;
}


public boolean isConnectedWifi(){
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
}



public boolean isConnectedMobile(){
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);
}

Saturday, December 26, 2020

JAVA Code to Rename all files in a folder

JAVA Code to Rename all files in a folder


import java.io.*;

public class RenameFileNames 

{

     public static void main(String[] args) 

     {

        String absolutePath = "E:\\Wllpapers\\unbelive";

        File dir = new File(absolutePath);

        File[] filesInDir = dir.listFiles();

        int i = 0;

        for(File file:filesInDir) {

            i++;

            String name = file.getName();

            String newName = "pic" + i + ".jpeg";

            String newPath = absolutePath + "\\" + newName;

            file.renameTo(new File(newPath));

            System.out.println(name + " changed to " + newName);

        }

    }

}


Tuesday, November 24, 2020

Code to Check Internet Connection in Android 8 and above

 Code to Check Internet Connection in Android 8 and above




public boolean isInternetConnected(Context context) {
int result = 0; // Returns connection type. 0: none; 1: mobile data; 2: wifi
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (cm != null) {
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
return true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) {
return true;
}
}
}
} else {
if (cm != null) {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
// connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
return true;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_VPN) {
return true;
}
}
}
}
return false;
}

Wednesday, September 30, 2020

Showing Snackbar with action button in Android

Showing Snackbar with  action button in Android 


void showSnackBarWithMessage(String message)
{

final Snackbar snack = Snackbar.make(yourView, message, 3000);
snack.getView().setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.colorPrimaryLight));
snack.setAction("OK", new View.OnClickListener() {
@Override
public void onClick(View view) {
snack.dismiss();
}
});

snack.show();
}

Friday, July 31, 2020

JAVA Code to find distance between two GPS Coordinates

Here is a JAVA Program to find the distance between two GPS Coordinates.



       static double latitude1 = 40.6971494;
       static double latitude2 = 19.0821978;
       static double longitude1 = -74.2598702;
       static double longitude2 = 72.7410985;


 public static void findDistance()
        {

            double lon1 = Math.toRadians(longitude1);
            double lon2 = Math.toRadians(longitude2);
            double  lat1 = Math.toRadians(latitude1);
            double  lat2 = Math.toRadians(latitude2);

 
            double dlon = lon2 - lon1;
            double dlat = lat2 - lat1;
            double a = Math.pow(Math.sin(dlat / 2), 2)
                    + Math.cos(lat1) * Math.cos(lat2)
                    * Math.pow(Math.sin(dlon / 2),2);

            double c = 2 * Math.asin(Math.sqrt(a));

            // Radius of earth in kilometers. Use 3956
            // for miles
            double r = 6371;

            // calculate the result
            double distance = c * r;
       
            System.out.println("Distance in KM : "+ Math.floor(distance));
            System.out.println("Distance in Miles : "+ Math.floor(distance*.621371));
            System.out.println("Distance in Nautical Miles : "+ Math.floor(distance*.539957));

        }

    

JAVA Code to convert Bytes into MB

Here is the JAVA Code to convert bytes in MB upto 1 decimal place.

public void getSizeInMB()
    {
        long sizeinBytes = 200*1024;
                long sizeInKB = sizeinBytes/1024;
                long sizeInMBInt = sizeInKB/1024;
                float sizeInMB = sizeInKB/1024.0f;
                String size = sizeInMB+"";

                int k = size.indexOf('.');
                size = sizeInMBInt+"."+size.charAt(k+1);
   
      System.out.print(size);
    }

JAVA Code to get Date with Month and Time



                                GregorianCalendar  gc=new GregorianCalendar();
    gc.setTimeInMillis(System.currentTimeMillis());

    int day=gc.get(Calendar.DAY_OF_MONTH);
    int month=gc.get(Calendar.MONTH)+1;
    int year=gc.get(Calendar.YEAR);
    int hour = gc.get(Calendar.HOUR_OF_DAY);
                                int minute = gc.get(Calendar.MINUTE);
                         
    String date="Date: "+day+"/"+month+"/"+year+" Time : "+hour+":"+minute;
                               
                                System.out.print(date);