Saturday 22 June 2019

How to create an RSS feed from URLs

How to create an RSS feed from URLs

Question: What is full form of RSS?
Rich Site Summary
Its also known as Really Simple Syndication.


Question: What is RSS feed?
It is standard web feed formats to publish the updated information of blog OR website.


Question: What is file extension of RSS Feed?
.xml or .rss


Question: Give a Sample of RSS Feeds?
Start the XML with following code.

<?xml version="1.0" encoding="utf-8"?>

<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:georss="http://www.georss.org/georss" xmlns:opensearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:thr="http://purl.org/syndication/thread/1.0">
    <channel>
 <title>Web Technology experts Notes</title>
  <link></link>http://web-technology-experts-notes.in
  <description>We are Web Technology Experts Team who provide you Important information on Web Development</description>
        <item><title>How to create folder with extension like .EBextensions</title> <description>Suppose you want to create folder with name ".EBextensions" Create folder with name ".EBextensions." Press enter You will see "." will disapper automatically from end of string Folder with name ".EBextensions" created successfully.</description><link></link>http://www.web-technology-experts-notes.in/2016/12/how-to-create-folder-with-extension-like-ebextensions.html<pubdate>Tue, 21 Jun 2016 15:36:00 +0000</pubdate><media:thumbnail height="72" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgWxGQGHkE2lgyXWpEN-LW9mN1MrHB2ldKSvZX-Xn2ZlAh2Zqv33Saw1_sjYdq7i0N4XPzQ6ufeh8JXw6h2ER9sFqLYyXWMUNcJU7suHXO3bgb7EwMdCaRj7yn-hMVfw5VncU7H3gkryBQ1/s72-c/How+to+create+folder+with+extension.png" width="72" xmlns:media="http://search.yahoo.com/mrss/"></media:thumbnail></item>
        <item><title>FCM push notification example</title> <description>Question: What is FCM Messages? Full form of FCM is Firebase Cloud Messaging. FCM is a cross-platform messaging solution that lets you reliably deliver messages to android and IOS devices at no cost. </description><link></link>http://www.web-technology-experts-notes.in/2016/12/fcm-push-notification-example.html<pubdate>Tue, 21 Jun 2016 20:36:00 +0000</pubdate><media:thumbnail height="72" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhJjl1lCoOWux0EG3hYYW1-rJqB-3iJsLaqIK-zOTjD_2Z_sq9v29LsVY9iC3lfu-6LZLD2TNQOahaajIsOP2y-HSQRGhUoe18L5LnJBHTU0ekF_6nVQMwSrYrkaeAJHYhFFkcds6FHEb6m/s72-c/FCM+push+notification+example.png" width="72" xmlns:media="http://search.yahoo.com/mrss/"></media:thumbnail></item>
        <item><title>What are special characters? and how to remove special characters?</title> <description>Question: What are special characters? Special characters are selected punctuation characters present on standard US keyboard. Question: Provide list of special characters?</description><link></link>http://www.web-technology-experts-notes.in/2016/12/what-are-special-characters-and-how-to-remove-special-characters.html<pubdate>Wed, 22 Jun 2016 01:36:00 +0000</pubdate><media:thumbnail height="72" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhJjl1lCoOWux0EG3hYYW1-rJqB-3iJsLaqIK-zOTjD_2Z_sq9v29LsVY9iC3lfu-6LZLD2TNQOahaajIsOP2y-HSQRGhUoe18L5LnJBHTU0ekF_6nVQMwSrYrkaeAJHYhFFkcds6FHEb6m/s72-c/FCM+push+notification+example.png" width="72" xmlns:media="http://search.yahoo.com/mrss/"></media:thumbnail></item>
        <item><title>Node JS tutorial for beginner</title> <description>Question: What is NodeJS Node.js is a platform built for fast and scalable network applications. It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.</description><link></link>http://www.example.com/url4http://www.web-technology-experts-notes.in/2016/12/node-js-tutorial-for-beginner.html<pubdate>Wed, 22 Jun 2016 06:36:00 +0000</pubdate><media:thumbnail height="72" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi7anpECNis2R4U7MyWdWUbi9ygJyKA211ydgESbcWUPGgG3acZwMO4vAKe5MxE53DkFdTOMVPVe8AH76piiHPtCo2YmgVrbI4cabzc7lX1slYKhMOHNDi1oWtvTI4B6bz6qsXQVh-sJL-f/s72-c/What+are+special+characters+and+how+to+remove+special+characters.png" width="72" xmlns:media="http://search.yahoo.com/mrss/"></media:thumbnail></item>
    </channel>
</rss>
Question: Create a script for?
Question: From where I can validate the RSS Feed URL?
https://validator.w3.org/feed/


Question: From where I can validate the RSS Feed Data?
https://validator.w3.org/feed/#validate_by_input


Question: Give a script to generate rss feeds from URL?


$urls= array(
    'http://www.web-technology-experts-notes.in/2016/12/how-to-create-folder-with-extension-like-ebextensions.html',
    'http://www.web-technology-experts-notes.in/2016/12/fcm-push-notification-example.html',
    'http://www.web-technology-experts-notes.in/2016/12/what-are-special-characters-and-how-to-remove-special-characters.html',
    'http://www.web-technology-experts-notes.in/2016/12/node-js-tutorial-for-beginner.html',
    );

$dateTime=strtotime('Tue, 21 Jun 2016 10:36:00 +0000');
$siteMapXml = '<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:georss="http://www.georss.org/georss" xmlns:opensearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:thr="http://purl.org/syndication/thread/1.0"><channel>';

//Uncomment the below code to enable download
/*header("Content-type: application/xml");
header("Content-Disposition: attachment; filename=rss.xml");
header("Pragma: no-cache");
header("Expires: 0");*/
$siteMapXml.=' <title>Web Technology experts Notes</title>
  <link></link>http://web-technology-experts-notes.in
  <description>We are Web Technology Experts Team who provide you Important information on Web Development</description>';
foreach($urls as $url){    
    $dateTime+=(3600*5);
    $dateString=date('D, j M Y H:i:s +0000',$dateTime);
     $siteMapXml.="<item><title>Page Title</title> <description>Page Description</description><link></link>{$url}<pubdate>{$dateString}</pubdate><media:thumbnail height="72" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgWxGQGHkE2lgyXWpEN-LW9mN1MrHB2ldKSvZX-Xn2ZlAh2Zqv33Saw1_sjYdq7i0N4XPzQ6ufeh8JXw6h2ER9sFqLYyXWMUNcJU7suHXO3bgb7EwMdCaRj7yn-hMVfw5VncU7H3gkryBQ1/s72-c/How+to+create+folder+with+extension.png" width="72" xmlns:media="http://search.yahoo.com/mrss/"></media:thumbnail></item>";   
}
echo $siteMapXml.='</channel></rss>';


Question: Give the Sample URL of RSS
Download Sample RSS


Thursday 6 June 2019

How to send email from zend framework 3?

How to send email from zend framework 3?

How to send email from zend framework3?


define('MR_MAIL_HOST','smtp.sendgrid.net');
define('MR_MAIL_PORT','587');//457,25
define('MR_MAIL_USERNAME','username');  
define('MR_MAIL_PASSWORD','password');  

$transport = new Mail\Transport\Smtp();
$options   = new Mail\Transport\SmtpOptions(array(
    'name'              => 'emailName',
    'host'              => MR_MAIL_HOST,
    'connection_class'  => 'login',
    'connection_config' => array(
        'username' => (MR_MAIL_USERNAME),
        'password' => (MR_MAIL_PASSWORD),
         'port' => MR_MAIL_PORT,
    ),
));
$transport->setOptions($options);

$mail = new Mail\Message();
$mail->setFrom('from@web-technology-experts-notes.in');
$mail->setSubject('This is simple subject');
$mail->setBody('this is html body text');
$mail->addTo('to@web-technology-experts-notes.in');
$transport->send($mail);

Wednesday 5 June 2019

Zend Framework 3 Authentication

Zend Framework 3 Authentication

use Zend\Authentication\Adapter\DbTable\CredentialTreatmentAdapter as AuthAdapter;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Storage\Session as SessionStorage;
            
$authAdapter = new AuthAdapter(
    $this->adapter,
    'admins',
    'email',
    'password',
     'md5(?)'
);

$authAdapter
    ->setIdentity($userName)
    ->setCredential($password);
$authResult = $authAdapter->authenticate();

if($authResult->isValid()){
    $result['success']=1;
    $identity=$authResult->getIdentity();

    //Save in session
    $adminDetails=$authAdapter->getResultRowObject(array('id','email'));
    $authService = new AuthenticationService();
    $authService->setStorage(new SessionStorage('AdminLogin'));
    $authService->getStorage()->write((array)$adminDetails);
}else{
    $messages = $authResult->getMessages();
    $result['msg'] =implode(' ',$messages);
}
    


HelpFul Links
https://github.com/zendframework/zend-authentication
https://github.com/zendframework/zend-authentication/blob/master/src/AuthenticationService.php

Friday 24 May 2019

How to download youtube video in PHP?

How to download youtube video in PHP?

Question: How to Get the YouTube Video Id?
Suppose we have following YouTube URL:
https://www.youtube.com/watch?v=iHp5veCNPVw
iHp5veCNPVw is YouTube Id.



Question: How to download YouTube using YouTube video Id?
$vid = 'iHp5veCNPVw'; //the youtube video ID
$vformat = 'video/mp4'; //video/mp4, video/webm, video/mp3 et.
$fileName = 'downloadvideos';//File name, downloadvideos.mp4
parse_str(file_get_contents("http://youtube.com/get_video_info?video_id=" . $vid), $info); //decode the data
$streams = $info['url_encoded_fmt_stream_map']; //the video's location info
$streams = explode(',', $streams);
foreach ($streams as $stream) {
    parse_str($stream, $data); //decode the stream
    if (stripos($data['type'], $vformat) !== false) { //We've found the right stream with the correct format
        $video = fopen($data['url'] . '&signature=' . @$data['sig'], 'r'); //the video
        $fullFileName = $fileName . '.' . str_replace('video/', '', $vformat);
        $file = fopen($fullFileName, 'w');
        stream_copy_to_stream($video, $file); //copy it to the file
        fclose($video);
        fclose($file);
        echo 'Downloaded Path:  ' . __DIR__ . '/' . $fullFileName;
        break;
    } else {
        echo "Unable to download this video.";
    }
}



Friday 10 May 2019

Zend 3 Interview Questions and Answers - Page 2

Zend 3 Interview Questions and Answers

Question: What is Hydrators?
Hydrators are used to create objects from different PHP array formats.
The main feature of each hydrator is a link between two separate layers, so that they are not cluttered up with unnecessary mappings, validations or filters in the classes, models etc.


Question: How to add filter in Zend3?
You can use Zend's HtmlEntities for filter the user data.
For Example:
$filter = new Zend\Filter\HtmlEntities();
print $filter->filter('<');



Question: How to set the UTC timezone for Zend?
Put the following code in public/index.php
date_default_timezone_set('UTC');



Question: What is Service Locator Pattern?
The service locator design pattern is used "Encapsulate the processes involved in obtaining a service with a strong abstraction layer".
It return the instances of services when they are requested for by the service consumers.

Following are the Design components of Service Locator Pattern.
Service Locator: It lookup services,dependencies,business object provides a simple interface to clients.
InitialContext: The InitialContext object is the start point in the lookup and creation process.
ServiceFactory: It provides the required BusinessService objects.
BusinessService: It the main object that fullfill your requirements.


Question: What is Service Manager?
Service Manager are heavely used in zend and it is based on Service Locator design Pattern.
It is used to register a service and get the server.


Question: How to install a Service Manager component?
composer require zendframework/zend-servicemanager



Question: How to register a service in Service manager?
use Zend\ServiceManager\ServiceManager; 
use Zend\ServiceManager\Factory\InvokableFactory; 
use stdClass;  
$serviceManager = new ServiceManager([ 
   'factories' => [stdClass::class => InvokableFactory::class,], 
]);



Question: How to get the object from Service Manager?
use Zend\ServiceManager\ServiceManager;  
$object = $serviceManager->get(stdClass::class);



Question: What is eventmanager?
The zend-eventmanager helps to design "High level architecture" and supports "subject/observer pattern".

It has two importants points
Event: Its event.
Listener: Listener are attached to the events and gets called when the event is triggered.
EventInterface Class: Used to specify the event itself.
EventManager class The instance of the EventManager tracks all the defined events in an application and its corresponding listeners.


Monday 6 May 2019

Zend 3 Interview Questions and Answers

Zend 3 Interview Questions and Answers

Question: How to print MySql query in zend framework?
$select = $this->sql->select();
echo $select->from('users')
        ->columns(array('id', 'first_name', 'last_name', 'email', 'status', 'total_events' => (`10`)))
        ->where($conds)
        ->order($orderBy);



Question: What are different type of route?
Literal routes: a literal route is one that exactly matches a specific string.
Segment routes: Segment routes allow you to define routes with variable parameters.


Question: How to disabled layout from controller in Zend Framework 3?
$view= new ViewModel();
$view->setTerminal(true);
return $view;



Question: How to print Sql Query in Zend3?
echo  $select->getSqlString($this->sql->getAdapter()->getPlatform(),\Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);



Question: Give example of Inner join, Left Join and Right join?
Inner join
$select = $this->sql->select();
$select->from(array('u'=>'users'))
        ->columns(array('id','email'))
        ->join(array('eq'=>'event_qualifiers'),"eq.user_id=u.id",array('total_events','event_type'));


Left join
$select = $this->sql->select();
$select->from(array('u'=>'users'))
        ->columns(array('id','email'))
        ->join(array('eq'=>'event_qualifiers'),"eq.user_id=u.id",array('total_events','event_type'),$select::JOIN_LEFT);


Right join
$select = $this->sql->select();
$select->from(array('u'=>'users'))
        ->columns(array('id','email'))
        ->join(array('eq'=>'event_qualifiers'),"eq.user_id=u.id",array('total_events','event_type'),$select::JOIN_RIGHT);


Question: How to autoload new module?
Once you have created the file structure for new module
1) Open the composer.json file.
2. Add the following line in psr-4 under autoload.
"Newmodule\\": "module/Newmodule/src/"


like below
"autoload": {
    "psr-4": {
        "Application\\": "module/Application/src/",
        "Album\\": "module/Album/src/"
    }
}



3. Execute following command
composer dump-autoload



Question: What are two components for databases?
A) One approach is to have "model classes" like Album represent each entity in your application
and then use mapper objects that load and save entities to the database.
B) Object-Relational Mapping (ORM) technology, such as Doctrine or Propel.


Question: What is use of config/modules.config.php?
We tell the ModuleManager that what module need to load with use of modules.config.php.


Question: What is Zend engine?
Zend Engine is a set of various components, which is used internally by PHP as a compiler.


Question: What are Decorators in the Zend framework?
Zend framework utilizes the decorator pattern to render elements and forms.


Question: What are Plugins in the Zend framework?
Zend Framework makes heavy use of plugin architectures.
Plugins allow for easy extensibility and customization of the framework while keeping your code separate from Zend Framework's code.


Question: How to check post method in zend framework?
if($this->getRequest()->isPost()){
}



Question: How to get post method in zend framework?
$postData = $this->getRequest()->getPost();



Question: How to get all GET data?
$this->getRequest()->getParams();



Question: How to redirect to another page from controller?
$this->_redirect("/users/login");



Question: What is Event Manager?
It gives the ability to create event based programming. This helps to create, inject and manage new events.


Question: What is Service Manager?
It gives the ability to consume any services (PHP classes) from anywhere with a little effort.


Question: What is Module Manager?
Ability to convert a collection of PHP classes with similar functionality into a single unit called as a module. The newly created modules can be used, maintained and configured as a single unit.


Difference between a lambda function and a closure (in PHP)

Difference between a lambda function and a closure (in PHP)

Question: Difference between a lambda function and a closure (in PHP)?
Lambda function is a function that assigned to a variable or passed to another function as parameter.

Example:
$greeting = function () {
  return "Hello world";
}
echo $greeting();//Hello world



A closure is a lambda function, but a lambda function is not a closure unless you specify the use keyword.

Example:

$user = "Rony";
// Create a Closure
$greeting = function() use ($user) {
  echo "Hello $user";
};
// Greet the user
$greeting();//Hello Rony


Tuesday 19 March 2019

AWS Rekognition for beginners

aws rekognition for beginners

Question: What is Amazon Rekognition?
Amazon Rekognition makes it easy to add image/video analysis to your applications.


Question: What different data we can get from Rekognition?
--Detect Objects and scenes that appear in photo/video.
--Face-based user verification.
--Detect Sentiment such as happy, sad, or surprise
--Unsafe Content Detection
--Celebrity recognition
--Text detection
--Rekognition can work on millions of photo.


Question: Give simplest example of working of Rekognition.
Each time a person arrives at your home, your door camera can upload a photo of the visitor to Amazon S3,
triggering a Lambda function that uses Rekognition API operations to identify your guest, and display the data on screen/mobile.



Question: Give some use case for Rekognition?
--Searchable image and video libraries
--Face-based user verification App
--Get the Sentiment and demographic analysis
--Detect the Unsafe Content Detection from photo/video
--Detect the Celebrity recognition
--Get the Text detection From photo/video


Question: What we can get from Rekognition for photos?
--Label detection
--Face detection and comparison
--Celebrity recognition
--Image moderation
--Text in image detection


Question: What we can get from Rekognition for videos?
--Labels
--Faces
--People
--Celebrities
--Suggestive and explicit adult content


Question: Recommendations for Stored and Streaming video?
https://docs.aws.amazon.com/rekognition/latest/dg/recommendations-camera-stored-streaming-video.html


Question: Give useful links for rekognition?

Get understanding
https://docs.aws.amazon.com/rekognition/latest/dg/what-is.html

Run sample code online (Require login)
https://ap-south-1.console.aws.amazon.com/rekognition/home?region=ap-south-1#/label-detection

API Docs
https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-rekognition-2016-06-27.html


Question: What are different type of commands detection for videos.
Labels - StartLabelDetection - GetLabelDetection
People - StartPersonTracking - GetPersonTracking
Faces - StartFaceDetection - GetFaceDetection
Celebrities - StartCelebrityRecognition - GetCelebrityRecognition
Detect adult content - StartContentModeration-GetContentModeration




Question: What are different limitation by video Rekognition?
Video must be available in S3
Video must be H.264 codec.
File format must be MPEG-4 and MOV
Max filesize is 8GB


Monday 4 March 2019

Node JS Interview Questions and Answers

Node JS Interview Questions and Answers

Question: What is callback?
A callback function is called at the completion of a given task.


Question: What Are Arrow Functions?
Arrow functions – also called "fat arrow" functions, are a more concise syntax for writing function expressions.

Examples
const multiplyES6 = (x, y) => { return x * y };
const phraseSplitterEs6 = phrase => phrase.split(" ");
var docLogEs6 = () => { console.log(document); };



Question: What is JSON.stringify()?
JSON.stringify() method converts a JavaScript object to a JSON string.


Question: What is Handlebars view engine in nodejs?
Handlebars.js is templating engine in NodeJS.


Question: What is an error-first callback?
Error-first callbacks are used to pass errors and data.
You have to pass the error as the first parameter, and it has to be checked to see if something went wrong.


Question: What are Promises?
The Promise object represents the event completion or failure of an asynchronous operation, and its resulting value.
function readFile(filename, enc){
  return new Promise(function (resolve, reject){
    fs.readFile(filename, enc, function (err, res){
      if (err) reject(err);
      else resolve(res);
    });
  });
}



Question: What is callback hell in Node.js?
Callback hell is the result of heavily nested callbacks that make the code not only unreadable but also difficult to maintain.


Question: What is the role of REPL in Node.js?
Full form of REPL is Read Eval print Loop.


Question: Explain chaining in Node.js?
Chaining is a mechanism whereby the output of one stream is connected to another stream as input.


Question: How to access the GET parameters after ? in Express?
req.query.name;



Question: What is buffer module?
Buffer class provides instances to store binary data similar to an array of integers.


Question: How we exporting a Module?
We use export for exporting the module.
exports.sayHelloInEnglish = function() {
    return "Hello, how are you?";
};



Question: What is meaning of tilde and caret?
the tilde(~) matches the most recent minor version.
the caret(^) matches the most recent major version.


Question: How to access 2nd argument when passed in command line?
process.argv.slice(3,4); //two=222



Question: What is Yargs?
Yargs helps to parsing arguments of command line tools.



Question: What is Async?
Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript.
async.map(['file1','file2','file3'], fs.stat, function(err, results) {
    // results is now an array of stats for each file
});



Question: How to use expressJs in Node
var express = require('express');
var app = express();

//Add cookie to express
var cookieParser = require('cookie-parser');
app.use(cookieParser());

//Add session to express
var session = require('express-session');
app.use(session({
    secret: 'XEDDKJKXD',
    name: 'testname',
    proxy: true,
    resave: true,
    saveUninitialized: true
}));

//Add static path
app.use(express.static('public'))

//Add "Parse JSOn" to express
var bodyParser = require('body-parser')
app.use(bodyParser.json());       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({// to support URL-encoded bodies
    extended: true
}));

//Add middleware to express
app.use(function (req, res, next) {
  //console.log('Time2222:', Date.now())
 res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   
  next()
})


//Add https to expresJs
var https = require('https');
var privateKey  = fs.readFileSync('public/cert/server.key', 'utf8');
var certificate = fs.readFileSync('public/cert/georama.crt', 'utf8');
var caCertificate = fs.readFileSync('public/cert/chain.crt', 'utf8');

var credentials = {key: privateKey, cert: certificate, ca: caCertificate};
var httpsServer = https.createServer(credentials, app);   


Question: How to start node on port?
httpsServer.listen(config['SERVERPORT'],function() {
    console.log('https listening on *:' + config['SERVERPORT']);
});



Question: How to connect socket with https?
var io = require('socket.io')(httpsServer);



Question: What is underscore module in nodeJS?
Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects.
console.log(_.each([1, 2, 3], function(value, key){
     console.log(key+'>>'+value)
 }));



Question: What Are Core Features Of Express Framework?
1) Allows to set up middlewares to respond to HTTP Requests.
2) Defines a routing.
3) Dynamically render HTML Pages.


Question: Give simple example of ExpressJS?
var app = require('express')();
var http = require('http').Server(app);

app.get('/listing', function (req, res) {   
   res.send('This is listing API'); 
});

http.listen('8080', function() {
    console.log('listening on *:8080');
});



Question: What are different Middleware?
1) Application-level middleware
2) Router-level middleware
3) Error-handling middleware
4) Built-in middleware
5) Third-party middleware



Wednesday 13 February 2019

PHP 7 interview Questions and Answers

PHP 7 interview Questions and Answers

Question: What is class Constants?
You can define constant as string OR expression within the class. but you can not define class as variable, or function.


Question: When will Autoloading function will be called once defined?
a) spl_autoload_register (autoload) will called when create object of class.
b) spl_autoload_register will called when extend by any class (using extends).
c) spl_autoload_register will called when implements an interface (using implements ).


Question: What is visibility? What are different type of visibility in class?
visibility means setting the access level of data member and member function.
Class methods must be declare as public, protected or private.
You can also declare with var which means public


Question: What is Static Keyword?
Declaring class property or methods as static makes them accessible without needing an instantiation of the class.
$this is not available inside the function.


Question: Tell me about Abstraction in PHP?
  1. Classes defined as abstract may not be instantiated.
  2. Class that contains at least one abstract method must also be abstract.
  3. When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child.
  4. if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.



Question: Tell me about Interface in PHP?
  1. We use "interface" keyword to create class.
  2. All methods declared in an interface must be public.
  3. To implement an interface, the implements operator is used.
  4. We can include multiple interface while implementing



Question: Tell me about Traits in PHP?
Traits are a mechanism for code reuse in single inheritance languages such as PHP.
We can't create instance of a traits
We can create Traits as below
    
trait Hello {
        public function sayHello() {
            echo 'Hello ';
        }
    }
We can use multiple traits using comma like below
 use Hello, World;
When two traits have same function, it would conflict but we can fix using insteadof like below
A::bigTalk insteadof B;
We can set the visibility of function using "as" like below
use HelloWorld { sayHello as protected; }
We can use one trait from another using "use"
we can also define abstract,static, data members, method


Question: Tell me about Anonymous classes?
We can create a class without specifing the class-name. Following are example
$util->setLogger(new class {
    public function log($msg)
    {
        echo $msg;
    }
});


Question: What is Overloading in PHP?
Overloading in PHP provides means to dynamically create properties and methods.
These dynamic entities are processed via magic methods one can establish in a class for various action types.
example of magic functions __get(), __set(), __isset(), __unset(), __call(),__callStatic() etc


Tuesday 5 February 2019

Node Js Buffer module examples with script code

Node Js Buffer module examples with script code

Question: What is buffer module?
Buffer class provides instances to store binary data similar to an array of integers. Buffer class is a global class that can be accessed in an application.


Question: How to create an empty buffer object?
var bufferData=Buffer.alloc(1024); //1024 bytes



Question: How to write in buffer object?
var bufferData.write('this is string'); //write only string



Question: How to create an array of buffer?
var buf1 = Buffer.from('1');
var buf2 = Buffer.from('2');
var buf3 = Buffer.from('3');
var bufferData = [buf1, buf2, buf3];
console.log(bufferData);//

OR
arrayObject=[];
arrayObject.push(Buffer.from('1'));
arrayObject.push(Buffer.from('2'));
arrayObject.push(Buffer.from('3'));
console.log(arrayObject);



Question: What is concat? How to concate the buffer data?
Concatenates an array of Buffer objects into one Buffer object
var buf1 = Buffer.from('1');
var buf2 = Buffer.from('2');
var buf3 = Buffer.from('3');
var bufferData = [buf1, buf2, buf3];
bufferData=Buffer.concat(bufferData);

OR
arrayObject=[];
arrayObject.push(Buffer.from('1'));
arrayObject.push(Buffer.from('2'));
arrayObject.push(Buffer.from('3'));
bufferData=Buffer.alloc(1024);
bufferData = Buffer.concat(arrayObject);
console.log(bufferData);



Question: How to compare two buffer?
var buf1 = Buffer.from('abc');
var buf2 = Buffer.from('abc');
var compare1 = Buffer.compare(buf1, buf2);
console.log(compare1); //0

var buf1 = Buffer.from('a');
var buf2 = Buffer.from('b');
var compare2 = Buffer.compare(buf1, buf2);
console.log(compare2); //-1

var buf1 = Buffer.from('b');
var buf2 = Buffer.from('a');
var compare3 = Buffer.compare(buf1, buf2);
console.log(compare3); //1



Question: How to check if data is buffer?
Buffer.isBuffer(obj);//true|false



Friday 1 February 2019

PHP 7 New Features

PHP 7 New Features

Question: What are main features of PHP 7?
  1. Lower Memory Consumption
  2. Improved performance as now using Zend Engine 3.0
  3. Consistent 64-bit support
  4. Scalar type declarations
  5. Return type declarations
  6. define() updates: Now you can add array.
  7. unserialize updates: Provide better security when unserializing objects on untrusted data
  8. Anonymous classes can be created
  9. Null coalescing operator (??) have been added
    Namespaces declaration like use some\namespace\{ClassA, ClassB, ClassC as C};
  10. Many fatal errors converted to Exceptions
  11. Secure random number generator
  12. session_start will accept an array.
  13. Spaceship operator
  14. list() function updates



Question: What is null coalescing operator?
null coalescing operator (??) has been introduced in PHP7.
$username = $_GET['username'] ?? $_POST['username'] ?? 'not passed';
print($username);



Question: What are Scalar type declarations?
Scalar type declarations has two type of options.
  1. coercive - coercive is default mode and need not to be specified.
  2. strict - strict mode has to explicitly hinted.



Question: What is Namespaces?
Namespaces are a way of encapsulating items. we can use two more different classes into one Namespaces.


Question: What is purpose of Namespaces?
1) To fixed the name collisions between your code and internal PHP classes/functions/constants or third-party classes/functions/constants.
2) Ability to shorten for Extra_Long_Names, improving readability of source code.



Question: Explain about Namespaces in PHP7?
  1. Namespace must be the first statement in the PHP Script.
  2. We can define Sub-Namespace also
  3. Defining multiple namespaces in same file with/without using bracketed syntax (Multiple declaration is not Recommended)
  4. We can access the Global method of namespaces using \
    namespace A\B\C;
            function strlen($string){
                return \strlen($string).'--arun';
            }
        echo strlen('imarun');
  5. we can use __NAMESPACE__ for getting the current namespace name
  6. We can use Alias for namespace as below
    use mynamespace\car as mycar;
  7. import multiple namespaces in single line
    use some\namespace\{ClassA, ClassB, ClassC as C};
            use function some\namespace\{fn_a, fn_b, fn_c};
            use const some\namespace\{ConstA, ConstB, ConstC};  
  8. Using namespaces: fallback to global function/constant
    a) An unqualified class name resolve to current namespace
    b) An unqualified function name resolve to current namespace
    c) An unqualified constant name resolve to Global namespace



Question: What is Class Constants?
Class Constants: You can define constant as string OR expression. but you can not define as variable, or function.


Question: When autoloading classes loads automatic?
a) Autoload when create object.
b) Autoload when include an another (using extends)
c) Autoload when include an interface (using implements )
d) we Can add exception in spl_autoload_register


Question: What is Visibility?
Class methods must be declare as public, protected or private.
You can also declare with var which means public


Question: What are Static Keyword?
Declaring class property or methods as static makes them accessible without needing an instantiation of the class.
$this is not available inside the function.




Thursday 10 January 2019

PHP namespace example - Tutorial

PHP namespace example - Tutorial

Question: What is namespace in PHP?
namespace is reserve keywords which is used to encapsulating the class, method, data member variables and static methods.


Question: Benefits of namespace in PHP?
  1. Encapsulate the data which fixed collisions between code you create, and internal PHP classes/functions/constants.
  2. Ability to alias which improved the readability of source code.



Question: Which PHP Version support namespaces?
PHP5.3



Question: How namespaces are defined?
namespaces are defined with keyword namespace
For Example:
namespace math



Question: Example - Simple class without namespace (OR Global namespace)?
File: /myproject/simple-file.php
class mathSimple {

    function add($a, $b) {
        return $a + $b;
    }

}

File: /myproject/run-example.php
include "simple-file.php";

$obj1 = new mathSimple(); //calling for Global Namespace
echo $obj1->add(10,20);//30

When we execute run-example.php file, it will return 30


Question: Example - Simple class with namespace?
File: /myproject/namespace-file.php
namespace math;

class mathSimple {

    function add() {        
        return array_sum(func_get_args()) ;
    }

}

File: /myproject/run-example.php
namespace math;
include "simple-file.php";
include "namespace-file.php";


$obj1 = new \mathSimple(); //calling for Global Namespace
echo $obj1->add(10,20,30);

echo "\n";
$obj2 = new mathSimple(); //calling for namespace math
echo $obj2->add(10,20,30);
Question: How to import namespaces?
use Zend\View\Model\ViewModel;



Question: How to use alias namespaces for import namespace?
use Zend\View\Model\ViewModel as ZendViewModel;



Question: Can we override the php in-built using namespace?
Yes, We can do. File: /myproject/namespace-file2.php
namespace math;

class mathSimple {

    function add() {        
        return array_sum(func_get_args()) ;
    }

}
function strlen($string){
    return 'in built functi';
}


File: /myproject/run-example2.php
namespace math;
include "namespace-file2.php";

echo strlen('string'); //calling namespace function
echo \strlen('strlen'); //calling inbuilt function


Tuesday 8 January 2019

Zend Framework modules questions and answers

Zend Framework modules questions and answers

Question: What are the basic steps for create new module?
Suppose you are creating module with name of Album.
  1. Attach module with application.
    Open file i.e /config/application.config.php, Add Blog in array like below:
    return array(
         'modules' => array(
             'Application',
             'Blog'
         ),
         
     );
    
  2. create Album  folder inside the module folder.
  3. After creating the Album folder inside modules, Create below folder structure.
  4. Album/
        Module.php
        autoload_classmap.php
        autoload_function.php
        autoload_register.php
        config/
            module.config.php
        public/
            images/
            css/
            js/
        src/
            Album/
                Controller/
                    AlbumController.php
                Form/
                    AlbumForm.php
                Model/
                    Album.php 
        view/
            album/
                album/
                    index.phtml
            layout/
                layout.phtml
            error
                index.phtml
    



Question: How to attach a module in main application?
Go to File config/application.config.php, and add your module name in modules array.
See example below (We have add a module Album).
return array(
     'modules' => array(
         'Application',
         'Album'
     ),
     
 );



Question: What is Service?
A Service is an object in the module that executes complex logic of the application.
Here we do all difficult logic together and gives you easy to understand results.


Question: What are the basic steps for creating the Service?
  1. Create a folder service in-side the module and path will be similar to below:
    /module/{moduleName}/src/{moduleName}/Service/{Album}Service.php
  2. Create a model in-side the module and path will be similar to below:
    /module/{moduleName}/src/{moduleName}/Model/Post.php
  3. Add Following code in controller where you want to use.
    use {moduleName}\Service\PostServiceInterface;

    Add following in controller (you can use another variable)
    protected $postService;
     public function __construct(PostServiceInterface $postService)
         {
             $this->postService = $postService;
         }

  4. Create the Factory class (path: /module/{moduleName}/src/{moduleName}/Factory/{factoryClass}.php)
  5. Register your service in module.config.php. (Add following code)
            'service_manager' => array(
             'invokables' => array(
                 '{moduleName}\Service\{Service}' => '{moduleName}\Service\{Service}'
             )
             
  6. Register your service from module.config
    (Path: /module/Blog/config/module.config.php)
        'controllers'  => array(
             'factories' => array(
                 '{moduleName}\Controller\List' => '{moduleName}\Factory\{factoryClass}'
             )
          

Question: How to set different Db Connections for each module?
There are different module.config.php file inside each module (module/{moduleName/config/module.config.php}.
In this you you can set the database credentials.
 'db' => array(
         'driver'         => 'Pdo',
         'username'       => 'SECRET_USERNAME',  //edit this
         'password'       => 'SECRET_PASSWORD',  //edit this
         'dsn'            => 'mysql:dbname=blog;host=localhost',
         'driver_options' => array(
             \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
         )
     ),



Monday 31 December 2018

17 FFmpeg Commands For Beginners

17 FFmpeg Commands For Beginners

#1 Getting audio/video file information
ffmpeg -i video.mp4

(use -hide_banner flag to hide information such as version, configuration details, copyright notice, build and library options etc.)


#2 Converting video files into AVI
ffmpeg -i video.mp4 video.avi

(use -qscale 0 to preserve the quality of your source video file)


#3 understand comman Abbr
-i filename (i=Input)
-vn  Indicates that we have disabled video recording in the output file.
-ar  Set the audio frequency of the output file. The common values used are 22050, 44100, 48000 Hz.
-ac  Set the number of audio channels.
-ab  Indicates the audio bitrate.
-f  Output file format. In our case, it’s mp3 format.
-b:v 64k (-b:v video bitrate)
-r 24 (change the frame rate)
-vf video filter (vf video filter)
-af audio filter (af audio filter)
-an file name (No audio)
-sn file name (No sub-title)
-dn file name (No data-stream)



#4 Change resolution of video files
ffmpeg -i input.mp4 -filter:v scale=1280:720 -c:a copy output.mp4



#5 Compressing video files
ffmpeg -i input.mp4 -vf scale=1280:-1 -c:v libx264 -preset veryslow -crf 24 output.mp4



#6 Compressing Audio files
ffmpeg -i input.mp3 -ab 128 output.mp3

96kbps
112kbps
128kbps
160kbps
192kbps
256kbps
320kbps


#7 Removing audio stream from a media file
ffmpeg -i input.mp4 -an output.mp4



#8 Removing video stream from a media file
ffmpeg -i input.mp4 -vn output.mp3



#9 Cropping videos
ffmpeg -i input.mp4 -croptop 100 -cropbottom 100 -cropleft 300 -cropright 300 output.mp4



#12 Set the aspect ratio to video
ffmpeg -i input.mp4 -aspect 16:9 output.mp4



#13 Trim a media file using start and stop times
ffmpeg -i input.mp4 -ss 00:00:50 -codec copy -t 50 output.mp4



#14 Changing resolution and Reencoding
ffmpeg -i 1.mp4 -vf scale=1280:720 -acodec aac -vcodec libx264   NewFile.mp4 -hide_banner



#15 Joining multiple video parts into one
ffmpeg -f concat -i join.txt -c copy output.mp4

(join.txt will have path of all videos)


#16 Add subtitles to a video file
fmpeg -i input.mp4 -i subtitle_file.srt -map 0 -map 1 -c copy -c:v libx264 -crf 23 -preset veryfast output.mp4



#17 Increase video playback speed
ffmpeg -i inputvideo.mp4 -vf "setpts=0.5*PTS" outputvideo.mp4





Question: How to execute ssh command in PHP and get the results?
exec("ls",$o);
print_r($o);




Sunday 30 December 2018

Zend Framework 2 Session Management - Add Update Delete Session

Zend Framework 2 Session Management - Add Update Delete Session


Question: What is Zend Session?
A Session is a way to store information (in variables) to be used across multiple pages. It is mainly used to check for login information on browser and track the user activies. Zend Session is Zend libery for Session which helps to manage the session data.


Question: What is difference between Session Manager and Session Container?
Zend\Session\Container instances provide the primary API for manipulating session data. Containers are used to segregate all session data. Zend\Session\SessionManager, is a class that is responsible for all aspects of session management. It is used to initializes and configuration, storage and save handling.


Question: What is difference between Session Manager and Session Container and Session Config in One line each?
Container: The provides the core interface for managing session data.
SessionConfig: Handles setting for session config options.
SessionManager: Handles session management such as session start/exists/write/regenerate id/time-to-live/and destroy and session validation.


Question: Can you store session data in database?
Yes, we can.
For this we need to set the configuration like below:
use Zend\Db\TableGateway\TableGateway;
use Zend\Session\SaveHandler\DbTableGateway;
use Zend\Session\SaveHandler\DbTableGatewayOptions;
use Zend\Session\SessionManager;

$tableGateway = new TableGateway('session', $adapter); //this is table where session will store, you need to create the table and its model also.
$saveHandler  = new DbTableGateway($tableGateway, new DbTableGatewayOptions());
$manager      = new SessionManager();
$manager->setSaveHandler($saveHandler);


Question: How to set the Defualt Session Mangaer for Session Container?
use Zend\Session\Container;
use Zend\Session\SessionManager;

$manager = new SessionManager();
Container::setDefaultManager($manager);



Question: How to create session Object?
use Zend\Session\Container;
$sessionObj = new Container('sessinName');



Question: How to set Session value?
$sessionObj->offsetSet('email', 'email@domain.com');



Question: How to get Session value?
$sessionObj->offsetGet('email');



Question: How to check Session value exist OR Not?
$sessionObj->offsetExists('email');



Question: How to unset the session value?
$sessionObj->offsetUnset('email');



Sunday 23 December 2018

FCM push notification example

FCM push notification example

Question: What is FCM Messages?
Full form of FCM is Firebase Cloud Messaging.
FCM is a cross-platform messaging solution that lets you reliably deliver messages to android and IOS devices at no cost.
You can notify a client app that new message has been arrived.



Question: How does FCM works?
App server interacts with FCM (HTTP or XMPP protocol) and a client app. You can compose and send messages.
FCM built on Firebase Cloud Messaging.


Question: What is FCM Server?
FCM servers take messages from an app server and send to cient app.
FCM connection servers provided by Google.


Question: What is App Server?
App Server sends data to a client app (via the chosen FCM connection server) using XMPP or HTTP protocol.



Question: What are role of App Server?
  • Communicate with your client
  • Send properly formatted requests to the FCM connection server
  • Securely store the Server key and client registration tokens



Question:How to send notification to android/IOS device with FCM server?
$jsonData='{
  "to": "dhkC5_jTnck:APA91bF7L_KN7GFOPMiVsykjMGqydlftItfapC4Va63hRBuhFCrRKMdUonqhO1qjKT5_OYPMRAZFMA2UDVA1spAw9SpCsLE7B05vGtNttvuykIdxL7jKWWvJkA51T98O8ZZkubhXwQyRx",
  "notification": {
    "body": "New Gr sent you a message",
    "title": "domain.com ",
    "icon": "main_ve_logo",
    "click_action": "com.domain.fcm"
  },
  "data": {
    "type": "message",    
    "avatar": "http://img.domain.com/upload/default.jpg",
    "message_id": 1
  }
}';
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "https://fcm.googleapis.com/fcm/send",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => json_encode($fields),
    CURLOPT_HTTPHEADER => array(
      "authorization: key=FCM_SERVER_KEY",
      "cache-control: no-cache",
      "content-type: application/json"
    ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);




Thursday 20 December 2018

Node JS tutorial for beginner

NodeJS Framework Understanding

Question: What is NodeJS
Node.js is a platform built for fast and scalable network applications. It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. It can be used in Websites application, Android applicationa and IOS application etc.


Question: What type of framework is Nodejs?
NodeJS is JavaScript-based framework/platform



Question: Is Nodejs Server OR Cient Side?
Both, Node work for both.



Question: What is REPL?
REPL stands for Read Eval Print Loop
Node.js comes with virtual environment called REPL (also Node shell).


Question: What are most common REPL Commands?
ctrl + c
Terminate the current command.
ctrl + c twice 
terminate the Node REPL.
Up/Down Keys
see command history.
tab Keys
list of current commands.
.help
list of all commands.
.break
exit from multiline expression.
.save filename 
save the current Node REPL session to a file.
.load filename
load file content in current Node REPL session.



Question: How to exist from REPL?
ctrl + c twice 



Question: How to install module in NodeJS?
npm install express
for install express.


Question: How to uninstall module in NodeJS?
npm uninstall express
for uninstall express.


Tuesday 13 November 2018

ThinkPHP SQL queries with examples

ThinkPHP SQL queries with examples

Question: How to create Model Object?
$userObj= D("Common/Users");



Question: How to add simple AND Query?
$map=array();
$userObj= D("Common/Users");
$map['user_type'] = 2;
$map['city_id'] = 10;
 $lists = $userObj
                ->alias("u")                
                ->where($map)
                ->order("u.id DESC")
                ->select();



Question: How to add simple OR Query?
$map=array();
$userObj= D("Common/Users");
$map['u.username|u.email'] = 'email@domain.com';  //username OR email is email@domain.com
 $lists = $userObj
                ->alias("u")                
                ->where($map)
                ->order("u.id DESC")
                ->select();



Question: How to use =, >, < in Query?
$map['id']  = array('eq',1000); //equal to 1000

$map['id']  = array('neq',1000); //Not equal to 1000

$map['id']  = array('gt',1000);//Greater than 1000

$map['id']  = array('egt',1000);//Greater than OR EQual 1000

$map['id']  = array('between','1,8'); //Between 1-8




Question: How to use like Query?
$map=array();
$userObj= D("Common/Users");
$map['name'] = array('like','test%'); //like test%
 $lists = $userObj
                ->alias("u")                
                ->where($map)
                ->order("u.id DESC")
                ->select();



Question: How to use like Query with NOT?
$map=array();
$userObj= D("Common/Users");
$map['b'] =array('notlike',array('%test%','%tp'),'AND'); //Not like %test% and %tp
 $lists = $userObj
                ->alias("u")                
                ->where($map)
                ->order("u.id DESC")
                ->select();



Question: How to use Inner JOIN ?
$map=array();
$userObj= D("Common/Users");
$map['name'] = array('like','test%'); //like test%
 $lists = $userObj
                ->alias("u") 
                ->join(C('DB_PREFIX') . "profile as p ON u.id = p.uid")               
                ->where($map)
                ->order("u.id DESC")
                ->select();



Question: How to use LEFT JOIN ?
$map=array();
$userObj= D("Common/Users");
$map['name'] = array('like','test%'); //like test%
 $lists = $userObj
                ->alias("u") 
                ->join('LEFT JOIN '.C('DB_PREFIX') . "profile as p ON u.id = p.uid")               
                ->where($map)
                ->order("u.id DESC")
                ->select();



Question: How to use RIGHT JOIN ?
$map=array();
$userObj= D("Common/Users");
$map['name'] = array('like','test%'); //like test%
 $lists = $userObj
                ->alias("u") 
                ->join('RIGHT JOIN '.C('DB_PREFIX') . "profile as p ON u.id = p.uid")               
                ->where($map)
                ->order("u.id DESC")
                ->select();



Question: How to use group by and having?
$map=array();
$userObj= D("Common/Users");
$map['name'] = array('like','test%'); //like test%
 $lists = $userObj
                ->alias("u") 
                ->join('RIGHT JOIN '.C('DB_PREFIX') . "profile as p ON u.id = p.uid")               
                ->where($map)
                ->order("u.id DESC")
                 ->group('u.id')                
                 ->having('count(p.id) >0')
                ->select();



Question: How to use count(for total records)?
$map=array();
$userObj= D("Common/Users");
$map['name'] = array('like','test%'); //like test%
 $count = $userObj
                ->alias("u")                 
                ->where($map)                
                ->count();



Monday 5 November 2018

How to change the video resolution from 1280X720 to 600X400


Question: Download the php-ffmpeg library (If not downloaded)?
composer require php-ffmpeg/php-ffmpeg




Question: How to change the video resolution from 1280 X 720 to 600 X 400?
    //load the library
    require_once 'ffmpeglib/vendor/autoload.php'; 
    $ffmpeg = FFMpeg\FFMpeg::create();

    //format of new video
    $format = new FFMpeg\Format\Video\X264();
    $format->setAudioCodec("aac");           

    //path of folder where video exist
    $videoFolderPath='folder';

    //change the resolution
    $width=600;
    $height=400;


    //load the video in ffmpeg
    $videoObj = $ffmpeg->open($videoFolderPath.'/input_video.mp4');
    //filter the video with height/width
    $videoObj->filters()->resize(new FFMpeg\Coordinate\Dimension($width, $height), FFMpeg\Filters\Video\ResizeFilter::RESIZEMODE_INSET, true);
    //save the video
    $videoObj->save($format, $videoFolderPath.'/output_video.mp4');