Tuesday 31 December 2019

ANN




import numpy as np 
feature_set = np.array([[0,1,0],[0,0,1],[1,0,0],[1,1,0],[1,1,1]]) 
labels = np.array([[1,0,0,1,1]]) 
labels = labels.reshape(5,1)

#define hyper parameters for our neural network

np.random.seed(42)  #random.seed function so that we can get the same random values whenever the script is executed.
weights = np.random.rand(3,1) 
bias = np.random.rand(1) 
lr = 0.05

def sigmoid(x):    #activation function is the sigmoid function
    return 1/(1+np.exp(-x))

def sigmoid_der(x):    #calculates the derivative of the sigmoid function
    return sigmoid(x)*(1-sigmoid(x))

#train our neural network that will be able to predict whether a person is
#obese or not.

# An epoch is basically the number of times we want to train the algorithm on our data.
#We will train the algorithm on our data 20,000 times. The ultimate goal i
#s to minimize the error.

for epoch in range(20000): 
    inputs = feature_set

#Here we find the dot product of the input and the weight vector and add bias to it.

    # feedforward step1
    XW = np.dot(feature_set, weights) + bias
   
#We pass the dot product through the sigmoid activation function

    #feedforward step2
    z = sigmoid(XW)
   
#The variable z contains the predicted outputs. The first step of the backpropagation is to find the error.

    # backpropagation step 1
    error = z - labels

    print(error.sum())

    # backpropagation step 2
    dcost_dpred = error
    dpred_dz = sigmoid_der(z)
   
#Here we have the z_delta variable, which contains the product of dcost_dpred and dpred_dz.
#Instead of looping through each record and multiplying the input with corresponding z_delta,
#we take the transpose of the input feature matrix and multiply it with the z_delta.
#Finally, we multiply the learning rate variable lr with the derivative to increase the speed of convergence.

    z_delta = dcost_dpred * dpred_dz

    inputs = feature_set.T
    weights -= lr * np.dot(inputs, z_delta)

    for num in z_delta:
        bias -= lr * num


#You can see that error is extremely small at the end of the
#training of our neural network.
#At this point of time our weights and bias will have values that can be used to detect whether a person is diabetic or not,
#based on his smoking habits, obesity, and exercise habits.

#TEST : suppose we have a record of a patient that comes
#in who smokes, is not obese, and doesn't exercise.
#Let's find if he is likely to be diabetic or not. The input feature will look like this: [1,0,0].

single_point = np.array([1,0,0]) 
result = sigmoid(np.dot(single_point, weights) + bias) 
print(result)




Monday 30 December 2019

GLA Python

str = 'Hello World!’

print(str) # Prints complete string
print(str[0]) # Prints first character of the string
print(str[2:5]) # Prints characters starting from 3rd to 5th
print(str[2:]) # Prints string starting from 3rd character
print(str * 2) # Prints string two times
print(str + "TEST") # Prints concatenated string
print(str[:-2])    # Hello Worl
print(str[::-1])  # Reverse   !dlroW olleH
print(str[::-2])  # Alternative reverse    !lo le
len(str) # 12 including space
str.count(' ')   # Space Count

______________________________________________________________

list = [ ‘xyz', 123, 1.23, ‘RAM', 17.5 ]
tinylist = [123, ‘RAM']
print(list) # Prints complete list
print(list[0]) # Prints first element of the list
print(list[1:3]) # Prints elements starting from 2nd till 3rd
print(list[2:]) # Prints elements starting from 3rd element
print(tinylist * 2) # Prints list two times
print(list + tinylist) # Prints concatenated lists
list.append(“Manish”) #Applicable
print(“list[3:] = ", list[3:]) 

_____________________________________________________________

tuple = (‘xyz', 123, 1.23, ‘RAM', 17.5 )
tinytuple = (123, ‘RAM‘)
print(tuple) # Prints complete list
print(tuple[0]) # Prints first element of the list
print(tuple[1:3]) # Prints elements starting from 2nd till 3rd
print(tuple[2:]) # Prints elements starting from 3rd element
print(tinytuple * 2) # Prints list two times
print (tuple + tinytuple) # Prints concatenated lists
tuple.append(‘Manish’) # Not Applicable
____________________________________________________________

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': ‘RAM','code:8989:, 'dept': ‘IT'}
print(dict['one']) # Prints value for 'one' key
print(dict[2]) # Prints value for 2 key
print(tinydict) # Prints complete dictionary
print(tinydict.keys()) # Prints all the keys
print(tinydict.values()) # Prints all the values

________________________________________________________

num1 = 1.5

num2 = 6.3

sum = float(num1) + float(num2)

 print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

____________________________________________________________

import calendar
 yy = int(input("Enter year: "))
mm = int(input("Enter month: "))
print(calendar.month(yy, mm))

_________________________________________________________


import calendar
yy = int(input("Enter year: "))
mm = int(input("Enter starting month: "))
mm1 = int(input("Enter ending month: "))
for i in range(mm,mm1):
       print(calendar.month(yy,i))

calendar.calender(yy)


Monday 23 December 2019

Vignan University

pragma solidity ^0.4.0;
contract SimpleStorage{
    uint a;
    uint b;
    uint c;
    function set( uint balu, uint bunny)public{
        a = balu;
       b = bunny;
    }
    function add()public constant returns(uint){
        c = a+b;
        return c;
    }
     function sub()public constant returns(uint){
        c = a-b;
        return c;
    } function mul()public constant returns(uint){
        c = a*b;
        return c;
    } function div()public constant returns(uint){
        c = a/b;
        return c;
    }
   
}
_______________________________________________________________________________


pragma solidity ^0.4.0;
contract SimpleStorage{
    uint a;
    function initial( uint balu)public{
        a = balu;
    }
     function Shop1( uint balu)public{
        a = a-balu;
    }
     function Shop2(uint balu)public{
          a = a-balu;
    }
     function add(uint balu)public{
          a = a+balu;
    }
    function balance()public constant returns(uint){
        return a;
    }}


_______________________________________________________________________________


pragma solidity ^0.4.21;

contract Election{
    struct Canditate{
        string name;
        uint voteCount;
    }
    struct Voter{
        bool authorized;
        bool voted;
        uint vote;
    }
    address public owner;
    string public electionName;
 
    mapping(address => Voter) public Voters;
    Canditate[] public Canditates;
    uint public totalVotes;
 
    modifier ownerOnly(){
        require(msg.sender == owner);
        _;
    }
    function Election(string _name) public {
        owner = msg.sender;
        electionName = _name;
    }
    function getNumberCandidates() public view returns(uint) {
        return Canditates.length;
    }
    function addCandidate(string _name) ownerOnly public {
        Canditates.push(Canditate(_name,0));
    }
    function authorize(address _person) ownerOnly public {
        Voters[_person].authorized = true;
    }
    function vote(uint _voterIndex) public {
        require(!Voters[msg.sender].voted);
        require(Voters[msg.sender].authorized);
     
        Voters[msg.sender].vote = _voterIndex;
        Voters[msg.sender].voted = true;
         Canditates[_voterIndex].voteCount += 1;
         totalVotes += 1;
    }
 
    function end() ownerOnly public {
        selfdestruct(owner);

    }}
_______________________________________________________________

pragma solidity ^0.4.0;
contract Payroll {
    // define variables
    address public CompanyOwner;

    uint employeeId;

    // create Employee object
    struct Employee {
        uint employeeId;
        address employeeAddress;
        uint wages;
        uint balance;
    }

    // employees contain Employee
    Employee[] public employees;

    // run this on contract creation just once
    function Payroll() {
        // make CompanyOwner the person who deploys the contract
        CompanyOwner = msg.sender;
        employeeId = 0;
        // add the company owner as an employee with a wage of 0
        AddEmployee(msg.sender, 0);
    }

    // function for checking number of employees
    function NumberOfEmployees() returns (uint _numEmployees) {
        return employeeId;
    }

    // allows function initiator to withdraw funds if they're an employee equal to their balance
    function WithdrawPayroll() returns (bool _success) {
        var employeeId = GetCurrentEmployeeId();
        if (employeeId != 999999) {
            // they are an employee
            if (employees[employeeId].balance > 0) {
                // if they have a balance
                if (this.balance >= employees[employeeId].balance) {
                    // if the balance of the contract is greater than or equal to employee balance
                    // then send them the money from the contract and set balance back to 0
                    msg.sender.send(employees[employeeId].balance);
                    employees[employeeId].balance = 0;
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    function GetCurrentEmployeeId() returns (uint _employeeId) {
        // loop through employees
        for (var i = 0; i < employees.length; i++) {
            // if the initiator of the function's address exists in the employeeAddress area of an Employee, return ID
            if (msg.sender == employees[i].employeeAddress) {
                return employees[i].employeeId;
            }
        }
        return 999999;
    }

    // function for getting an ID by address if needed
    function GetEmployeeIdByAddress(address _employee) returns (uint _employeeId) {
        for (var i = 0; i < employees.length; i++) {
            if (_employee == employees[i].employeeAddress) {
                return employees[i].employeeId;
            }
        }
        return 999999;
    }


    /* OWNER ONLY FUNCTIONS */
    // add an employee given an address and wages
    function AddEmployee(address _employee, uint _wages) returns (bool _success) {
        if (msg.sender != CompanyOwner) {
            return false;
        } else {
            employees.push(Employee(employeeId, _employee, _wages, 0));
            employeeId++;
            return true;
        }
    }

    // pay the employee their wages given an employee ID
    function PayEmployee(uint _employeeId) returns (bool _success) {
        if (msg.sender != CompanyOwner) {
            return false;
        } else {
            // TODO: need to figure out how to check to make sure employees[_employeeId] exists
            employees[_employeeId].balance += employees[_employeeId].wages;
            return true;
        }
    }

    // modify the employee wages given an employeeId and a new wage
    function ModifyEmployeeWages(uint _employeeId, uint _newWage) returns (bool _success) {
        if (msg.sender != CompanyOwner) {
            return false;
        } else {
            // TODO: need to figure out how to check to make sure employees[_employeeId] exists
            // change employee wages to new wage
            employees[_employeeId].wages = _newWage;
            return true;
        }
    }

    // check how much money is in the contract
    function CheckContractBalance() returns (uint _balance) {
        return this.balance;
    }

}

Friday 13 December 2019

SA


hadoop jar complete.jar org.myorg.MrManager /user/cloudera/flume/events_manish /user/cloudera/sentiment/output -no_case -skip stop-words.txt -pos pos-words.txt -neg neg-words.txt

conf

# example.conf: A single-node Flume configuration

# Name the components on this agent
a1.sources = r1
a1.sinks = k1
a1.channels = c1

# Describe/configure the source
a1.sources.r1.type = netcat
a1.sources.r1.bind = localhost
a1.sources.r1.port = 44444

# Describe the sink
a1.sinks.k1.type = logger

# Use a channel which buffers events in memory
a1.channels.c1.type = memory
a1.channels.c1.capacity = 1000
a1.channels.c1.transactionCapacity = 100

# Bind the source and sink to the channel
a1.sources.r1.channels = c1
a1.sinks.k1.channel = c1
a1.sinks.k1.type= HDFS
a1.sinks.k1.fileType=DataStream
a1.sinks.k1.hdfs.path = hdfs://localhost:8020/user/flume/events

PIG

A = LOAD '/user/cloudera/movies' using PigStorage(',') as (col1: chararray,col2:chararray,col3:chararray,col4:chararray,col5:chararray);

DUMP A;

B = FOREACH A generate col1,col4,col5;

DUMP B;

Thursday 12 December 2019

RVIM HIVE


CREATE TABLE IF NOT EXISTS vnr_table
(col1 int COMMENT 'col1',
col2 string,
col3 int,
col4 DECIMAL,
col5 int)
COMMENT 'This is test table'

ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS TEXTFILE;

Desc vnr_table;

load data LOCAL INPATH '/home/cloudera/Desktop/movies_data.csv' OVERWRITE INTO TABLE vnr_table;

select * from vnr_table;

RVIM

public class AddTwoIntegers {
    public static void main(String[] args) {
     
        int first = 10;
        int second = 20;
        int sum = first + second;
        System.out.println("The sum is: " + sum);
    }
}


________________________________________________________


import java.util.Scanner;

public class Main {
  public static void main(String[] args) 
  {
    Scanner input = new Scanner (System.in);
    System.out.print("Input the first number: ");
    int num1 = input.nextInt();
    System.out.print("Input the second number: ");
    int num2 = input.nextInt();
    int sum = num1 + num2;
    System.out.println();
    System.out.println("Sum: "+sum);
  }
}

__________________________________________________


public class WordCount { 
      static int wordcount(String string) 
        { 
          int count=0; 
     
            char ch[]= new char[string.length()];    
            for(int i=0;i<string.length();i++) 
            { 
                ch[i]= string.charAt(i); 
                if( ((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!=' ')&&(i==0)) ) 
                    count++; 
            } 
            return count; 
        } 
      public static void main(String[] args) { 
          String string ="    Hi How are you I am fine"; 
         System.out.println(wordcount(string) + " words.");  
    } 
}
_________________________________________________

Mapreduce Addition

package aa;

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class GlobalNumberAddition {

 public static class GlobalNumberAdditionMapper
 extends Mapper < Object, Text, Text, IntWritable > {

  int sum = 0;

  public void map(Object key, Text value, Context context) throws IOException,
  InterruptedException {
   StringTokenizer itr = new StringTokenizer(value.toString());
   while (itr.hasMoreTokens()) {
    String str = itr.nextToken();
    sum = sum + Integer.parseInt(str);
   }
  }

  public void cleanup(Context context) throws IOException,
  InterruptedException {
   context.write(new Text("Addition of numbers is"), new IntWritable(sum));
  }
 }

 public static void main(String[] args) throws Exception {
  Configuration conf = new Configuration();
  Job job = Job.getInstance(conf, "Global Addition of Numbers");
  job.setJarByClass(GlobalNumberAddition.class);
  job.setMapperClass(GlobalNumberAdditionMapper.class);
  job.setNumReduceTasks(0);
  job.setOutputKeyClass(Text.class);
  job.setOutputValueClass(IntWritable.class);
  FileInputFormat.addInputPath(job, new Path(args[0]));
  FileOutputFormat.setOutputPath(job, new Path(args[1]));
  System.exit(job.waitForCompletion(true) ? 0 : 1);
 }

}

Tuesday 3 December 2019

Solidity5

pragma solidity ^0.4.0;
contract Payroll {
    // define variables
    address public CompanyOwner;
 
    uint employeeId;
 
    // create Employee object
    struct Employee {
        uint employeeId;
        address employeeAddress;
        uint wages;
        uint balance;
    }
 
    // employees contain Employee
    Employee[] public employees;
 
    // run this on contract creation just once
    function Payroll() {
        // make CompanyOwner the person who deploys the contract
        CompanyOwner = msg.sender;
        employeeId = 0;
        // add the company owner as an employee with a wage of 0
        AddEmployee(msg.sender, 0);
    }
 
    // function for checking number of employees
    function NumberOfEmployees() returns (uint _numEmployees) {
        return employeeId;
    }
 
    // allows function initiator to withdraw funds if they're an employee equal to their balance
    function WithdrawPayroll() returns (bool _success) {
        var employeeId = GetCurrentEmployeeId();
        if (employeeId != 999999) {
            // they are an employee
            if (employees[employeeId].balance > 0) {
                // if they have a balance
                if (this.balance >= employees[employeeId].balance) {
                    // if the balance of the contract is greater than or equal to employee balance
                    // then send them the money from the contract and set balance back to 0
                    msg.sender.send(employees[employeeId].balance);
                    employees[employeeId].balance = 0;
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
 
    function GetCurrentEmployeeId() returns (uint _employeeId) {
        // loop through employees
        for (var i = 0; i < employees.length; i++) {
            // if the initiator of the function's address exists in the employeeAddress area of an Employee, return ID
            if (msg.sender == employees[i].employeeAddress) {
                return employees[i].employeeId;
            }
        }
        return 999999;
    }
 
    // function for getting an ID by address if needed
    function GetEmployeeIdByAddress(address _employee) returns (uint _employeeId) {
        for (var i = 0; i < employees.length; i++) {
            if (_employee == employees[i].employeeAddress) {
                return employees[i].employeeId;
            }
        }
        return 999999;
    }
 
 
    /* OWNER ONLY FUNCTIONS */
    // add an employee given an address and wages
    function AddEmployee(address _employee, uint _wages) returns (bool _success) {
        if (msg.sender != CompanyOwner) {
            return false;
        } else {
            employees.push(Employee(employeeId, _employee, _wages, 0));
            employeeId++;
            return true;
        }
    }
 
    // pay the employee their wages given an employee ID
    function PayEmployee(uint _employeeId) returns (bool _success) {
        if (msg.sender != CompanyOwner) {
            return false;
        } else {
            // TODO: need to figure out how to check to make sure employees[_employeeId] exists
            employees[_employeeId].balance += employees[_employeeId].wages;
            return true;
        }
    }
 
    // modify the employee wages given an employeeId and a new wage
    function ModifyEmployeeWages(uint _employeeId, uint _newWage) returns (bool _success) {
        if (msg.sender != CompanyOwner) {
            return false;
        } else {
            // TODO: need to figure out how to check to make sure employees[_employeeId] exists
            // change employee wages to new wage
            employees[_employeeId].wages = _newWage;
            return true;
        }
    }
 
    // check how much money is in the contract
    function CheckContractBalance() returns (uint _balance) {
        return this.balance;
    }
 
}

Solidity4

pragma solidity ^0.4.21;

contract Election{
    struct Canditate{
        string name;
        uint voteCount;
    }
    struct Voter{
        bool authorized;
        bool voted;
        uint vote;
    }
    address public owner;
    string public electionName;
   
    mapping(address => Voter) public Voters;
    Canditate[] public Canditates;
    uint public totalVotes;
   
    modifier ownerOnly(){
        require(msg.sender == owner);
        _;
    }
    function Election(string _name) public {
        owner = msg.sender;
        electionName = _name;
    }
    function getNumberCandidates() public view returns(uint) {
        return Canditates.length;
    }
    function addCandidate(string _name) ownerOnly public {
        Canditates.push(Canditate(_name,0));
    }
    function authorize(address _person) ownerOnly public {
        Voters[_person].authorized = true;
    }
    function vote(uint _voterIndex) public {
        require(!Voters[msg.sender].voted);
        require(Voters[msg.sender].authorized);
       
        Voters[msg.sender].vote = _voterIndex;
        Voters[msg.sender].voted = true;
         Canditates[_voterIndex].voteCount += 1;
         totalVotes += 1;
    }
   
    function end() ownerOnly public {
        selfdestruct(owner);
    }}

Solidity3

pragma solidity ^0.4.0;
contract SimpleStorage{
    uint a;
    function initial( uint balu)public{
        a = balu;
    }
     function Shop1( uint balu)public{
        a = a-balu;
    }
     function Shop2(uint balu)public{
          a = a-balu;
    }
     function add(uint balu)public{
          a = a+balu;
    }
    function balance()public constant returns(uint){
        return a;
    }}

Solidity2

pragma solidity ^0.4.0;
contract SimpleStorage{
    uint a;
    uint b;
    uint c;
    function set( uint balu, uint bunny)public{
        a = balu;
       b = bunny;
    }
    function add()public constant returns(uint){
        c = a+b;
        return c;
    }
     function sub()public constant returns(uint){
        c = a-b;
        return c;
    } function mul()public constant returns(uint){
        c = a*b;
        return c;
    } function div()public constant returns(uint){
        c = a/b;
        return c;
    }
   
}

Solidity1

pragma solidity ^0.4.0;
contract AddInteger{
  uint private c;
function addition(uint _a, uint _b) public constant returns(uint)
  {
     c = _a+_b;
     return c;
  } }

Monday 25 November 2019

Image Processing

import numpy as np
import cv2

# multiple cascades: https://github.com/Itseez/opencv/tree/master/data/haarcascades

#https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml
face_cascade = cv2.CascadeClassifier('D:\\opencv\\OpenCV Final Softwares\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_default.xml')
#https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_eye.xml
eye_cascade = cv2.CascadeClassifier('D:\\opencv\\OpenCV Final Softwares\\opencv\\sources\\data\\haarcascades\\haarcascade_eye.xml')

cap = cv2.VideoCapture(0)

while 1:
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
      cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
      roi_gray = gray[y:y+h, x:x+w]
      roi_color = img[y:y+h, x:x+w]
      eyes = eye_cascade.detectMultiScale(roi_gray)
      for(ex,ey,ew,eh) in eyes:
            cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

    cv2.imshow('img',img)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()

Wednesday 20 November 2019

DevOps Day1 - Experiments

Build Python apps



https://docs.microsoft.com/en-us/azure/devops/pipelines/ecosystems/python?view=azure-devops


Use CI/CD to deploy a Python web app to Azure App Service on Linux



https://docs.microsoft.com/en-us/azure/devops/pipelines/ecosystems/python-webapp?view=azure-devops

_______________________________________________

trigger:
master

pool:
  vmImage'ubuntu-latest'
strategy:
  matrix:
    Python27:
      python.version'2.7'

steps:
taskUsePythonVersion@0
  inputs:
    versionSpec'$(python.version)'
  displayName'Use Python $(python.version)'
scriptpython "a1.py"

taskPythonScript@0
  inputs:
    scriptSource'inline'
    script: |
      print('Hello world 1')
      print('Hello world 2')

Monday 18 November 2019

DT-EA

install.package("party")

library(party)

View(readingSkills)

input =  readingSkills[c(1:105),]

output = ctree(nativeSpeaker ~ age + shoeSize + score, data = input)

plot(output)

Sunday 10 November 2019

Project

Part One: Text Mining and Exploratory Analysis
Part Two: Sentiment Analysis and Topic Modeling with NLP
Part Three: Predictive Analytics using Machine Learning
___________________________________________________________________
Part 1

https://www.datacamp.com/community/tutorials/R-nlp-machine-learning

Part 2

https://www.datacamp.com/community/tutorials/sentiment-analysis-R

https://www.datacamp.com/community/tutorials/ML-NLP-lyric-analysis

Part 3

https://www.datacamp.com/community/tutorials/predictive-analytics-machine-learning




_______________________________________________________________


https://github.com/thanujhaa/R-Python-Machine-Learning-Projects



Tuesday 22 October 2019

Captcha

phptextClass.php

?php

class phptextClass
{
public function phpcaptcha($textColor,$backgroundColor,$imgWidth,$imgHeight,$noiceLines=0,$noiceDots=0,$noiceColor='#162453')
{
/* Settings */
$text=$this->random();
$font = './font/monofont.ttf';/* font */
$textColor=$this->hexToRGB($textColor);
$fontSize = $imgHeight * 0.75;

$im = imagecreatetruecolor($imgWidth, $imgHeight);
$textColor = imagecolorallocate($im, $textColor['r'],$textColor['g'],$textColor['b']);

$backgroundColor = $this->hexToRGB($backgroundColor);
$backgroundColor = imagecolorallocate($im, $backgroundColor['r'],$backgroundColor['g'],$backgroundColor['b']);

/* generating lines randomly in background of image */
if($noiceLines>0){
$noiceColor=$this->hexToRGB($noiceColor);
$noiceColor = imagecolorallocate($im, $noiceColor['r'],$noiceColor['g'],$noiceColor['b']);
for( $i=0; $i<$noiceLines; $i++ ) {
imageline($im, mt_rand(0,$imgWidth), mt_rand(0,$imgHeight),
mt_rand(0,$imgWidth), mt_rand(0,$imgHeight), $noiceColor);
}}

if($noiceDots>0){/* generating the dots randomly in background */
for( $i=0; $i<$noiceDots; $i++ ) {
imagefilledellipse($im, mt_rand(0,$imgWidth),
mt_rand(0,$imgHeight), 3, 3, $textColor);
}}

imagefill($im,0,0,$backgroundColor);
list($x, $y) = $this->ImageTTFCenter($im, $text, $font, $fontSize);
imagettftext($im, $fontSize, 0, $x, $y, $textColor, $font, $text);

imagejpeg($im,NULL,90);/* Showing image */
header('Content-Type: image/jpeg');/* defining the image type to be shown in browser widow */
imagedestroy($im);/* Destroying image instance */
if(isset($_SESSION)){
$_SESSION['captcha_code'] = $text;/* set random text in session for captcha validation*/
}
}

/*function to convert hex value to rgb array*/
protected function hexToRGB($colour)
{
        if ( $colour[0] == '#' ) {
$colour = substr( $colour, 1 );
        }
        if ( strlen( $colour ) == 6 ) {
list( $r, $g, $b ) = array( $colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5] );
        } elseif ( strlen( $colour ) == 3 ) {
list( $r, $g, $b ) = array( $colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2] );
        } else {
return false;
        }
        $r = hexdec( $r );
        $g = hexdec( $g );
        $b = hexdec( $b );
        return array( 'r' => $r, 'g' => $g, 'b' => $b );
}


/*function to get center position on image*/
protected function ImageTTFCenter($image, $text, $font, $size, $angle = 8)
{
$xi = imagesx($image);
$yi = imagesy($image);
$box = imagettfbbox($size, $angle, $font, $text);
$xr = abs(max($box[2], $box[4]))+5;
$yr = abs(max($box[5], $box[7]));
$x = intval(($xi - $xr) / 2);
$y = intval(($yi + $yr) / 2);
return array($x, $y);
}

}
?>
_________________________________________________

demo.php

<?php session_start();

if(isset($_POST['Submit'])){
// code for check server side validation
if(empty($_SESSION['captcha_code'] ) || strcasecmp($_SESSION['captcha_code'], $_POST['captcha_code']) != 0){ 
$msg="<span style='color:red'>The Validation code does not match!</span>";// Captcha verification is incorrect.
}else{// Captcha verification is Correct. Final Code Execute here!
$msg="<span style='color:green'>The Validation code has been matched.</span>";
}
}
?>
 
  <form action="" method="post" name="form1" id="form1" >
  <table width="400" border="0" align="center" cellpadding="5" cellspacing="1" class="table">
    <?php if(isset($msg)){?>
    <tr>
      <td colspan="2" align="center" valign="top"><?php echo $msg;?></td>
    </tr>
    <?php } ?>
    <tr>
      <td align="right" valign="top"> Validation code:</td>
      <td><img src="captcha.php?rand=<?php echo rand();?>" id='captchaimg'><br>
        <label for='message'>Enter the code above here :</label>
        <br>
        <input id="captcha_code" name="captcha_code" type="text">
        <br>
        Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh.</td>
    </tr>
    <tr>
      <td> </td>
      <td><input name="Submit" type="submit" onclick="return validate();" value="Submit" class="button1"></td>
    </tr>
  </table>
</form>
________________________________________
captcha.php


<?php
session_start();
include("./phptextClass.php");

/*create class object*/
$phptextObj = new phptextClass();
/*phptext function to genrate image with text*/
$phptextObj->phpcaptcha('#162453','#fff',120,40,10,25);
 ?>

PHP Calc

<?php

$page = $_GET['page'];

// Defining the "calc" class
class calc {
     var $number1;
     var $number2;

          function add($number1,$number2)
          {
                   $result =$number1 + $number2;
                    echo("The sum of $number1 and $number2 is $result<br><br>");
                    echo("$number1 + $number2 = $result");
                    exit;
           }

          function subtract($number1,$number2)
          {
                   $result =$number1 - $number2;
                    echo("The difference of $number1 and $number2 is $result<br><br>");
                    echo("$number1 &#045 $number2 = $result");
                    exit;
           }

          function divide($number1,$number2)
          {
                   $result =$number1 / $number2;
                    echo("$number1 divided by $number2 is $result<br><br>");
                    echo("$number1 ÷ $number2 = $result");
                    exit;
           }

          function multiply($number1,$number2)
          {
                   $result =$number1 * $number2;
                    echo("The product of $number1 and $number2 is $result<br><br>");
                    echo("$number1 x $number2 = $result");
                    exit;
           }
}
$calc = new calc();
?>
<TITLE>PHP Calculator v1</TITLE>
<form name="calc" action="?page=calc" method="POST">
Number 1: <input type=text name=value1><br>
Number 2: <input type=text name=value2><br>
Operation: <input type=radio name=oper value="add">Addition <input type=radio name=oper value="subtract">Subtraction <input type=radio name=oper value="divide">Division <input type=radio name=oper value="multiply">Multiplication</input><br>
<input type=submit value="Calculate">
</form>
<?php
if($page == "calc"){
$number1 = $_POST['value1'];
$number2 = $_POST['value2'];
$oper = $_POST['oper'];
     if(!$number1){
          echo("You must enter number 1!");
          exit;
     }
     if(!$number2){
          echo("You must enter number 2!");
          exit;
     }
     if(!$oper){
          echo("You must select an operation to do with the numbers!");
          exit;
     }
     if(!eregi("[0-9]", $number1)){
          echo("Number 1 MUST be numbers!");
          exit;
     }
     if(!eregi("[0-9]", $number2)){
          echo("Number 2 MUST be numbers!");
          exit;
     }
     if($oper == "add"){
          $calc->add($number1,$number2);
     }
     if($oper == "subtract"){
          $calc->subtract($number1,$number2);
     }
     if($oper == "divide"){
          $calc->divide($number1,$number2);
     }
     if($oper == "multiply"){
          $calc->multiply($number1,$number2);
     }
}
?>

PHP New

login.php

<form action="" method="post" name="Login_Form">
  <table width="400" border="0" align="center" cellpadding="5" cellspacing="1" class="Table">
    <?php if(isset($msg)){?>
    <tr>
      <td colspan="2" align="center" valign="top"><?php echo $msg;?></td>
    </tr>
    <?php } ?>
    <tr>
      <td colspan="2" align="left" valign="top"><h3>Login</h3></td>
    </tr>
    <tr>
      <td align="right" valign="top">Username</td>
      <td><input name="Username" type="text" class="Input"></td>
    </tr>
    <tr>
      <td align="right">Password</td>
      <td><input name="Password" type="password" class="Input"></td>
    </tr>
    <tr>
      <td> </td>
      <td><input name="Submit" type="submit" value="Login" class="Button3"></td>
    </tr>
  </table>
</form>

______________________________________________________
Step 2: Next we need to write a php script to check the
login authentication.


<?php session_start(); /* Starts the session */

/* Check Login form submitted */
if(isset($_POST['Submit'])){
/* Define username and associated password array */
$logins = array('Alex' => '123456','username1' => 'password1','username2' => 'password2');

/* Check and assign submitted Username and Password to new variable */
$Username = isset($_POST['Username']) ? $_POST['Username'] : '';
$Password = isset($_POST['Password']) ? $_POST['Password'] : '';

/* Check Username and Password existence in defined array */
if (isset($logins[$Username]) && $logins[$Username] == $Password){
/* Success: Set session variables and redirect to Protected page  */
$_SESSION['UserData']['Username']=$logins[$Username];
header("location:index.php");
exit;
} else {
/*Unsuccessful attempt: Set error message */
$msg="<span style='color:red'>Invalid Login Details</span>";
}
}
?>

____________________________________________________________

Step 3: If the login is correct then we need to redirect page to
 protected area.So need an protected script page too.

index.php

<?php session_start(); /* Starts the session */

if(!isset($_SESSION['UserData']['Username'])){
header("location:login.php");
exit;
}
?>
__________________________________________________________

index.php

<?php session_start(); /* Starts the session */

if(!isset($_SESSION['UserData']['Username'])){
header("location:login.php");
exit;
}
?>

Congratulation! You have logged into password protected page.
<a href="logout.php">Click here</a> to Logout.
__________________________________________________________

logout.php

<?php session_start(); /* Starts the session */
session_destroy(); /* Destroy started session */
header("location:login.php");  /* Redirect to login page */
exit;
?>
Congratulation! You have logged into password protected page. <a href="logout.php">Click here</a> to Logout.
Ready, now our login system perfectly done but we also need to provide a logout facility to user, so we require to create a logout page.

logout.php
Example:
<?php session_start(); /* Starts the session */
session_destroy(); /* Destroy started session */
header("location:login.php");  /* Redirect to login page */
exit;
?>

Thursday 17 October 2019

DT -EA

install.packages("party")
library(party)
View(readingSkills)

input = readingSkills[c(1:105),]

View(input)

output = ctree(
  nativeSpeaker ~ age + shoeSize + score,
  data = input)

plot(output)

Sunday 13 October 2019

Kmeans

library(ggplot2)

df <- data.frame(age = c(18, 21, 22, 24, 26, 26, 27, 30, 31, 35, 39, 40, 41, 42, 44, 46, 47, 48, 49, 54),
    spend = c(10, 11, 22, 15, 12, 13, 14, 33, 39, 37, 44, 27, 29, 20, 28, 21, 30, 31, 23, 24))

ggplot(df, aes(x = age, y = spend)) + geom_point()

____________________________________________________________

CODE: HIERACHICAL CLUSTERING

clusters <- hclust(dist(iris[, 3:4]))
plot(clusters)

clusterCut <- cutree(clusters, 3)

plot(clusterCut,type="p")
table(clusterCut, iris$Species)

ggplot(iris, aes(Petal.Length, Petal.Width, color = iris$Species)) +
  geom_point(alpha = 0.4, size = 3.5) + geom_point(col = clusterCut) +
  scale_color_manual(values = c('black', 'red', 'green'))

_______________________________________

install.packages(“devtools”)
install.packages(“factoextra”)

library(devtools)
library(factoextra)
 
data("multishapes")
df <- multishapes[, 1:2]
set.seed(123)
km.res <- kmeans(df, 5, nstart = 25)
fviz_cluster(km.res, df, frame = FALSE, geom = "point")

Saturday 12 October 2019

LR shiny


library(shiny)

ui <- fluidPage(
  pageWithSidebar(
   
    headerPanel("HP prediction"),
   
    sidebarPanel(
      numericInput(inputId = "noofCYL",
                   label = "noofCYL",
                   min = 40, max = 160, value = 100),
      actionButton('go',"Predict")
    ),
   
    mainPanel( textOutput("value") )
  )
)




server <- function(input, output, session) {
 
  data <- reactiveValues()
  observeEvent(input$go,{
    #browser()
    data$var <-input$noofCYL
   
    newPredict = data.frame(cyl=data$var)
   
    modelLM = lm(hp~cyl, data = mtcars)
   
    data$op = predict(modelLM, newPredict)
  })
 
  lstat = renderText({data$var})
 
  output$value <- renderPrint({data$op})
}

shinyApp(ui, server)