Thursday, 23 November 2017

Bresenham's line drawing algorithm program in Java

/*
    Bresenham's Line Drawing Algorithm
    Created By : Pirate
*/

import java.awt.Graphics;
import java.util.Scanner;
import javax.swing.*;
public class Line extends JFrame implements Runnable{
int a,b,x,y,p=0,q=0;

public static void main(String[] args) {
                 System.out.println("*** Bresenham Line Algorithm ***");
                 System.out.println("\nEnter the starting point of line");
                 Scanner scan = new Scanner(System.in);
                 Line line = new Line();
                 line.a = scan.nextInt();
                 line. b = scan.nextInt();
                 System.out.println("\nEnter the ending point of line");
                 line.x = scan.nextInt();
                 line.y = scan.nextInt();
 Thread t= new Thread(line);
 t.start();
 scan.close();
}
public Line(){
                 this.pack();
                 this.setVisible(true);
                 this.setTitle("Wave The World");
                 this.setSize(400, 400);
                 this.setContentPane(getContentPane());
                 this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}

@Override
        public void paint(Graphics g) {
                 super.paint(g);
                 g.drawLine(a, b, p, q);
        }

public void putPixel(int x,int y){
p=x;
q=y;
repaint();
}

public void run(){
      Bre_Line();
}

public void Bre_Line(){
int x1=a;
                int y1=b;
                int dx, dy;
                x2=x;
                y2=y;
dx=x2-x1;

if(dx < 0){
dx = dx*(-1);
}

dy=y2-y1;

if(dy < 0){
dy= dy*(-1);
}
int temp;
if(dx<dy){
temp = dx;
dx = dy;
dy = temp;
}

                int p=2*dy-dx;
                i=dx;
                while(i>0){
             try{
                Thread.sleep(100);
             }catch(Exception e){
                                    System.out.println(e.getMessage());
             }
                         putPixel(x1,y1);
                         if(p<0)
                         {
                                   x1=x1+1;
                                   p=p+2*dy;
                 }
                 else
                {
                           x1=x1+1;
                   y1=y1+1;
                   p=p+2*dy-2*dx;
                }
            i--;
    }
      }
}

Output :









Enjoy :)

Monday, 13 November 2017

How to get value from comma separated string in oracle

Hi Friends,

Today I'm here with a new program. The problem is that we have given a string with comma separated values i.e 'wave,the,world,oracle,program,' and we have to extract values from the string.


So the input value will be,

Input : 'wave,the,world,oracle,program,'

and output will be like this,
Output :
wave
the
world
oracle
program

Let's start, we are going to use following Oracle builtin function in the program.








length()

translate()
substr()
instr()

So first we will understand the working of these functions.



  • length() : The Oracle length() function returns the length of the specified string.

          i.e. select length('wave the world') from dual;
          Result : 14


  • translate() : The Oracle translate() function replaces a sequence of character in a string with another set of characters. It replaces a single character at a time. i.e it will replace the first character in the string_to_replace with the first character in the replacement_string. The it will replace the second character and so on.

          i.e select translate('wave the world','e ','AS') from dual;
          Result : wavASthASworld


  • substr() : The Oralce substr() function allows you to extract a substring from a string.
          i.e select substr('wave the world',0,4) from dual;
          Result : wave







  • instr() : The function returns the location of a substring in a string.
          i.e select instr('wave the world','the') from dual;
          Result : 6

Now we will create a pl/sql block to do the job by using all these functions.



declare
    comma varchar2(20);
    st varchar2(50):='wave,the,world,oracle,program,';
    st_temp varchar2(20);
begin
    comma:=length(st) -length(translate(st,'A,','A'));
    for i in 0.. comma - 1 loop
        st_temp := substr(st,0,instr(st,',')-1);
        dbms_output.put_line(st_temp);
        st:= substr(st,instr(st,',') + 1);
    end loop;
end;



When will you run this pl/sql block you will get the desired output.








Output :
wave
the
world
oracle
program



How this code works? 
First we count the no of comm in the string and run a for loop. Everytime we cut the string that is printed and loop contine run till the all values from string printed.

Share your thoughts in comment section.

Enjoy :) 


Thursday, 2 November 2017

Program to implement Insertion Sort in C

/*
   Insertion Sort
   Created By: Pirate
*/

#include<stdio.h>
#include<conio.h>
void insertion(int items[],int n);
void main(){
    int items[500],n,i;

    printf("*** Insertion Sort ***\n");
    printf("\nEnter the number of elements: ");
    scanf("%d",&n);

    printf("\nEnter the %d elements: \n",n);
    for(i = 0; i < n; i++){
        scanf("%d",&items[i]);
    }

    printf("\n\nBefore Sorting:\n");
    for(i = 0; i < n; i++){
        printf("%d\t",items[i]);
    }

    insertion(items,n);

    printf("\n\nAfter Sorting:\n");
    for(i = 0; i < n; i++){
        printf("%d\t",items[i]);
    }
    getch();
}

void insertion(int items[],int n){
    int i,j,temp;
    for(i=0;i<n;i++){
        temp = items[i];
        for(j = i-1; j >= 0; j--){
            if(temp<items[j]){
                items[j+1]=items[j];
            }
            else{
                break;
            }
        }
        items[j+1] = temp;
    }

}






Output :


Program to implement Bubble Sort in C

/*
   Bubble Sort Algorithm
   Created By: Pirate
*/

#include<stdio.h>
#include<conio.h>
void bubble(int items[],int n);
void main(){
    int items[500],n,i;

    printf("*** Bubble Sort ***\n");

    printf("Enter the number of elements: ");
    scanf("%d",&n);

    printf("\nEnter the elements: \n");
    for(i = 0; i < n; i++){
        scanf("%d",&items[i]);
    }

    printf("\n\nBefore Sorting:\n");
    for(i = 0; i < n; i++){
        printf("%d\t",items[i]);
    }
    bubble(items,n);

    printf("\n\nAfter Sorting:\n");
    for(i = 0; i < n; i++){
        printf("%d\t",items[i]);
    }
    getch();
}
void bubble(int items[],int n){
    int i,j,temp;
    for(i = 0; i < n; i++){
        for(j = 0; j < n-1; j++){
            if(items[j] > items[j+1]){
                temp = items[j];
                items[j] = items[j+1];
                items[j+1] = temp;
            }
        }
    }

}






Output :


Thursday, 7 September 2017

Blogger could not save earnings settings

Hi Friend,

Today I'll tell you how to solve the blogger error Could not save earnings settings. I'm getting this error and I searched a lot. But did not find any solution. But now I'm able to solve this error. So I thought I should post about this error.

When this error occur?

This error occurs when you try to save Your AdSense ad-display setting. After selecting the ad layout, you click on Save Settings button, whoa... You see the error pop up Could not save earning settings.



And you will not be able to setup AdSense ad on your blog. That's means no earning.





What could be the reasons?

  • Your AdSense account may have expired.
  • It is not a browser issue. If it is a browser issue then it should be working with other browsers. I have tried almost all browsers.
  • You have more no of ads running on your single page.
  • Your AdSense account is more then six month old and din't get approved.


How to solve this error?

To solve this error, you should have a approved AdSense account. And if you don't have a approved AdSense account then also you need to follow these steps. Because for getting a AdSense account you need to save Earning Settings. Now there is deadlock, and you can't get approve for your adsense account. That means no money no honey.

Steps to solve this error

If you follow each step, then you will be able to solve the problem and soon you will get a approved AdSense account.

  • Step : 1 If you are already running ads on your blog, check the no of ads. If you are not running any ad then skip this step.








Tuesday, 5 September 2017

Program to implement Peterson’s Algorithm for Mutual Exclusion in C

/*
    Peterson’s Algorithm for Mutual Exclusion
    Created By: Pirate
*/


#include <stdio.h>
#include <pthread.h>

void* process(void *s);
int flag[2];
int turn,count=0,mode=0;
const int MAX = 1e9;

void main()
{
    printf("*** Peterson's Algorithm ***\n");
    pthread_t p1,p2,p3,p4;

    printf("\nFirst without Lock\n");

    pthread_create(&p1, NULL, process, (void*)0);
    pthread_create(&p2, NULL, process, (void*)1);

    pthread_join(p1, NULL);
    pthread_join(p2, NULL);

    printf("Actual Count: %d | Expected Count: %d\n",count, MAX*2);

    printf("\n\nNow with Lock\n");
    count = 0;
    mode = 1;
    lock_init();

    pthread_create(&p3, NULL, process, (void*)0);
    pthread_create(&p4, NULL, process, (void*)1);

    pthread_join(p3, NULL);
    pthread_join(p4, NULL);

    printf("Actual Count: %d | Expected Count: %d\n",count, MAX*2);

}

void lock_init()
{
    flag[0] = flag[1] = 0;
    turn = 0;
}

void lock(int current)
{
    flag[current] = 1;

    turn = 1-current;
    while (flag[1-current]==1 && turn==1-current) ;
}

void unlock(int current)
{
    flag[current] = 0;
}

void* process(void *s)
{
    int i = 0;
    int current = (int *)s;
    printf("Process : %d\n", current);

    if(mode == 1)
        lock(current);
    for (i=0; i<MAX; i++)
        count++;

    if(mode == 1)
        unlock(current);
}





Output :



Sunday, 27 August 2017

FCFS scheduling program in C with arrival time

/*
    FCFS (First Come First Serve) Scheduling Algorithm with Arrival time
    Created By: Pirate
*/



#include<stdio.h>
#include<conio.h>
void main()
{
    float process[500],aTime[500],bTime[500],abTime[500],wTime[500],tat_time[500];
    int n = 0,i = 0 ;
    float aw_time = 0, atat_time = 0;
    printf("*** FCFS Scheduling Algorithm Using Arrival Time ***\n");
    printf("\nEnter the number of process : ");
    scanf("%d",&n);

    printf("Enter the Arrival time and Burst time.\n\n");
    printf("\tA_Time B_Time\n");
    for(i = 0 ; i < n ; i++){
        process[i]=i+1;
        printf("P%d :\t", i+1);
        scanf("%f\t%f",&aTime[i],&bTime[i]);
    }
    printf("\n\nProcess\tA_Time\tB_Time\n");
    for(i = 0 ; i < n ; i++){
        printf("P[%d]\t%.2f\t%.2f\n",i,aTime[i],bTime[i]);
    }
    wTime[0] = 0;
    tat_time[0] = bTime[0];
    abTime[0] = bTime[0]+aTime[0];
    for( i = 1 ; i < n ; i++){
        abTime[i] = abTime[i-1] + bTime[i];
        tat_time[i] = abTime[i] - aTime[i];
        wTime[i] = tat_time[i] - bTime[i];
    }
    for(i = 0 ; i < n ; i++){
        aw_time = aw_time + wTime[i];
        atat_time = atat_time + tat_time[i];
    }
    printf("\tA_time\tB_time\tC_time\tTat_time  W_time\n");
    for(i = 0 ; i < n ; i++){
        printf("P[%d]\t%.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\n",i,aTime[i],bTime[i],abTime[i],tat_time[i],wTime[i]);
    }
    printf("\nAverage waiting time : %0.2f",aw_time/n);
    printf("\nAverage turn around time : %0.2f",atat_time/n);
}

Output



Tuesday, 22 August 2017

How to send mail from php from local host using gmail smtp

Hi Friends,

How are you all? Good. I'm also good. Today I'll tell you how to send mail from local host in php.

I'm using php mailer to send mail. PHPMailer is a class library for PHP that provides a collection of functions to build and send email messages. PHPMailer supports several ways of sending email: mail(), Sendmail, qmail & direct to SMTP servers. You can use any feature of SMTP-based e-mail, multiple recepients via to, CC, BCC, etc. In short: PHPMailer is an efficient way to send e-mail within PHP.

PHP has a built-in mail() function. So why use PHPMailer? Isn't it slower? Not really, because before you can send a message you have to construct one correctly, and this is extremely complicated because there are so many technical considerations. PHPMailer makes it easy to send e-mail, makes it possible to attach files, send HTML e-mail, etc. With PHPMailer you can even use your own SMTP server and avoid Sendmail routines used by the mail() function on Unix platforms.
You can download phpmailer from here. 
After downloading the file, you need to extract the content and save it under your server folder. For me I'm saving in htdocs because i'm using XAMPP. The best practice is save it inside your website folder. My website folder name is test. So I saved it inside test folder.
To send mail you need a html file in which you can provide the details, Google id and password and php file in which all the mail logic written.
Lets create a simple html form,
<html>
    <body>
        <form name="email" method="post" action="test.php">
            <table>
                <tr>
                    <td>To</td>
                    <td><input type="text" name ="to" required></td>
                </tr>
                <tr>
                    <td>From</td>
                    <td><input type="text" name="from" required></td>
                </tr>
                <tr>
                    <td>CC</td>
                    <td><input type="text" name="cc"></td>
                </tr>
                <tr>
                    <td>Subject</td>
                    <td><input type="text" name ="subject"></td>
                </tr>
                <tr>
                    <td>Message</td>
                    <td><textarea rows="5" cols="22" name="message" required>
                    </textarea></td>
                </tr>
                <tr>
                    <td><input type="submit"></td>
                    <td><input type="reset"></td>
                </tr>
        </form>
    </body>
</html>
I'm not adding any validation in the form. Just one that is you have to enter something. You can also email validation if the email id is valid or not.
You can save the file with any name. I'm saving it test1.html. It will look like,

I did not added any css. If you want you can add and modify code according to your need. Now we created html file. Lets write some php code.

<?php
    require 'PHPMailer/PHPMailerAutoload.php';

    if (!empty($_POST["to"]) && !empty($_POST["from"]) 
        && !empty($_POST["message"])){
        $to = $_POST["to"];
        $from = $_POST["from"];
        $message = $_POST["message"];
        $subject = $_POST["subject"];
        //Create a new PHPMailer instance
        $mail = new PHPMailer;   
        $mail->isSMTP();
        $mail->SMTPDebug = 0;
        $mail->Debugoutput = 'html';
        $mail->Host = 'smtp.gmail.com';
        $mail->Port = 587;
        $mail->SMTPSecure = 'tls';

        //use SMTP authentication
        $mail->SMTPAuth = true;

        //Username to use for SMTP authentication
        $mail->Username = "yourEmail@gmail.com";
        $mail->Password = "yourEmailIdPass";
        $mail->setFrom($from);
        $mail->addReplyTo($to);
        $mail->addAddress($to);
        $mail->Subject = $subject;
        // $message is gotten from the form
        $mail->msgHTML($message);
        $mail->AltBody = "";
        if (!$mail->send()) {
            echo "Error while sending mail";
        } else {
            echo "Congratulations. Success";
            }
    }
    else
        header('Location: http://localhost/test/test1.html')
?> 

when you write your php mail code, check require 'PHPMailer/PHPMailerAutoload.php' . If you saved PHPMailer in another folder then you have to give proper path.

After checking path, see these two lines,
        $mail->Username = "yourEmail@gmail.com";
        $mail->Password = "yourEmailIdPass";
Replace yourEmail@gmail.com with your email id and yourEmailIdPass with your password for that email id. Two-Step verification should be disable on the account that you are using in php file. If two-step verification is enabled then you have to disable it from your gmail settings.

Now save your file with the name of test.php.

You almost completed. But you have make some setting in your Gmail. For less secure apps you need to change account access. Go to following link.


It is turn off by default. You have to turn it on.


So everything is setup. It's time to test our mail if it is working or not.

Enter the email id in To and From, Enter a subject and a message and then click on Submit button.

If everything works as expected then you will get the success message,

Now go to your mailbox to check if you really get the email or is it just showing success message Congratulations. Success .

Great, I got the mail.

Enjoy :)





Saturday, 19 August 2017

Program to implement FCFS (First Come First Serve ) Algorithm in C

/*
    FCFS (First Come First Serve) Scheduling Algorithm
    Created By: Pirate
*/

#include<stdio.h>
#include<conio.h>
void main(){
    float input[500],process[500],tat[20];
    float avg_wt=0,avg_tat=0;
    int n,i,j;
    printf("*** FCFS Process Scheduling Algorithm ***\n");
    printf("\nEnter number of Processes : ");
    scanf("%d",&n);

    printf("\nEnter Process Burst Time\n");
    for(i=0;i<n;i++){
        printf("P%d : ",i+1);
        scanf("%f",&input[i]);
    }

    process[0]=0;

    for(i=1;i<n;i++){
        process[i]=0;
        for(j=0;j<i;j++)
            process[i]+=input[j];
    }
    printf("\nProcess\t\tBurst Time\tWaiting Time\tTurnaround Time");

    for(i=0;i<n;i++){
        tat[i]=input[i]+process[i];
        avg_wt+=process[i];
        avg_tat+=tat[i];
        printf("\nP[%d]\t\t%.2f\t\t%.2f\t\t%.2f",i+1,input[i],process[i],tat[i]);
    }

    avg_wt/=i;
    avg_tat/=i;
    printf("\n\nAverage Waiting Time     :  %.2f",avg_wt);
    printf("\nAverage Turnaround Time  :  %.2f\n",avg_tat);

}

Output


Program to implement SJF (Shortest Job first) algorithm in C


/*
    SJF (Shortest Job First) Scheduling Algorithm
    Created By: Pirate
*/

#include<stdio.h>
#include<conio.h>
void main(){
    int input[500],process[500];
    int wt[500],tat[500],total=0;
    int i,j,n,pos,temp;
    float avg_wt,avg_tat;
    printf("*** SJF Process Scheduling Algorithm ***\n");
    printf("Enter the number of Process: ");
    scanf("%d",&n);

    printf("\nEnter Burst Time:\n\n");
    for(i=0;i<n;i++){
        printf("P%d: ",i+1);
        scanf("%d",&input[i]);
        process[i]=i+1;
    }

    for(i=0;i<n;i++){
        pos=i;
        for(j=i+1;j<n;j++){
            if(input[j]<input[pos])
                pos=j;
        }
        temp=input[i];
        input[i]=input[pos];
        input[pos]=temp;

        temp=process[i];
        process[i]=process[pos];
        process[pos]=temp;
    }

    wt[0]=0;

    for(i=1;i<n;i++){
        wt[i]=0;
        for(j=0;j<i;j++){
            wt[i]+=input[j];
        }
        total+=wt[i];
    }

    avg_wt=(float)total/n;
    total=0;

    printf("\nProcess\t Burst Time \tWaiting Time\tTurnaround Time");
    for(i=0;i<n;i++){
        tat[i]=input[i]+wt[i];
        total+=tat[i];
        printf("\nP%d\t\t%d\t\t%d\t\t%d",process[i],input[i],wt[i],tat[i]);
    }

    avg_tat=(float)total/n;
    printf("\n\nAverage Waiting Time    =   %f",avg_wt);
    printf("\nAverage Turnaround Time =   %f\n",avg_tat);

}

Output