Saturday 3 August 2019

Speech to Voice in Website using Javascript

Speech to Voice in Website using Javascript

W3C Community introduced the Web Speech API specification. Its a wonderful feature to introduce voice enabled commands on your website which works in Chrome Browser.

Convert Speech to Text

Below code just convert voice speech to text that you can use to make any search on your website or to navigate to another link on your website. Also you can make simple Bot on your website using this feature.

window.SpeechRecognition = window.webkitSpeechRecognition || window.SpeechRecognition;
console.log(window.SpeechRecognition);
if ('SpeechRecognition' in window{
    const recognition = new window.SpeechRecognition();
    recognition.onresult = (event) => {
        let speechToText = event.results[0][0].transcript;
        console.log("speech text", speechToText);
    }

    recognition.start();
    console.log('Ready to receive a command.');
} else {
    alert("speaking not working");
    // speech recognition API not supported
}



Below code is used to output speech on Chrome browser.
speechSynthesis.getVoices(); method is used to get voices from various countries accents.

var m = 'Hi How are you?';
if ('speechSynthesis' in window{
    const msg = new SpeechSynthesisUtterance(m);
    const voices = window.speechSynthesis.getVoices();
    // msg.voice = voices[9];
    //msg.voice = voices[4];
    console.log("speaking: " + m);
}

Sunday 22 July 2018

Progressive App Example

Progressive App Example Add to Home Screen

I am sharing my research on how to allow users to Add Website Icon on mobile device's Homescreen, just like Mobile Apps Icon(works mainly for Android devices).

Reference tutorials code



Create manifest.json at the root of the website

manifest.json
{
    "name": "Example site",
    "short_name": "examplesite",
    "icons": [{
            "src": "images/logo-96x96.png",
            "sizes": "32x32",
            "type": "image/png"
        },
        {
            "src": "images/logo-192x192.png",
            "sizes": "192x192",
            "type": "image/png"
        },
        {
            "src": "images/logo-512x512.png",
            "sizes": "512x512",
            "type": "image/png"
        }
    ],
    "start_url": "/?utm_source=web_app_manifest",
    "display": "standalone",
    "theme_color": "#000000",
    "background_color": "#000000"
}

Add following code in head part of the HTML of Index page

<meta name="theme-color" content="#000000"/>
<link rel="manifest" href="/manifest.json" />

Add following JS code in the footer of Index page


    if (window.matchMedia('(display-mode: standalone)').matches{

        console.log('display-mode is standalone');
    }

    if (window.navigator.standalone === true{
        console.log('display-mode is standalone');
    }

    window.addEventListener('appinstalled', (evt) => {
        //app.logEvent('a2hs', 'installed');
    });

    let deferredPrompta;

    window.addEventListener('beforeinstallprompt', (e) => {
        // Prevent Chrome 67 and earlier from automatically showing the prompt
        e.preventDefault();
        // Stash the event so it can be triggered later.
        deferredPrompta = e;

        // very important to prompt flyout
        deferredPrompta.prompt();
    });

    if ('serviceWorker' in navigator{
        window.addEventListener('load', function () {
            navigator.serviceWorker.register('/service-worker.js').
            then(function (registration) {
                // Registration was successful
                console.log('ServiceWorker registration successful with scope: ', registration.scope);
            }).catch(function (err) {
                // registration failed :(
                console.log('ServiceWorker registration failed: ', err);
            });
        });
    }


Finally create service-worker.js at the root of the website

server-worker.js

self.addEventListener('install', function (event) {});
self.addEventListener('activate', function (event) {});
self.addEventListener('fetch', function (event) {});

Saturday 10 February 2018

Check Uploaded File Size And Type JQuery

Check Uploaded File Size And Type JQuery

We upload files in web applications, sometimes we require to get uploaded file size and type at client side. I am sharing my JavaScript code to get uploaded file size and type at client side.

jQuery("input[name='member-file']").change(function () {
    var type = '';
    var iSize = 0;
    var error = true;
    if (jQuery.browser.msie{
        var objFSO = new ActiveXObject("Scripting.FileSystemObject");
        var sPath = jQuery(this)[0].value;
        var objFile = objFSO.getFile(sPath);
        iSize = objFile.size;
        iSize = iSize / 1024;
        type = objFile.type;
    } else {
        iSize = (jQuery(this)[0].files[0].size / 1024);
        type = jQuery(this)[0].files[0].type;
    }

    var TypeArr = [
        'video/mp4',
        'image/jpg',
        'image/jpeg',
        'image/gif',
        'image/png'
    ];

    jQuery(TypeArr).each(function (i, l) {
        if (type == l{
            error = false;
            return false;
        }
    });

    if (error == false{
        if (iSize > 0{
            iSize = (Math.round((iSize / 1024* 100/ 100)
        }

        if (iSize > 10{
            error = true;
        }
    }

    if (error == true{
        // show error
        return false;
    } else {
        // no error
        return true;
    }
});

Tuesday 19 December 2017

Get Remaining Hours In Day at Gap JavaScript

Get Remaining Hours In Day at Gap JavaScript

I am sharing my JavaScript code to get remaining hours at the gap of specific minutes. May be this code will helpful for someone.

var t = 0;
var h = 0;
var m = 0;

var totalHoursRemaining = [];
var hrs = [];
String.prototype.paddingLeft = function (paddingValue) {
    return String(paddingValue + this).slice(-paddingValue.length);
};
var date = new Date();
var ch = date.getHours();
ch = ch % 12;
ch = ch ? ch : 12; // the hour '0' should be '12'
var cm = date.getMinutes();

for (h = ch; h < 12; h++{
    for (m = 0; m < 60; m++{
        if (m % 5 == 0{
            var timstr = h + ":" + m.toString().paddingLeft("00");
            //if(m > cm) {   
            totalHoursRemaining.push(timstr);
            //}
        }
    }
}

var totalTimeLost = [];
for (var nm = 0; nm < cm; nm++{
    if (nm % 5 == 0{
        var timstr = ch + ":" + nm.toString().paddingLeft("00");
        totalTimeLost.push(timstr);
    }
}

function remove(array, element) {
    const index = array.indexOf(element);
    array.splice(index, 1);
}

for (s = 0; s < totalHoursRemaining.length; s++{
    for (s1 = 0; s1 < totalTimeLost.length; s1++{
        if (totalHoursRemaining[s== totalTimeLost[s1]) {
            remove(totalHoursRemaining, totalTimeLost[s1]);
        }
    }
}

console.log(totalTimeLost);

console.log(totalHoursRemaining);

Thursday 6 July 2017

Print HTML Div in JavaScript using HTML2canvas

Print HTML Div in JavaScript using HTML2canvas


I am sharing JavaScript Code, how to print HTML Div, Class, Section using HTML2canvas.

/* install html2canvas plugin */

First we need to add dependencies in package.json file:
  • @types/html2canvas: ^0.5.32
  • html2canvas: 0.5.0-beta4

/* run npm install command */
npm install

/* add ng-material print icon */
<a><md-icon (click)="printPage()">print</md-icon></a>

/* create printPage function */

function printPage() {
    html2canvasHTMLElement > document.getElementsByClassName("content")[0]).then(
        function (canvas) {
            var myImage = new Image();
            myImage.src = canvas.toDataURL("image/png");
            var w = window.open("", "print");
            w.document.body.appendChild(myImage);
            setTimeout(function () {
                w.focus();
                w.print();
                w.close();
            },
            500
        );
    });
}



Tuesday 4 August 2015

Improve MySQL Query Performance Tips

Improve MySQL Query Performance Tips



I am sharing some of my understanding on how to improve any MySQL Query performance, as per me below points makes the queries faster. May these points helpful for someone.





Tips
  1. Make index of columns used in where clause but not many columns, only higher priority columns.
  2. Always make joins on int columns.
  3. Use subquery or IN statement in place of joins.
  4. Don't select * from [table], always provide specific select columns in a query.
  5. Use Group By in place of DISTINCT.
  6. Use UTF-8 general collation for tables and columns.
  7. Some INNODB Engine tables configurations are helpful at server level. Below link can be helpful:
               MySQL Performance Tips

Get Random Values From Array IN PHP

Get Random Values From Array IN PHP



I am sharing my example code to get random values from PHP array. May this small code can be helpful for someone.





<?php

// array
$arr_subjects = array('Science', 'Maths', 'GK', 'Law', 'History', 'Arts', 'Chemistry',
    'Computers', 'Bio', 'Music');
// random number
$c = rand(1, 6);
//shuffle array elements
shuffle($arr_subjects);

//print random values in an array
print_r(array_slice($arr_subjects, $c, $c));
// prints $c'th elements from $c'th position in an array

Create .ICS file using PHP code

Recently worked on creating a .ics file in PHP after a very long time, code so thought to share with everybody. Please find below the comple...