Tuesday, 21 February 2023

Google autosuggest address

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel</title>
    <!-- Fonts -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"
        integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.6.3.min.js"
        integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.min.js"></script>
    <style> .pac-container.pac-logo { z-index: 9999; }  </style>
</head>
<body>
    <div class="relative flex items-top justify-center min-h-screen bg-gray-100 dark:bg-gray-900 sm:items-center py-4 sm:pt-0">
        <div class="grid grid-cols-1 md:grid-cols-2">
            <div class="container mt-2">
                <div class="row">
                    <div class="col-md-6  m-auto">
                        <div class="card shadow">
                            <div class="card-body">
                                <!-- Trigger the modal with a button -->
                                <input type="text" name="currentlocation" id="currentlocation"
                                    class="form-control col-md-6" placeholder="Select Location" readonly
                                    data-toggle="modal" data-target="#myModal">
                                <!-- Modal -->
                                <div id="myModal" class="modal fade" role="dialog">
                                    <div class="modal-dialog col-md-5 modal-sm">

                                        <!-- Modal content-->
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <button type="button" class="close"
                                                    data-dismiss="modal">&times;</button>
                                                <h4 class="modal-title">Search Location</h4>
                                            </div>
                                            <div class="modal-body">
                                                <div class="card-body">
                                                    <div class="form-group">
                                                        <input type="text" name="autocomplete" id="autocomplete"
                                                            class="form-control" placeholder="Enter a city">
                                                    </div>
                                                    <div class="form-group" id="lat_area">
                                                        <label for="latitude"> Latitude </label>
                                                        <input type="text" name="latitude" id="latitude"
                                                            class="form-control">
                                                    </div>
                                                    <div class="form-group" id="long_area">
                                                        <label for="latitude"> Longitude </label>
                                                        <input type="text" name="longitude" id="longitude"
                                                            class="form-control">
                                                    </div>
                                                    <br>
                                                    <div id="ucurrentlocation">Use Current Location</div>
                                                </div>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-default"
                                                    data-dismiss="modal">Close</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
                integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
                crossorigin="anonymous"></script>
            <script
                src="https://maps.google.com/maps/api/js?key=xxxxx&libraries=places&callback=initAutocomplete"
                type="text/javascript"></script>
            <script src="address.js"></script>
        </div>
    </div>
    <script> $("#ucurrentlocation").click(function(event) { getLocation(); });

    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition, showError);
        } else {
            div.innerHTML = "The Browser Does not Support Geolocation";
        }
    }

    function showPosition(position) {
        var location = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + position.coords.latitude + "," +
            position.coords.longitude + "&key=xxxxx"
        $.get(location, function(data) {
            $("#currentlocation").val(data.results[0].formatted_address);
        });
    }

    function showError(error) {
        if (error.PERMISSION_DENIED) {
            div.innerHTML = "The User have denied the request for Geolocation.";
        }
    }
    getLocation();
    </script>
</body>
</html>

*************************************************************

address.js            

$(document).ready(function () {
    $("#lat_area").addClass("d-none");
    $("#long_area").addClass("d-none");
});
google.maps.event.addDomListener(window, "load", initialize);
function initialize() {
    var input = document.getElementById("autocomplete");
    var autocomplete = new google.maps.places.Autocomplete(input);
    autocomplete.addListener("place_changed", function () {
        var place = autocomplete.getPlace();      
        $("#latitude").val(place.geometry["location"].lat());
        $("#longitude").val(place.geometry["location"].lng());
        // --------- show lat and long ---------------
        $("#lat_area").removeClass("d-none");
        $("#long_area").removeClass("d-none");
        var newadd =$("#autocomplete").val();
        $("#currentlocation").val(newadd);
        $(".close").click();
    });
}

Sunday, 19 February 2023

Create new scratch card.

 Html

<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Scratch Card</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
    <div class="container">
      <div class="base">
        <h4>You Won</h4>
        <h3>$20</h3>
      </div>
      <canvas id="scratch" width="200" height="200"></canvas>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>


Scriptjs

let canvas = document.getElementById("scratch");
let context = canvas.getContext("2d");

const init = () => {
  let gradientColor = context.createLinearGradient(0, 0, 135, 135);
  gradientColor.addColorStop(0, "#c3a3f1");
  gradientColor.addColorStop(1, "#6414e9");
  context.fillStyle = gradientColor;
  context.fillRect(0, 0, 200, 200);
};

//initially mouse X and mouse Y positions are 0
let mouseX = 0;
let mouseY = 0;
let isDragged = false;

//Events for touch and mouse
let events = {
  mouse: {
    down: "mousedown",
    move: "mousemove",
    up: "mouseup",
  },
  touch: {
    down: "touchstart",
    move: "touchmove",
    up: "touchend",
  },
};

let deviceType = "";

//Detech touch device
const isTouchDevice = () => {
  try {
    //We try to create TouchEvent. It would fail for desktops 
and throw error.
    document.createEvent("TouchEvent");
    deviceType = "touch";
    return true;
  } catch (e) {
    deviceType = "mouse";
    return false;
  }
};

//Get left and top of canvas
let rectLeft = canvas.getBoundingClientRect().left;
let rectTop = canvas.getBoundingClientRect().top;

//Exact x and y position of mouse/touch
const getXY = (e) => {
  mouseX = (!isTouchDevice() ? e.pageX : e.touches[0].pageX) - rectLeft;
  mouseY = (!isTouchDevice() ? e.pageY : e.touches[0].pageY) - rectTop;
};

isTouchDevice();
//Start Scratch
canvas.addEventListener(events[deviceType].down, (event) => {
  isDragged = true;
  //Get x and y position
  getXY(event);
  scratch(mouseX, mouseY);
});

//mousemove/touchmove
canvas.addEventListener(events[deviceType].move, (event) => {
  if (!isTouchDevice()) {
    event.preventDefault();
  }
  if (isDragged) {
    getXY(event);
    scratch(mouseX, mouseY);
  }
});

//stop drawing
canvas.addEventListener(events[deviceType].up, () => {
  isDragged = false;
});

//If mouse leaves the square
canvas.addEventListener("mouseleave", () => {
  isDragged = false;
});

const scratch = (x, y) => {
  //destination-out draws new shapes behind the existing canvas content
  context.globalCompositeOperation = "destination-out";
  context.beginPath();
  //arc makes circle - x,y,radius,start angle,end angle
  context.arc(x, y, 12, 0, 2 * Math.PI);
  context.fill();
};

window.onload = init();


style.css

* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
  }
  body {
    height: 50vh;    
  }
  .container {
    width: 20em;
    height: 20em;
    background-color: #f5f5f5;
    position: absolute;
    transform: translate(-50%, -50%);
    top: 50%;
    left: 50%;
    border-radius: 0.6em;
  }
  .base,
  #scratch {
    height: 200px;
    width: 200px;
    position: absolute;
    transform: translate(-50%, -50%);
    top: 50%;
    left: 50%;
    text-align: center;
    cursor: pointer;
    border-radius: 1.3em;
  }
  .base {
    background-color: #ffffff;
    font-family: "Poppins", sans-serif;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    box-shadow: 0 1.2em 2.5em rgba(17, 12, 99, 0.15);
  }
  .base h3 {
    font-weight: 600;
    font-size: 3.5em;
    color: #17013b;
  }
  .base h4 {
    font-weight: 400;
    color: #746e7e;
  }
  #scratch {
    -webkit-tap-highlight-color: transparent;
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    user-select: none;
  }


Thursday, 16 February 2023

How to get the current longitude and latitude. using javascript?

<div id="location"></div>

<script>
    var div = document.getElementById("location");
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition, showError);
        } else {
            div.innerHTML = "The Browser Does not Support Geolocation";
        }
    }
    
    function showPosition(position) {
        div.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
    }
    
    function showError(error) {
        if (error.PERMISSION_DENIED) {
            div.innerHTML = "The User have denied the request for Geolocation.";
        }
    }
    getLocation();
</script>

Wednesday, 15 February 2023

URL encode

 URL  encode

 

 <?php

namespace App\Http\Controllers\API;
 
use Log; use DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class EncodeController extends Controller
{       
    // UrlEncode
    public function urlencode(Request $request)
    {
        try            
        {  
            $myvar = DB::table('cl_master_category')
            ->select('cl_master_category.category_id', 'cl_master_category.category_name', 'cl_master_category.status', 'cl_master_category.color_code')
            ->get();
            
            $ciphering = "AES-256-CBC";    
            $encryption_key = env('ENCRYPTION_KEY');            
            $encryption_iv = env('ENCRYPTION_IV');
            
            $myencoding = openssl_encrypt($myvar, $ciphering,$encryption_key, 0, $encryption_iv);  
            
            return response()->json(['success' => true ,'encoded'=>$myencoding], 200);
           
        }
        catch (\Exception\Database\QueryException $e)
        {
            Log::info('Query: '.$e->getSql());
            Log::info('Query: Bindings: '.$e->getBindings());
            Log::info('Error: Code: '.$e->getCode());
            Log::info('Error: Message: '.$e->getMessage());

            return response()->json(['success' => false , 'message' => 'Database Server Error. Please try again later.'], 500);
        }
        catch (\Exception $e)
        {
            Log::info('Error: Code: '.$e->getCode());
            Log::info('Error: Message: '.$e->getMessage());

            return response()->json(['success' => true , 'message' => 'Internal Server Error. Please try again later.'], 500);
        }
    }
   
}


********************************************************************
Nextjs code

import React from "react";

import CryptoJS from "crypto-js";

const test = () => { 

  let keytext =  "25c6c7ff35b9979b151f2136cd13b0ff"

  let encrypted = "Nb7g0tuktmBmEwUbGrMabzMHlUTN/uyDPg5coE0AHTgmkvkxmwYxapvMu4IaZoCEXphDN+A+PfcMRGGdPso1vbKWJU9X1Yr+oh/eBRobD6hkG4BWJIxnVW79LSkK8WBfieMy05j2FxQH8GzXlPJ9KtcaMcxU2Zj8YERpko2Q8bpcWAlbQVDHXHRaYLMjoR7QvUz2OYqY3CNyLQgXnoc70q5JyAT+eC036Mx/zBnjA16HeVI5xI1MFQ4aFEddd58XwICngKZcuahG0tdUcZ8Z4XgZnmMzMrt+QeunhPg+IQGZhPhL4ZqH2CMYMy2TDtIqClRiAytjekMIcyJErYjVSYPnvGuBQqXiwW23QM69XWMvY0WFmZXXnKQPiwcRUSh3UgEPmbk6Dx023KnL6uw6Maq7/8BzaPzKCJO31gxyXk17NEh+by/59/UDaaLSKnB4fFRu1G/qa+Rg5n5l01XK2uNWITqKne3xWleACeMN652ZVhU1dWPwiWKkwI6hjbCg8m9UtRKw57rq3d6Jt/pN+SUdLJXbIjcTd9oxWlltSUDv4LlstWIlRIx9i6B+SEOMWtEvJvVfDn2DrBtxdo+02SH7ZjNhNi8CEFEHQybPxNBd2KNaiAWyIHgiqCZwmoCDjgPoQh2bWj33jPOVGvqPsCfuFfW10RieWK8yMtZHV2/W16DX3+j3Urt7Cb5o0KvG2+va3+YvTZ123c3a/+UkR+S2odrhEku041VUahIx15Zlhi80ffPn0ngX6E4wDa5QkKAL34kZbQJnZPnzD0P4QOHl34cpn5ZZVP8HsoWAXrAiTM033qG976w43Ld1ewxGG5VhSGRgNHj9CQ42l5+7GQ=="

  // let decrypted = "";

  let ivtext ="1234567891011121"

  

  const key = CryptoJS.enc.Utf8.parse(keytext);

  const iv = CryptoJS.enc.Utf8.parse(ivtext);  

  var decrypted = CryptoJS.AES.decrypt(encrypted, key, {

    iv: iv,

    mode: CryptoJS.mode.CBC,

  });

  text = CryptoJS.enc.Utf8.stringify(decrypted)

  console.log("decrypt", CryptoJS.enc.Utf8.stringify(decrypted));

  return (

    <>

      <div> {text}</div>

      {/ <div>encrypted Text : {encrypted}</div> /}

      {/ <div>Decrypted Text : {decrypted}</div> /}

    </>

  );

};

export default test;

 

 

Tuesday, 14 February 2023

Steps to consider for login process using google

 web.php

<?php

use App\Http\Controllers\ConnectController;
 
Route::get('/googleconnect', [ConnectController::class, 'googleconnect'])->name('googleconnect');
Route::get('oauth2callback', [ConnectController::class, 'oauth2callback'])->name('oauth2callback'); 


require __DIR__.'/auth.php';

ConnectController.php

<?php namespace App\Http\Controllers; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Redirect; use Illuminate\View\View; class ConnectController extends Controller { public function googleconnect(Request $request) { // Initialise the client. $client = new \Google\Client(); $client->setApplicationName('Calendar'); $client->setDeveloperKey("xxxxxxxxx"); $client->setAuthConfig('./client_secret.json'); $client->setAccessType("offline"); $client->setIncludeGrantedScopes(true); $client->setApprovalPrompt('force'); $client->addScope(['profile',\Google_Service_Calendar::CALENDAR]); // Set the redirect URL back to the site to handle the OAuth2 response. 
This handles both the success and failure journeys. $auth_url = $client->createAuthUrl(); $client->setRedirectUri(('http://localhost:8000/') . '/oauth2callback'); return redirect()->to($auth_url); } public function oauth2callback (Request $request) { // Get all the request parameters $input = $request->all();// Attempt to load the venue from the state
we set in $client->setState($venue->id); // the venue with a message. if (isset($input['error']) && $input['error'] == 'access_denied') { toastr()->warning('Authentication was cancelled. Your calendar has not been integrated.'); return redirect()->route('login'); } elseif (isset($input['code'])) { $client = new \Google\Client(); $client->setApplicationName('Calendar'); $client->setDeveloperKey("xxxxxxx"); $client->setAuthConfig('./client_secret.json'); $client->setAccessType("offline"); $client->setIncludeGrantedScopes(true); $client->setApprovalPrompt('force'); $client->addScope(['profile',\Google_Service_Calendar::CALENDAR]); $accessToken = $client->fetchAccessTokenWithAuthCode($request->code); $service = new \Google\Service\Calendar($client); $google_account_email = $service->calendars->get('primary')->id; toastr()->success($google_account_email); return redirect()->route('login'); } } }


Note: Store the access token in database.
Settings

$client->setAccessToken($google->token); // If there is no previous token or it's expired. if ($client->isAccessTokenExpired()) { // Refresh the token if possible, else fetch a new one. if ($client->getRefreshToken()) { $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); } else { // Request authorization from the user. return response()->json(['success' => false, 'message' => 'Something wrong! Please try again.' ], 200); } $tokenObj=json_encode($client->getAccessToken()); $google->token=$tokenObj; $save_token=$google->save(); }


Points to be consider while writing HTML

 1.    Add proper alt text and title text to images.

2.    Use headings properly.

3.    Use ARIA landmarks. (e.g., role="navigation", role="main")

4.    Add labels to form fields.

5.    Group related form fields together

6.    Provide sufficient color contrast.

7.    Avoid using tiny fonts.

8.    Respect white space.

9.    Provide a visible indication of focus. (e.g., :hover, :focus)

10.    Use text, not pictures of text (as possible).

11.    Caption video

12.    Describe the video

13.    Test web pages using a keyboard

14.    Giving proper title on <a> tags

15.    Responsive testing

Monday, 23 January 2023

Steps to follow before making live project in laravel.

 Below are some points that should be kept in mind while making laravel project live.


1.    php artisan optimize:clear    

        composer install --optimize-autoloader --no-dev

        composer dump-autoload --optimize 

        Laravel Telescope: If you have installed packages like Laravel Telescope or Debugbar, you should            disable or remove them in production: To remove run below command
        composer remove laravel/telescope barryvdh/laravel-debugbar

        Use Composer to check for any known security vulnerabilities in your dependencies:

        composer audit

2.    In the .env file
                APP_DEBUG=false. 

                LOG_LEVEL=error.  

                APP_ENV=production

3.    In the app.php

        $envKeys = [];
$serverKeys = [];
$cookieKeys = [];
foreach ( $_ENV as $key => $value ) { if(is_string($value)) $envKeys[] = $key; }
foreach ( $_SERVER as $key => $value ) { if(is_string($value)) $serverKeys[] = $key; }
foreach ( $_COOKIE as $key => $value ) { if(is_string($value)) $cookieKeys[] = $key; }       

        Inside return [
            'debug_blacklist' => [
                '_COOKIE'   => $cookieKeys,
                '_SERVER'   => $serverKeys,
                '_ENV'      => $envKeys,
            ],

4. .htaccess

    <Files ~ "\.(git|env|json|config.js|md|gitignore|gitattributes|lock|example)$">
        Order allow,deny
        Deny from all
    </Files>

    <Files ~ "(artisan)$">
      Order allow,deny
        Deny from all
    </Files>

5. php artisan storage:link 

6. Remove tests folder from project.

Wednesday, 4 January 2023

Laravel with Nextjs setup

 Steps to follow

composer create-project laravel/laravel example-app

cd example-app

php artisan serve

Open the .env file and update the database details

Add the below line before LOG_CHANNEL=stack

SESSION_DOMAIN=localhost

php artisan migrate

php artisan serve


composer require laravel/breeze --dev

php artisan breeze:install api


git clone https://github.com/laravel/breeze-next.git

cd breeze-next

npm install

rename the .env.example file to .env.local

npm run dev

Friday, 7 October 2022

Jenkins + Github + AWS Server

 

1. Create a git repo account on github.com

2. Create a nextjs project on local pc.

3. Upload the project on github.

4. Your genkins should be install on server. Login to Jenkins

5. Open putty key generator. Clik on Generate button. 
            Click on Save private key. Save the file with extension .ppk
            Copy Public key key .


6. In github account, In settings click on Deploy keys and then click Add deploy key.    

7.     Paste the public key that was copied from putty.

8. Set the ppk file.


9.  Create a   new freestyle project. Update the fields.



10. Settings for notification.






How to get geo location on registration in laravel?

Get Geo - location details 

 function getLocationInfoByIp(){

    $client  = @$_SERVER['HTTP_CLIENT_IP'];

    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];

    $remote  = @$_SERVER['REMOTE_ADDR'];

    $result  = array('country_name'=>'', 'time_zone'=>'');

    if(filter_var($client, FILTER_VALIDATE_IP)){

        $ip = $client;

    }elseif(filter_var($forward, FILTER_VALIDATE_IP)){

        $ip = $forward;

    }else{

        $ip = $remote;

    }    

    $ip_data = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip));    

      

    if($ip_data && $ip_data->geoplugin_countryName != null){

        $result['country_name'] = $ip_data->geoplugin_countryName;

        $result['time_zone'] = $ip_data->geoplugin_timezone;

    }

    return $result;

}

Saturday, 19 March 2022

Restrict number only in input box

 @section('script')

<script type="text/javascript"> 

         function restrictAlphabets(e) {

             var x = e.which || e.keycode;

             if ((x >= 48 && x <= 57))

                 return true;

             else

                 return false;

         }  

</script>

@endsection


onkeypress='return restrictAlphabets(event)'

Machine Learning - Potato Leaf Disease Prediction

Step 1: import numpy as np import pandas as pd import splitfolders import matplotlib.pyplot as plt import tensorflow as tf from tensorflow i...