Wednesday 22 July 2020

How to Call async/await functions in parallel

How to Call async/await functions in parallel

Question: How to Call async/await functions in parallel?
We can use await on Promise.all()

Syntax
let [someResult, anotherResult, anotherResult3] = await Promise.all([someCall(), anotherCall(), another3Call()]);


Example
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});
Promise.all([promise1, promise2, promise3]).then((values) => {
  console.log(values);
});



Question: How to read data from Image url and write in file synchronous?
First, We must need to install https and fs module in node.
https - Its for execute the https request.
fs - for save the file in local.

Example
const https = require('https');
const fs = require('fs');

const file = fs.createWriteStream("file.jpg");//Create  a file
const request = https.get("https://img.youtube.com/vi/0yX92mE6h2M/mqdefault.jpg", function(response) {
  response.pipe(file);//Add the image-content in file
});



Question: What is difference between app.listen and server.listen?
Both are used to start the server, for listening the request.

We need server.listen for create the request on https server.
var https = require('https');
var server = https.createServer(app).listen(config.port, function() {
    console.log('Https App started');
});

app.listen will create http server.
var express = require('express');
var app = express();
app.listen(1234);



Question: How to return the json response?
You can use res.json() to return the response in APIs
Example
exports.get_data = function(req, res) {  
    res.json({name: "web technology experts",description:"this is description"});
};



Question: How to auto-reload files in Node.js in Local server?
While doing the development, you do not want to re-start the node server each time, when you made changes.
For this you can use nodemon module.
Install the nodemon module
npm install nodemon -g 

start the node with nodemon instead of node
nodemon app.js



Question: How to create https request?
To Create the https server,
---first you need to install the modules like https, express and socket.io etc
---You need private/public keys for ssl

var https = require('https');
var privateKey  = fs.readFileSync('public/server.key', 'utf8');
var certificate = fs.readFileSync('public/file.crt', 'utf8');
var caCertificate = fs.readFileSync('public/chain.crt', 'utf8');
var credentials = {key: privateKey, cert: certificate, ca: caCertificate};
var httpsServer = https.createServer(credentials, app);  
var io = require('socket.io')(httpsServer);  
httpsServer.listen(443,function() {
    console.log('https listening on 443');
});  




Monday 20 July 2020

Call socket event from router page in Node

Call socket event from router page in Node

Question: How to send socket notification from Node API/Router?
  1. In App file (like index.js OR app.js)
    //Express setup
    var express = require('express');
    var app = express();
    
    //socketsetup setup
    var io = require('socket.io')(https);    
    app.set('io', io); //IMP this will let available io in router file
    
  2. In Router or Controller file
    exports.sendnotify = function(req, res) {
        var io = req.app.get('io');
        io.sockets["in"]('room_446').emit('session_end_notify', {vid:100,event_type:'live'});   //Send the Notification
        res.send('node is working fine');
    };
    
    


Question: How decrypt a text which is encoded with base64?
let buff = Buffer.from('ENCRYPTED_TXT', 'base64');
print buff.toString('ascii');        




Thursday 2 July 2020

Node JS Interview Questions and Answers

Node JS Interview Questions and Answers

Question: How to write in files synchronous in Node.js?
const fs = require('fs');
fs.writeFileSync('/fold/test.txt', 'Write in file');



Question: What is the difference between --save and --save-dev?
--save-dev is used to save the package for development purpose. Example: unit tests, minification
--save is used to save the package required for the application to run.



Question: is node single threaded or multithreaded?
It is a single threaded language which in background uses multiple threads to execute asynchronous code. Also its is non-blocking which means that all functions ( callbacks ) are delegated to the event loop and they are ( or can be ) executed by different threads.


Question: How to print console without a trailing newline?
    process.stdout.write("hello: ");



Question: How to create a directory if it doesn't exist using Node.js?
var fs = require('fs');
var dir = './tmp';
if (!fs.existsSync(dir)){
    fs.mkdirSync(dir);
}



Question: How can we execute binary/exe files in Node ?
const { exec } = require('child_process');
exec('wc -l', (err, stdout, stderr) => {
  if (err) {
    // node couldn't execute the command
    return;
  }
});



Question: Is there a way to get version from package.json?
var pjson = require('./package.json');
console.log(pjson.version);



Question: How can I update npm on Windows?
Simple way
Download and run the latest MSI from nodejs.org. The MSI will update your installed node and npm.


Question: How can node in background?
nohup node server.js &



Question: What is the difference between __dirname and ./ in node.js?
__dirname is always the directory in which the currently executing script exist.
. gives you the directory from which you ran the node command in your terminal window



Question: How to get the full url in Express?
var url = require('url');
function fullUrl(req) {
  return url.format({
    protocol: req.protocol,
    host: req.get('host'),
    pathname: req.originalUrl
  });
}




Wednesday 1 July 2020

Node JS Interview Questions and Answers for 3 Years experience



Question: What is the difference between tilde(~) and caret(^) in package.json?
~ update you to all future patch versions, without incrementing the minor version. ~2.2.3 will use releases from 2.2.3 to 2.3.0.
^ update you to all future minor/patch versions, without incrementing the major version. ^2.3.3 will use releases from 2.3.3 to 3.0.0.



Question: How do I pass command line arguments to a Node.js program?
In Node - How to pass arguent
node process-2.js one two=three four
In Node - How to get argument value
process.argv



Question: How do I update each dependency in package.json to the latest version?
npm i -g npm-check-updates
ncu -u
npm install



Question: How can I update NodeJS and NPM to the next versions?
npm install -g npm



Question: How to write in files synchronous in Node.js?
const fs = require('fs');
fs.writeFileSync('/fold/test.txt', 'Write in file');



Question: How to read environment variables?
var mode   = process.env.NODE_ENV;
var apiKey = process.env.apiKey; 



Question: How to parse JSON using Node.js?
//Parse JSON Data
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
}));



Question: How  an HTTP POST request made?
var request = require('request');
request.post(
    'https://www.example.com',
    { json: { key: 'value' } },
    function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body);
        }
    }
);



Question: How can I get the full object in Node.js's console.log(), rather than Object?
const util = require('util');
console.log(util.inspect(myObject, {showHidden: false, depth: null}));

OR
console.log(JSON.stringify(myObject, null, 4));




Question: How to encode a text using base64?
Buffer.from("Hello World").toString('base64'); //SGVsbG8gV29ybGQ=


Question: How to decoded a text which is encoded with base64?
Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'); //Hello World


Thursday 18 June 2020

Get Mysql Row size too large error when change engine from MyISAM to Innodb

Get Mysql Row size too large error when change engine from MyISAM to Innodb
ALTER TABLE table_name ENGINE=InnoDB

When i try to change the engine From MyISAM to InnoDB, getting following error.

row size too large (> 8126). changing some columns to text or blob or using row_format=dynamic or row_format=compressed may help.

Solutions:
  1. Add the following to the my.cnf file under [mysqld] section.
            innodb_file_per_table=1;
            innodb_file_format = Barracuda;
            innodb_log_file_size = 256M    
    
         
  2. ALTER TABLE table_name ENGINE=InnoDB ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=8;




Sunday 7 June 2020

MySQL database Administrator interview question and Answer for 6 year experienced

MySQL database Administrator interview question and Answer for 6 year experienced

Question: How to reset AUTO_INCREMENT in MySQL?>
ALTER TABLE tablename AUTO_INCREMENT = 1

Question: How to concatenate multiple rows into one field?>
SELECT GROUP_CONCAT(id SEPARATOR ', ')   FROM users   WHERE city = 'india'  GROUP BY city;

(It will concatinate all the users)


Question: Which MySQL data type to use for storing boolean values?>
BIT

Question: What are best character-set for multi-language data?>
utf8mb4

Question: What is the difference between utf8mb4_unicode_ci and utf8mb4_general_ci?
utf8mb4_unicode_ci is based on the official Unicode rules for universal sorting and comparison, which sorts accurately in a wide range of languages.

utf8mb4_general_ciis a simplified set of sorting rules which aims to do as well as it can while taking many short-cuts designed to improve speed. It does not follow the Unicode rules and will result in undesirable sorting or comparison in some situations


Question: How do you set a default value for a MySQL Datetime column?>
Add the default CURRENT_TIMESTAMP
For example:
CREATE TABLE foo (
    `modification_time` DATETIME ON UPDATE CURRENT_TIMESTAMP
)



Question: What is the difference between physical and logical backup?>
physical backup is to copy for backing up all the physical files that belongs to database.(like data files,control files,log files, executables etc), we need to stop the mysql service temporary.>
In logical backup, you don't take the copies of any physical things,you only extract the data from the data files into dump files.(ex : using export )


Question: What are World's most popular Databases?>
  1. Oracle
  2. MySQL
  3. Microsoft SQL Server
  4. PostgreSQL
  5. MongoDB



Question: Explain ACID?
Atomicity. All completed OR Nothing.
Consistency. Database protected from actions that may corrupt data.
Isolation. multiple actions occuring in parallel will not impact each other.
Durability. All commited statements data are safe.


Question: What does FLUSH TABLES WITH READ LOCK do?
1 set the global read lock - after this step, insert/update/delete/replace/alter statements cannot run.
2 close open tables - this step will block until all statements started previously have stopped.
3 set a flag to block commits.
FLUSH TABLES


Thursday 4 June 2020

MySQL database Administrator interview question and Answer

MySQL database Administrator interview questions and Answer

Question: How to start MySQL Service?
Start MySQL Server using service
sudo service mysql start


Start MySQL Server using using init.d
sudo /etc/init.d/mysql start


Start MySQL Server using systemd
Start MySQL Server using systemd


Question: List the MySQL Users
select user from mysql.user;



Question: List all databases
show databases



Question: Grant insert,UPDATE,delete privileges on the mydb (DB) to dbuser (User)
GRANT INSERT, UPDATE, DELETE ON mydb.* TO bob@localhost;



Question: Grant all privileges on the mydb (DB) to dbuser(User)
grant all privileges on mydb.* to dbuser@localhost;



Question: Show all the privileges to dbuser(User)
SHOW GRANTS FOR dbuser;



Question: Revoke insert,UPDATE,delete privileges on the mydb (DB) from dbuser (User)
REVOKE INSERT, UPDATE ON mydb.* FROM dbuser@localhost;



Question: List all the Proesslist in MySQL
SHOW Full PROCESSLIST



Question: What are different MySQL storage engines
  1. MyISAM: Before MySQL version 5.5, MyISAM is the default storage engine. MyISAM extends the former ISAM storage engine. MyISAM tables are optimized for compression and speed. MyISAM tables can be compressed into read-only tables to save spaces. The MyISAM tables are not transaction-safe. MySQL also checks and repairs InnoDB tables.
  2. InnoDB: InnoDB tables fully support ACID-compliant and transactions. InnoDB table supports foreign keys, commit, rollback, roll-forward operations. MySQL also checks and repairs InnoDB tables.
  3. MERGE: A MERGE table is a virtual table that combines multiple MyISAM tables that have a similar structure to one table. MERGE table does not have its own indexes;
  4. MEMORY: The memory tables are stored in memory and use hash indexes so that they are faster than MyISAM tables The lifetime of the data of the memory tables depends on the uptime of the database server.




Monday 1 June 2020

MySQL Stored procedure interview Questions and Answer

MySQL Stored procedure interview Questions and Answer

Question: What is stored procedure?
A stored procedure is Structured Query Language (SQL) statements which has a name, a parameter list, and SQL statement(s) stored in MySQL Server.



Question: Give example of stored procedure?
DELIMITER $$
CREATE PROCEDURE getUsersAscending()
BEGIN
	SELECT 
		first_name, 
		last_name, 
		email
	FROM
		users
	ORDER BY first_name;    
END$$
DELIMITER ;




Question: Give example of stored procedure with parameter details?
DELIMITER $$
CREATE   PROCEDURE `getUsersDetails`(IdSearch INT)    
    BEGIN
	SELECT 
		first_name, 
		last_name, 
		email
	FROM
		users
	WHERE id=IdSearch;      

    END$$
DELIMITER ;



Question: To show all stored procedures:
SHOW PROCEDURE STATUS;



Question: How to show stored procedures in a specific database
SHOW PROCEDURE STATUS WHERE Db = 'db_name';



Question: MySQL stored procedures advantages?
  1. Reduce network traffic
  2. Make database more secure



Question: MySQL stored procedures dis-advantages?
  1. Resource usages: If you use many stored procedures, the memory usage of every connection will increase substantially.
  2. Troubleshooting:MySQL does not provide any facilities to debug stored procedures like other enterprise database products such as Oracle and SQL Server
  3. Maintenances Developing and maintaining stored procedures often requires a specialized skill set that not all application developers possess.



Question: How to call stored procedure with OR without arguments?
Call without argument
call getUsersAscending();
Call With argument
call getUsersDetails(10);



Question: How to delete the procedure?
DROP PROCEDURE IF EXISTS getUsersAscending;



Question: What if i am trying to delete the stored procedure for non-exist.?
It will give warning only, if you have used "IF EXISTS"
It will give Error, if you have used not used "IF EXISTS"


Question: How to Alter a stored procedure in mysql?
1: Delete the Stored procedure. 
2: Re-Create the Stored procedure.



Sunday 31 May 2020

AWS Elastic Beanstalk Interview Questions and Answers

AWS Elastic Beanstalk Interview Questions and Answers


Question: What is Elastic Beanstalk in AWS?
AWS Elastic Beanstalk is End-to-end web application management.


Question: Can we use Elastic beanstalk to deploy the web application which is made in Node OR PHP?
Yes, AWS Elastic Beanstalk is service for deploying and scaling web applications and services developed with Java, .NET, PHP, Node.js, Python, Ruby, Go, and Docker on familiar servers such as Apache, Nginx, Passenger, and IIS.


Question: How does works Elastic Beanstalk?
You simply upload your code and Elastic Beanstalk automatically handles the deployment, from capacity provisioning, load balancing, and automatic scaling to web application health monitoring, with ongoing fully managed patch and security updates.


What are Benefits and features of Elastic Beanstalk?
  1. Easy to get started
    Elastic Beanstalk is the simplest way to deploy and run your web application on AWS.
  2. Complete resource control
    You have the freedom to select the AWS resources, such as Amazon EC2 instance types, that are optimal for your web application.
  3. Fully managed: update your web application with the latest platform security and patch updates.
  4. Automatic application health monitoring
    Elastic Beanstalk automatically collects more than 40 key metrics and attributes to determine the health of your web application



Question: What Language Supported by Elastic Beanstalk
  1. Go
  2. Java SE
  3. Java with Tomcat
  4. NET on Windows Server with IIS
  5. Node.js
  6. PHP
  7. Python
  8. Ruby
  9. Packer Builder



Question: How is AWS CloudFormation different from AWS Elastic Beanstalk?
AWS CloudFormation helps you provision and describe all of the infrastructure resources that are present in your cloud environment. On the other hand, AWS Elastic Beanstalk provides an environment that makes it easy to deploy and run applications in the cloud.
AWS CloudFormation supports the infrastructure needs of various types of applications, like legacy applications and existing enterprise applications. On the other hand, AWS Elastic Beanstalk is combined with the developer tools to help you manage the lifecycle of your applications.



Question: Who should use AWS Elastic Beanstalk?
Those who want to deploy and manage their applications within minutes in the AWS Cloud. You don’t need experience with cloud computing to get started. AWS Elastic Beanstalk supports Java, .NET, PHP, Node.js, Python, Ruby, Go, and Docker web applications.




Saturday 30 May 2020

PHP 7 Scalar type declarations and return type declarations

PHP 7  Scalar type declarations and return type declarations

What is a Scalar type declarations?
Allowing/Not-Allowing datatype declaration in functions is known as Scalar type declarations.


Question: What are different types of Scalar type declarations?
1) Coercive Mode (default)
2) Strict Mode


What are different type of data-type can be used in Scalar type declarations?
  1. int
  2. float
  3. bool
  4. string
  5. interfaces
  6. array
  7. callable



Question: Give the examples of Scalar type declarations with Coercive Mode (default)
Example 1
$a=1; // integer
$b=2; //integer
function FunctionName1(int $a, int $b){
return $a + $b;
}
echo FunctionName1($a, $b); //3


Example 2
   function sum(int ...$ints) {
      return array_sum($ints);
   }

   print(sum(3, '2', 5.1)); //10


Example 3
function FunctionName3(int $a, int $b){
return $a * $b;
}

echo FunctionName3('hello', 10); //PHP Fatal error: Uncaught TypeError: Argument 1 passed to FunctionName() must be of the type integer, string given.


Example 4
$a='1One'; 
$b=2; //integer
function FunctionName3(int $a, int $b){
return $a + $b;
}
echo FunctionName3($a, $b);//RESULT: PHP Notice: A non well formed numeric value encountered on line 5


Question: Give the examples of Scalar type declarations with STRICT MODE?
Example 1
declare(strict_types=1); 

$a=1; // integer
$b=2; //integer
function phpFunction (int $a, int $b){
return $a + $b;
}

echo phpFunction1($a, $b);//3

Example 2
declare(strict_types=1); 

$a='1'; // String
$b=2; //integer
function phpFunction1 (int $a, int $b){
return $a + $b;
}

echo phpFunction1($a, $b);//Fatal error: Uncaught TypeError: Argument 1 passed to phpFunction1() must be of the type int, string given


Question: Give the examples of Return type declarations with STRICT MODE?
Example 1
$a='10'; //  string
$b=2; // integer
function phpFunctionReturn ($a, $b) : int  {
return $a * $b;
}
echo phpFunctionReturn ($a, $b);


Example 2
declare(strict_types=1); 
$a='10'; //  string
$b=2; // integer
function phpFunctionReturn ($a, $b) : string  {
return $a * $b;
}
echo phpFunctionReturn ($a, $b);//PHP Fatal error:  Uncaught TypeError: Return value of phpFunctionReturn() must be of the type string, integer returned in /home/cg/root/7035270/main.php:6




Friday 29 May 2020

CSS3 interview questions and answers for experienced

css3 interview questions and answers for experienced



Question: How to write conditional statement in CSS?
<!--[if IE 7]>
<style type="text/css">
div.abc {                 
    background-color:red;
}
</style>
<![endif]-->



Question: How to write styles for all html elements of the same type?
Use tag name to write the CSS.
See Example
h1{font-size:18px;}
h2{font-size:17px;}
h3{font-size:16px;}
h4{font-size:15px;}



Question: What are different vaules of position attributes?
absolute
fixed
inherit
relative
static


Question: How to display a link without underline using CSS?
 a{
    text-decoration:none;
}



Question: How to display a link without underline when mouseover on the link using CSS?
 a:hover{
    text-decoration:none;
}



Question: How to page break after an html element in CSS?
<div style="page-break-after: always;">
Web Technology Experts Notes</div>



Question: What is the default value of "position" attribute in css?
static


Question: How we can specify more than one css class for any HTML element?
<div class="class1 class2">
Web technology experts Notes</div>




Question: Is CSS case sensitive?
No


Question: What is ID selector?
ID selector is an individually identified selector to which a specific style is declared.



Question: How to set wait cursor?
div.click{
    cursor:wait;
}




Question: What is Tweening ?
It process of generating intermediate frames between two images to give the appearance that the first image evolves smoothly into the second image.

Question: What are Child Selectors?
A child selector is used when you want to match an element that is the child of another specific element.
div.abc > ul {font-weight: bold;}



Question: What are different ways to apply styles to a Web page
Inline
Embedded
Linked
Imported



Question: What is contextual selector
Contextual selector addresses specific occurrence of an element.




Question: How to disable text selection highlighting with CSS?
.noselect {
  -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Old versions of Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome, Edge, Opera and Firefox */
}

Add the .noselect to the html tag





Saturday 18 April 2020

How to check if a number is prime?

How to check if a number is prime?


Question: What is Prime Number
A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers.


Question: Give the example of Prime Number
2, 3, 5, 7, 11, 13, 17, 19, 23 and 29.


Question: Write an function that check the prime number OR Not?
function checkPrime($number){
    if($number < 0 ){
        return false;
    }
    $return=true;
    for($i=2; $i < $number; $i++){
        if($number % $i ==0){
            $return=false;
            break;
        }
    }
   return $return;
}



Question: How to check a number is prime Or Not?
echo checkPrime(2)?'Prime':'Not Prime'; //Prime
echo checkPrime(4)?'Prime':'Not Prime'; //Not Prime
echo checkPrime(6)?'Prime':'Not Prime'; //Not prime
echo checkPrime(7)?'Prime':'Not Prime';  //Prime


Question: What are the prime numbers between 1 to 100?
for( $i = 2; $i < 100; $i++ ){
    if( checkPrime( $i ) ){
        echo $i;
        echo ',';
    }
}






Wednesday 8 April 2020

Difference between mysql.createConnection and mysql.createPool in Node.js?

Difference between mysql.createConnection and mysql.createPool in Node.js?

mysql.createConnection

When you create a connection with mysql.createConnection, you only have one connection and it lasts until you close it OR connection closed by MySQL.

A single connection is blocking. While executing one query, it cannot execute others. hence, your application will not perform good.
Example:
var mysql = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'mydb',
});


mysql.createPool

mysql.createPool is a place where connections get stored.
When you request a connection from a pool,you will receive a connection that is not currently being used, or a new connection.
If you're already at the connection limit, it will wait until a connection is available before it continues.

A pool while one connection is busy running a query, others can be used to execute subsequent queries. Hence, your application will perform good.
Example:
var mysql = require('mysql');
var pool  = mysql.createPool({
  connectionLimit : 10,
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'mydb',
});



Tuesday 7 April 2020

How to check active connections in MySQL?

How to check active connections in MySQL?

Question: How to check active connections in mysql?
show status where `variable_name` = 'Threads_connected';



Question: How to check the limit of MySQL active connections?
SHOW VARIABLES LIKE "max_connections";



Question: Display the list of active MySQL Process list?
show processlist;



Question: How to check the max no of connections used?
SHOW STATUS WHERE `variable_name` = 'Max_used_connections';



Question: MySQL set the max no of connections used (Temporarily/Quick)?
SET GLOBAL max_connections = 512;



Question: MySQL set the max no of connections used (Temporarily/Quick)?
Open my.cnf or my.ini in MySQL
max_connections = 512

service mysqld restart


Question: MySQL check number of connections throughout history?
show status like 'Connections%';

Sunday 5 April 2020

Laravel interview questions for 4 year experienced

Laravel interview questions for 4 year experienced

Question: What is Server Requirements for Laravel 5.6?
  1. PHP >= 7.1.3
  2. PDO PHP Extension
  3. Ctype PHP Extension
  4. OpenSSL PHP Extension
  5. XML PHP Extension
  6. JSON PHP Extension
  7. Mbstring PHP Extension
  8. Tokenizer PHP Extension

Question: What is Laravel Dusk?
It is expressive, easy-to-use browser automation and testing API.


Question: What is Laravel Echo?
Event broadcasting, evolved. Bring the power of WebSockets to your application without the complexity.


Question: How to Install Laravel via Composer?
composer create-project --prefer-dist laravel/laravel myproject



Question: How to Install any Specific version of Laravel via Composer
composer create-project --prefer-dist laravel/laravel blog "5.4.*" //Install Laravel 5.4 using Composer



Question: What is Lumen?
  1. Lumen is a micro-framework provided by Laravel.
  2. It is developed by creator of Laravel Taylor Otwell.
  3. It is mostly used for creating RESTful API's & microservices.
  4. Lumen is built on top components of Laravel.



Question: How to Install Lumen via Composer?
composer create-project --prefer-dist laravel/lumen myproject



Question: List benefits of using Laravel over other PHP frameworks?
  1. Artisan
  2. Migrations & Seeding
  3. Blade Template Engine
  4. Middleware - HTTP middleware provide a convenient mechanism for filtering HTTP requests
  5. Routing (RESTful routing)
  6. Authentication, Cashier, Scheduler, SSH, Socialite
  7. Security
  8. Unit Testing
  9. Caching


Question: Which Template Engine used by Laravel?
Blade is the simple, yet powerful templating engine provided with Laravel.


Question: How to enable maintenance mode in Laravel?
// Enable maintenance mode
php artisan down

// Disable maintenance mode
php artisan up



Question: What are Closures in Laravel?
A Closure is an anonymous function. Closures are often used as a callback methods and can be used as a parameter in a function.


Question: List out databases that laravel supports?
MySQL
PostgreSQL
SQLite
SQL Server


Question: How To Use Insert Query In Laravel?
class UserController extends Controller
{
    /**
     * Create a new user instance.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $user = new User;
        $user->name = $request->name;
        $user->role = $request->role;
        $user->save();
    }



Question: What are the available Router Methods?
Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);



Question: How To Use Update Query In Laravel?
$result = User::where('id',1)->update(['name'=>'My web technology experts notes']);



Question: How To Use Delete Query In Laravel?
$result = User::where('id',$id)->delete();



Question: What is Response in Laravel?
Following are different type of responses?
  1. View Responses
  2. JSON Responses
  3. File Downloads
  4. File Responses
  5. Response Macros
  6. Redirecting To Named Routes
  7. Redirecting To Controller Actions
  8. Redirecting To External Domains
  9. Redirecting With Flashed Session Data



Question: How to get current environment in Laravel?
$environment = App::environment();


Question: Where do you locate database configuration file?
Migrations are like version control for your database, that's allow to easily modify and share the application's database schema. Migrations are typically paired with Laravel's schema builder to easily build your application's database schema.


Question: What are laravel 6 features?
  1. Inbuilt CRSF (cross-site request forgery ) Protection.
  2. Inbuilt paginations
  3. Reverse Routing
  4. Query builder
  5. Route caching
  6. Database Migration
  7. IOC (Inverse of Control) .
  8. Job middleware
  9. Lazy collections



Friday 3 April 2020

Laravel interview questions for 3 year experienced

Laravel interview questions for 3 year experienced

Question: Explain validation in Laravel.?
ValidatesRequests is the trait which is been used by Laravel classes for validating input data.
public function store(Request $request)
{
   $validatedData = $request->validate([
       'title' => 'required|unique:posts|max:255',
       'description' => 'required',
       'email' => 'required',
   ]);
}



Question: What is CSRF protection and CSRF token?
Cross-site forgeries are a type of malicious exploit where unauthorized person/command do/run on behalf of the authenticated user.
Laravel generates a CSRF "token" automatically for each active user session.
This token is used to verify that the authenticated user is the one actually making the requests.


Question: What is Laravel Dusk?
It is expressive, easy-to-use browser automation and testing API.


Question: What is Laravel Echo?
Event broadcasting, evolved. Bring the power of WebSockets to your application without the complexity.


Question: How do you install Laravel?
Laravel utilizes Composer to manage its dependencies. So, before using Laravel, make sure we have Composer installed on your machine.


Question: Explain Binding Instances?
You may also bind an existing object instance into the container using the instance method.
$api = new HelpSpot\API(new HttpClient);
$this->app->instance("HelpSpot\API", $api);



Question: Explain Extending Bindings?
$this->app->extend(Service::class, function($service) {
    return new DecoratedService($service);
});



Question: What is the make Method?
You may use the make method to resolve a class instance out of the container.
$api = $this->app->make("HelpSpot\API");



Question: What is Register Method?
within the register method, you should only bind things into the service container.


Question: What is the Boot Method?
if we need to register a view composer within our service provider? This should be done within the boot method.


Question: Where do you regiser service providers?
config/app.php configuration file


Question: What are Laravel’s Contracts?
Laravel’s Contracts are a set of interfaces that define the core services provided by the framework.


Question: Give example of Router?
Route::get("foo", function () {
return "Hello World";
});



Question: What are the available Router Methods?
Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);



Question: How to 301 redirect in laravel (permanent redirect)
Route::redirect("/old", "/new", 301);



Question: How to 302 redirectin laravel (temporary redirect)
Route::redirect("/old", "/new", 302);



Question: What are Middleware Groups?
Sometimes you may want to group several middleware under a single key to make them easier to assign to routes.


Question: What are Redirect responses?
Redirect responses are instances of the Illuminate\Http\RedirectResponse class, and contain the proper headers needed to redirect the user to another URL.


Question: Where do you locate database configuration file?
The database configuration for your application is located at config/database.php.


Question: What are Blade Templates?
Blade is the simple, yet powerful templating engine provided with Laravel.


Wednesday 1 April 2020

Laravel interview questions for 2 year experienced

Laravel interview questions for 2 year experienced

Question: How to get current route name and method name?
request()->route()->getName(); //Return route name
request()->route()->getActionMethod();//Return method name



Question: What do you mean by bundles?
Bundles are referred to as packages in Laravel. These packages are used to increase the functionality of Laravel.


Question: Explain important directories used in a common Laravel application.?
App/ : This is a source folder where our application code lives. All controllers, policies, and models are in this folder.
Config/ : Here are configuration files.
Database/: Houses the database files, including migrations, seeds, and test factories.
Public/: Publicly accessible folder holding compiled assets and of course an index.php file.


Question: Explain reverse routing in Laravel.
Reverse routing is a method of generating URL based on symbol or name. It makes your Laravel application flexible.


Question: Define Lumen?
Lumen framework is a smaller, and faster, version of a building Laravel based services, and REST API's.


Question: How can you generate URLs?
Laravel has helpers to generate URLs.


Question: Explain faker in Laravel?
It is a type of module or packages which are used to create fake data. This data can be used for testing purpose.


Question: List basic concepts in Laravel?
  1. Routing
  2. Eloquent ORM
  3. Middleware
  4. Security
  5. Caching
  6. Blade Templating



Question: What is Eloquent?
Eloquent is an ORM used in Laravel. It provides simple active record implementation working with the database.


Question: What is the use of DB facade?
DB facade is used to run SQL queries like create, select, update, insert, and delete.


Question: What is a session in Laravel?
Session is used to pass user information from one web page to another.
Support for cookie, array, file, Memcached, and Redis to handle session data.


Question: Explain to listeners?
Listeners are used to handling events and exceptions.


Question: What are policies classes?
Policies classes include authorization logic of Laravel application.


Question: What is an Observer? Observeris used to make clusters of event listeners for a model.
Method names of these classes depict the Eloquent event. Observers classes methods receive the model as an argument.

Question: What is the use of the bootstrap directory?
It is used to initialize a Laravel project. This bootstrap directory contains app.php file.


Question: Where will you define Laravel's Facades?
In Illuminate\Support\Facades namespace.


Question: Name databases supported by Laravel.
  1. MySQL
  2. SQLite
  3. SQL Server
  4. PostgreSQL



Question: What is the default session timeout duration?
2 hours.


Question: How to remove a complied class file?
Use clear-compiled command.


Question: In which folder robot.txt is placed?
Robot.txt file is placed in Public directory.


Laravel interview questions for 1 year experience

Laravel interview questions for 1 year experience

Question: How to make a helper file in laravel?
  1. Please create a app/helpers.php file in app folder.
  2. Add Following in in autoload variable.
    "files": [
        "app/helpers.php"
    ]
  3. Now update your composer.json
    composer update



Question: How to use mail() in laravel?
Mail::send('emails.reminder', ['user' => $user], function ($m) use ($user) {
    $m->from('from@example.com', 'Send Name');
    $m->to('receiver@example.com', 'Receiver Name')->subject('Your Reminder!');
});



Question: What is a REPL?
REPL is a type of interactive shell that takes in single user inputs, process them, and returns the result to the client. The full form of REPL is Read—Eval—Print—Loop


Question: How to use update query in Laravel?
Use Update function. for example
Blog::where(['id' => 10023])->update([
   'title' => 'Interview Questions',
   'content’ => 'Web Technology exerts notes'
]); 



Question: How to use multiple OR condition in Laravel Query?
Blog::where(['id' => 10023])->orWhere(['username’ => 'username12'])->update(['title' => 'Interview Questions',]);



Question: What are different type of where Clauses in Laravel?
  1. where()
  2. orWhere()
  3. whereBetween()
  4. orWhereBetween()
  5. whereNotBetween()
  6. orWhereNotBetween()
  7. wherein()
  8. whereNotIn()
  9. orWhereIn()
  10. orWhereNotIn()
  11. whereNull()
  12. whereNotNull()
  13. orWhereNull()
  14. orWhereNotNull()
  15. whereDate()
  16. whereMonth()
  17. whereDay()
  18. whereYear()
  19. whereTime()
  20. whereColumn()
  21. orWhereColumn()
  22. whereExists()



Question: What is updateOrInsert method? Give example?
updateOrInsert() method is used to update an existing record in the database if matching the condition or create if no matching record exists.
Blog::updateOrInsert([
   'title' => 'Interview Questions',   
]); 



Question: How to check table is exists or not in our database using Laravel?
if(Schema::hasTable('users')) {
    echo "Table Exists";
} else {
    echo "Table does not exists"
} 



Question: How to check column is exists or not in a table using Laravel?
if(Schema::hasColumn('users', 'title')) ; //check whether admin table has username column
{
   echo "Column Exists in table";
}else{
    echo "Column does not Exists in table";
}



Question: What are the difference between insert() and insertGetId() in laravel?
Inserts(): This method is used for insert records into the database table.
insertGetId(): This method is used for insert records into the database table and return the autoincrement-id.


Question: What is lumen?
Lumen is a PHP framework which is a faster, smaller and leaner version of a full web application framework.


Question: What is the full form of ORM in Laravel?
Object Relational Mapping.


Question: How to get current route name and method name?
request()->route()->getName(); //Return route name
request()->route()->getActionMethod();//Return method name



Question: How to check Ajax request in Laravel?
You can use the following syntax to check ajax request in laravel.
if ($request->ajax()) {
     echo "This is ajax requrest";
}



Question: What do you mean by bundles? In Laravel, bundles are referred to as packages.
These packages are used to increase the functionality of Laravel.
A package can have views, configuration, migrations, routes, and tasks.


Question: Name databases supported by Laravel.

  1. PostgreSQL
  2. SQL Server
  3. SQLite
  4. MySQL



Monday 30 March 2020

Laravel Interview Questions and answers for Fresher

Laravel Interview Questions and answers for Fresher

Question: What are the new features of Laravel 7?
Laravel 7.0 is incorporated features such as Better routing speed, Laravel Airlock, Custom Eloquent casts, Fluent string operations, CORS support, and many more features like below.
  1. Custom Eloquent Casts
  2. Route Caching Speed Improvements
  3. HTTP Client
  4. Query Time Casts
  5. Blade Component Tags & Improvements
  6. Laravel Airlock
  7. CORS Support
  8. Fluent string operations
  9. Multiple Mail Drivers
  10. New Artisan Commands etc


Question: What is the use of dd() in Laravel?
It is a helper function which is used to dump a variable's contents to the browser.
dd($arrayData);



Question: How to make a helper file in laravel?
  1. Please create a app/helpers.php file in app folder.
  2. Add Following in in autoload variable.
    "files": [
        "app/helpers.php"
    ]
  3. Now update your composer.json
    composer update


Question: What is PHP artisan in laravel? Name some common artisan commands?
Artisan is a type of the "command line interface" using in Laravel.
It supports following commands to execute.
  1. php artisan list
  2. php artisan –version
  3. php artisan down
  4. php artisan help
  5. php artisan up
  6. php artisan make:controller
  7. php artisan make:mail
  8. php artisan make:model
  9. php artisan make:migration
  10. php artisan make:middleware
  11. php artisan make:auth
  12. php artisan make:provider etc.


Question: What is laravel Service container?
Service Container is a powerful tool which is used to manage class dependencies and perform dependency injection.


Question: How to get last inserted id using laravel query?
$blogObj = new Blog;
$blogObj->title = "Web technology experts notes";
$blogObj->save(); //Save the data 
echo $blogObj->id // Return the last inserted id


Question: How to use mail() in laravel?
Mail::send('emails.reminder', ['user' => $user], function ($m) use ($user) {
    $m->from('from@example.com', 'Send Name');
    $m->to('receiver@example.com', 'Receiver Name')->subject('Your Reminder!');
});


Question: What is Auth?
Auth is in-built functionality provided by Laravel to identifying the user credentials with the database.


Question: How to make a constant? and how to use?
Add element in constants.php which should be in config folder.
return [
    'EMAIL_FROM' => 'from@example.com',
];

Get the value from config file.
echo Config::get('constants.EMAIL_FROM');//from@example.com



Question: What is with() in Laravel?
with() function is used to eager load in Laravel.


Question: How to get user’s ip address in laravel?
request()->ip()



Question: Difference between softDelete() & delete() in Laravel?
delete(): Record delete permanently.
softDelete(): records did not remove from the table only delele_at value updated with current date and time.


Question: How to enable query log in laravel?
DB::connection()->enableQueryLog();
$querieslog = DB::getQueryLog();
dd($querieslog) //Print the logs



Question: How to use skip() and take() in Laravel Query?
$posts = DB::table('blog')->skip(5)->take(10)->get();


Question: Give the list of Design Patterns in Laravel?
  1. The Builder pattern
  2. The Repository pattern
  3. The need for the Builder pattern
  4. The need for the Factory pattern
  5. The Factory pattern
  6. The Provider pattern
  7. The Facade pattern
  8. The Strategy pattern

Question: What are views?
Views contain the HTML provided by our application (UI part).


Question: What is faker in Laravel?
Faker is a type of module or packages which are used to create fake data for testing purposes.


Sunday 29 March 2020

How do I copy to the clipboard in JavaScript?

How do I copy to the clipboard in JavaScript?

Step 1: Add Following javascript function in Web page.
    function selectAllData(id) {
    var obj = document.getElementById(id);
        var text_val=eval(obj);
        text_val.focus();
        text_val.select();
        if (!document.all) return; // if IE return;
        r = text_val.createTextRange();
        r.execCommand('copy');
    }

Step 2: call selectAllData('id') function with passing the id of the container. See Example
<input onclick="return selectAllData('textareaId')" type="button" value="Select All" />


Following are consolidate Code:

<script type="text/javascript"> function selectAllData(id) { var obj = document.getElementById(id); var text_val=eval(obj); text_val.focus(); text_val.select(); if (!document.all) return; // if IE return; r = text_val.createTextRange(); r.execCommand('copy'); }</script> <textarea cols="30" id="textareaId" row="50"> javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers </textarea> <input onclick="return selectAllData('textareaId')" type="button" value="Select All" />


See demo:






Question: What is the most efficient way to deep clone an object in JavaScript?
const a = {
  string: 'string',
  number: 123,
  bool: false,
  nul: null,
  date: new Date(), 
}
console.log(a);
console.log(typeof a.date);  // Date object
const clone = JSON.parse(JSON.stringify(a));
console.log(clone);