Sunday, September 18, 2016

Apache Interview Questions

1) How to check the version of Apache server ?

Ans: # httpd -v

2) What is meaning of “Listen” in httpd.conf file ?

Ans: Port number on which to listen for nonsecure (http) transfers.

3) If you specify both deny from all and allow from all, what will be the default action of Apache?

Ans: Deny always takes precedence over allow.

4) What is DocumentRoot ?

Ans: The document root is a directory that is designated for holding web pages. By default, the Apache HTTP server is configured to serve files from the /var/www/html/ directory.

5) Tell me name of main configuration file of Apache server ?

Ans: /etc/httpd/conf/httpd.conf

6)Does Apache act as Proxy server?

Ans:Yes,using mod_proxy module.

7) What do you mean by a ServerName directive?

Ans: The DNS system is used to associate IP addresses with domain names. The value of ServerName is returned when the server generates a URL. If you are using a certain domain name, you must make sure that it is included in your DNS system and will be available to clients visiting your site.

8) What is the main difference between and sections?

Ans: Directory sections refer to file system objects; Location sections refer to elements in the address bar of the Web page

9) What is the difference between a restart and a graceful restart of a web server?

Ans: During a normal restart, the server is stopped and then started, causing some requests to be lost. A graceful restart allows Apache children to continue to server their current requests until they can be replaced with children running the new configuration.

10) What is the difference between ServerName directive and ServerAlias?

Ans: ServerName directive is hostname and port that the server uses to identify itself and ServerAlias is alternate names for a host used when matching requests to name-virtual hosts.

11) How t to enable PHP scripts on your server?

Ans: If you have mod_php installed, use AddHandler.
AddHandler application/x-httpd-php .phtml .php

12) How to enable htaccess on Apache?

Ans:
Open httpd.conf and remove the comment on line from

;LoadModule rewrite_module modules/mod_rewrite.so

Find the following
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all

Replace it
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
allow from all

13) What is ServerType directive?

Ans: It defines whether Apache should spawn itself as a child process (standalone) or keep everything in a single process (inetd). Keeping it inetd conserves resources. This is deprecated, however.

14) What is mod_vhost_alias?

Ans: It allows hosting multiple sites on the same server via simpler configurations.

15) Which tool you have used for Apache benchmarking?

Ans: ab (Apache bench) ab -n 1000 -c 10 http://www.techoism.com/launch-an-amazon-ec2-instance/

16) How you will put a limit on uploads on your web server?

Ans: This can be achieved be LimitRequestBody directive.
<Directory "/usr/local/apache2/htdoc/wp-content/uploads">
LimitRequestBody 100000
<Directory>
Here I have put limit of 100000 Bytes

17) I want to stop people using my site by Proxy server. Is it possible>

Ans:
<Directory "proxy:http://www.techoism.com/content">
Order Allow,Deny
Satisfy All
<Directory>

18) What we can do to find out how people are reaching your site?

Ans: Add the following effector to your activity log format.%{Referer}

19) If you have added “loglevel debug” in htpd.conf file, than what will happen?

Ans: It will give you more information in the error log in order to debug a problem.

20) How to check for the httpd.conf consistency and any errors in it?

Ans: httpd -t

Nginx Interview Questions

1) Explain what is Nginx?

Nginx is a web server and a reverse proxy server for HTTP, HTTPS, SMTP, POP3 and IMAP protocols.

2) Mention some special features of Nginx?

Special features of the Nginx server includes

    Reverse proxy/ L7 Load Balancer
    Embedded Perl interpreter
    On the fly binary upgrade
    Useful for re-writing URLs and awesome PCRE support

3) Mention what is the difference between Nginx and Apache?
   
   #Nginx                                    

    Nginx is an event based web server
    All request are handled by a single thread.
    Nginx avoids child processes idea.
    Nginx resembles speed
    Nginx is better when it comes to memory consumption and connection
    Nginx is better when you want load-balancing
    For PHP, Nginx might be preferable as it supports PHP internally
    Nginx do not support O.S like IBMi and OpenVMS.
    Nginx comes only with core features
    Nginx performance and scalability do not depend on hardware

   
    #Apache
     Apache is a process based server
    Single thread handles a single request.
    Apache is based on child processes
    Apache resemble power
    Apache is not up-to the mark when it comes to memory consumption and connection
    Apache will refuse new connections when traffic reaches the limit of processes
    Apache support’s PHP, Python, Perl and other languages using plugins. It is useful when application is based on Python or Ruby
    Apache support much wider range of O.S
    Apache provides lot more functionality than Nginx
    Apache is dependent on hardware components like CPU and memory

4) Explain how Nginx can handle HTTP requests?

Nginx uses the reactor pattern.  The main event loop waits for the OS to signal a readiness event- such that the data is accessible to read from a socket, at which instance it is read into the buffer and processed.  A Single thread can serve tens of thousands of simultaneous connections.

5) In Nginx how you can prevent processing requests with undefined server names?

A server that just drops the requests can be defined as



Server {

listen                80;

server_name  “ “ ;

return              444;

}

Here the server name is kept as an empty string which will match request without the “Host” header field, and a special Nginx’s non-standard code 444 is returned that terminates the connection.

Nginx-logo

6) What is the advantage of using a “reverse proxy server”?

The reverse proxy server can hide the presence and characteristics of the origin server. It acts as an intermediate between internet cloud and web server. It is good for security reason especially when you are using web hosting services.

7) Mention what is the best usage of Nginx server?

The best usage of Nginx server is to deploy dynamic HTTP content on a network with using SCGI, WSGI application servers, FastCGI handlers for scripts.  It can also serve as a load balancer.

8) Mention what is the Master and Worker Processes in Nginx Server?

    Worker processes: It reads and evaluate configuration and maintain worker processes.
    Master processes: It actually does the processing of the requests.

9) Explain how you can start Nginx through a different port other than 80?

To start Nginx through a different port, you have to go to /etc/Nginx/sites-enabled/ and if this is the default file, then you have to open file called “default.” Edit the file and put the port you want

Like server { listen 81; }

10) Explain is it possible to replace Nginx errors like 502 error with 503?

    502= Bad gateway
    503= Server overloaded

Yes, it is possible but you to ensure that fastcgi_intercept_errors is set to ON, and use the error page directive.



Location / {

fastcgi_pass 127.0.01:9001;

fastcgi_intercept_errors on;

error_page 502 =503/error_page.html;

#…

}

11) In Nginx, explain how you can keep double slashes in URLs?

To keep double slashes in URLs you have to use merge_slashes_off;

Syntax: merge_slashes [on/off]

Default: merge_slashes on

Context: http, server

12) Explain what is ngx_http_upstream_module is used for?

The ngx_http_upstream_module is used to define groups of servers that can reference by the fastcgi pass, proxy pass, uwsgi pass, memcached pass and scgi pass directives.

13) Explain what is C10K problem?

C10K problem is referred for the network socket unable to handle a large number of client (10,000) at the same time.

14) Mention what is the use of stub_status and sub_filter directives?

    Stub_status directive: This directive is used to know the current status of Nginx like current active connection, total connection accepted and handled current number of read/write/wait connection
    Sub_filter directive: It is used to search and replace the content in response, and quick fix for stale data

15) Explain does Nginx support compress the request to the upstream?

You can compress the request to the upstream by using the Nginx module gunzip. The gunzip module is a filter that decompresses responses with “Content Encoding: gzip” for clients or servers that do not support “gzip” encoding method.

16) Explain how you can get the current time in Nginx?

To get the current time in Nginx, you have to use variables from SSI module, $date_gmt and $date_local.

    Proxy_set_header THE-TIME $date_gmt;

17) Explain what is the purpose of –s with Nginx Server?

To run the executable file of Nginx –s parameter is used.

18) Explain how to add modules in Nginx Server?

During the compilation process, Nginx modules must be selected as such run-time selection of modules is not supported by Nginx.

Cucumber Interview Questions

Cucumber – a Behavior Driven Development (BDD) framework which is used with Selenium for performing acceptance testing.

Cucumber Introduction:

Cucumber is a tool based on Behavior Driven Development (BDD) framework which is used to write acceptance tests for web application. It allows automation of functional validation in easily readable and understandable format (like plain English) to Business Analysts, Developers, Testers, etc.
Cucumber feature files can serve as a good document for all. There are many other tools like JBehave which also support BDD framework. Initially Cucumber was implemented in Ruby and then extended to Java framework. Both the tools support native JUnit.
Behavior Driven Development is extension of Test Driven Development and it is used to test the system rather than testing the particular piece of code. We will discuss more about the BDD and style of writing BDD tests.
Cucumber can be used along with Selenium, Watir, and Capybara etc. Cucumber supports many other languages like Perl, PHP, Python, .Net etc. In this tutorial we will concentrate on Cucumber with Java as a language.

Cucumber Basics:

In order to understand cucumber we need to know all the features of cucumber and its usage.
#1) Feature Files:
Feature files are essential part of cucumber which is used to write test automation steps or acceptance tests. This can be used as live document. The steps are the application specification. All the feature files ends with .feature extension.
Sample feature file:
Feature: Login Functionality Feature
In order to ensure Login Functionality works,
I want to run the cucumber test to verify it is working
Scenario: Login Functionality
Given user navigates to SOFTWARETETINGHELP.COM
When user logs in using Username as “USER” and Password “PASSWORD”
Then login should be successful
Scenario: Login Functionality
Given user navigates to SOFTWARETETINGHELP.COM
When user logs in using Username as “USER1” and Password “PASSWORD1”
Then error message should be thrown


 ============================================

1) What is Cucumber and what are the advantages of Cucumber?

To run functional tests written in a plain text Cucumber tool is used. It is written in a Ruby programming language.

Advantages of Cucumber

    You can inolve business stakeholders who can not code
    End user experience is priority
    High code reuse

2) What are the 2 files required to execute a Cucumber test scenario?

The 2 files required to execute a Cucumber test scenario are

    Features
    Step Definition

3) What is feature file in Cucumber? What does feature file consist of ?

Feature file in cucumber consist of parameters or conditions required for executing code, they are

    Feature
    Scenario
    Scenario Outline
    Given
    When
    Then

4) Give an example of behaviour driven test in plain text?

    Feature: Visit XYZ page in abc.com
    Scenario : Visit abc.com
    Given:  I am on abc.com
    When:  I click on XYZ page
    Then:  I should see ABC page

5) Explain what is Scenario Outline in feature file?

Scenario Outline:  Same scenario can be executed for multiple sets of data using scenario outline.  The data is provided by a tabular structure separated by (I   I).

6) What is step definition in Cucumber?

A step definition is the actual code implementation of the feature mentioned in feature file.

061114_1018_Introductio1

7) Give the example for step definition using “Given” function?

For example to make visitor visit the site “Yahoo” the command we use for given

Given (/^ I am on www.yahoo.com$/) do

Browser.goto “http://www.yahoo.com”

end – This will visit www.yahoo.com

8) What are the difference between Jbehave and Cucumber?

Although Cucumber and Jbehave are meant for the same purpose, acceptance tests are completely different frameworks

    Jbehave is Java based and Cucumber is Ruby based
    Jbehave are based on stories while Cucumber is based on features

9) Explain what is test harness?

A test harness for cucumber and rspec allows for separating responsibility between setting up the context and interacting with the browser and cleaning up the step definition files

10) Explain when to use Rspec and when to use Cucumber?

    Rspec is used for Unit Testing
    Cucumber is used behaviour driven development. Cucumber can be used for System and Integration Tests

11) What is the language used for expressing scenario in feature file ?

Gherkin language is used to express scenario in feature files and ruby files containing unobtrusive automation for the steps in scenarios

12) Explain what is regular expressions?

A regular expression is a pattern describing a certain amount of text.  The most basic regular expression consists of a single literal character

13) Explain what is BDD (Behaviour Driven Development) ?

BDD or Behaviour driven development is a process of developing software based on TDD (Test Driven Development) which focusses on behavioural specification of software units.

14) What softare do you need to run a Cucumber Web Test ?

    Ruby and its Development Kit
    Cucumber
    IDE like ActiveState
    Watir ( To simulate browser)
    Ansicon and rspec (if required)

15) What does a features/ support file contains?

Features/ support file contains supporting ruby code. Files in support load before those in step_definitions, which can be useful for environment configuration.

Saturday, September 17, 2016

1) Explain what is object oriented programming language?
Object oriented programming language allows concepts such as modularity, encapsulation, polymorphism and inheritance. Objects are said to be the most important part of object oriented language. Concept revolves around making simulation programs around an object. Organize a program around its data (object)& set well define interface to that data. i.e. objects and a set of well defined interfaces to that data. OOP is the common abbreviation for Object-Oriented Programming. OOps have many properties such as DataHiding,Inheritence,Data Absraction,Data Encapsulation and many more.

2) Name some languages which have object oriented language and characteristics?
Some of the languages which have object oriented languages present in them are ABAP, ECMA Script, C++, Perl, LISP, C#, Tcl, VB, Ruby, Python, PHP, etc. Popularity of these languages has increased considerably as they can solve complex problems with ease.

3) Explain about UML?
UML or unified modeling language is regarded to implement complete specifications and features of object oriented language. Abstract design can be implemented in object oriented programming languages. It lacks implementation of polymorphism on message arguments which is a OOPs feature.

4) Explain the meaning of object in object oriented programming?
Languages which are called as object oriented almost implement everything in them as objects such as punctuations, characters, prototypes, classes, modules, blocks, etc. They were designed to facilitate and implement object oriented methods.

5) Explain about message passing in object oriented programming?
Message passing is a method by which an object sends data to another object or requests other object to invoke method. This is also known as interfacing. It acts like a messenger from one object to other object to convey specific instructions.

6) State about Java and its relation to Object oriented programming?
Java is widely used and its share is increasing considerably which is partly due to its close resemblance to object oriented languages such as C++. Code written in Java can be transported to many different platforms without changing it. It implements virtual machine.

7) What are the problems faced by the developer using object oriented programming language?

These are some of the problems faced by the developer using object oriented language they are: -

a) Object oriented uses design patterns which can be referred to as anything in general.
b) Repeatable solution to a problem can cause concern and disagreements and it is one of the major problems in software design.
8 ) State some of the advantages of object oriented programming?
Some of the advantages of object oriented programming are as follows: -
a) A clear modular structure can be obtained which can be used as a prototype and it will not reveal the mechanism behind the design. It does have a clear interface.
b) Ease of maintenance and modification to the existing objects can be done with ease.
c) A good framework is provided which facilitates in creating rich GUI applications.

9 ) Explain about inheritance in OOPS?
Objects in one class can acquire properties of the objects in other classes by way of inheritance. Reusability which is a major factor is provided in object oriented programming which adds features to a class without modifying it. New class can be obtained from a class which is already present.

10) Explain about the relationship between object oriented programming and databases?
Object oriented programming and relational database programming are almost similar in software engineering. RDBMS will not store objects directly and that’s where object oriented programming comes into play. Object relational mapping is one such solution.

11) Explain about a class in OOP?
In Object oriented programming usage of class often occurs. A class defines the characteristics of an object and its behaviors. This defines the nature and functioning of a specified object to which it is assigned. Code for a class should be encapsulated.

12) Explain the usage of encapsulation?
Encapsulation specifies the different classes which can use the members of an object. The main goal of encapsulation is to provide an interface to clients which decrease the dependency on those features and parts which are likely to change in future. This facilitates easy changes to the code and features.

13) Explain about abstraction?
Abstraction can also be achieved through composition. It solves a complex problem by defining only those classes which are relevant to the problem and not involving the whole complex code into play.

14) Explain what a method is?
A method will affect only a particular object to which it is specified. Methods are verbs meaning they define actions which a particular object will perform. It also defines various other characteristics of a particular object.

15) Name the different Creational patterns in OO design?
There are three patterns of design out of which Creational patterns play an important role the various patterns described underneath this are: -
a) Factory pattern
b) Single ton pattern
c) Prototype pattern
d) Abstract factory pattern
e) Builder pattern

16) Explain about realistic modeling?
As we live in a world of objects, it logically follows that the object oriented approach models the real world accurately. The object oriented approach allows you to identify entities as objects having attributes and behavior.

17) Explain about the analysis phase?
The anlaysis or the object oriented analysis phase considers the system as a solution to a problem in its environment or domain. Developer concentrates on obtaining as much information as possible about the problem. Critical requirements needs to be identified.

1) Explain the rationale behind Object Oriented concepts?

Object oriented concepts form the base of all modern programming languages. Understanding the basic concepts of object-orientation helps a developer to use various modern day programming languages, more effectively.

2) Explain about Object oriented programming?
Object oriented programming is one of the most popular methodologies in software development. It offers a powerful model for creating computer programs. It speeds the program development process, improves maintenance and enhances reusability of programs.

3) Explain what is an object?
An object is a combination of messages and data. Objects can receive and send messages and use messages to interact with each other. The messages contain information that is to be passed to the recipient object.

4) Explain the implementation phase with respect to OOP?
The design phase is followed by OOP, which is the implementation phase. OOP provides specifications for writing programs in a programming language. During the implementation phase, programming is done as per the requirements gathered during the analysis and design phases.

5) Explain about the Design Phase?
In the design phase, the developers of the system document their understanding of the system. Design generates the blue print of the system that is to be implemented. The first step in creating an object oriented design is the identification of classes and their relationships.

6) Explain about a class?
Class describes the nature of a particular thing. Structure and modularity is provided by a Class in object oriented programming environment. Characteristics of the class should be understandable by an ordinary non programmer and it should also convey the meaning of the problem statement to him. Class acts like a blue print.

7) Explain about instance in object oriented programming?
Every class and an object have an instance. Instance of a particular object is created at runtime. Values defined for a particular object define its State. Instance of an object explains the relation ship between different elements.

8 ) Explain about inheritance?
Inheritance revolves around the concept of inheriting knowledge and class attributes from the parent class. In general sense a sub class tries to acquire characteristics from a parent class and they can also have their own characteristics. Inheritance forms an important concept in object oriented programming.

9) Explain about multiple inheritance?
Inheritance involves inheriting characteristics from its parents also they can have their own characteristics. In multiple inheritance a class can have characteristics from multiple parents or classes. A sub class can have characteristics from multiple parents and still can have its own characteristics.

10) Explain about encapsulation?
Encapsulation passes the message without revealing the exact functional details of the class. It allows only the relevant information to the user without revealing the functional mechanism through which a particular class had functioned.

11) Explain about abstraction?
Abstraction simplifies a complex problem to a simpler problem by specifying and modeling the class to the relevant problem scenario. It simplifies the problem by giving the class its specific class of inheritance. Composition also helps in solving the problem to an extent.

12) Explain the mechanism of composition?
Composition helps to simplify a complex problem into an easier problem. It makes different classes and objects to interact with each other thus making the problem to be solved automatically. It interacts with the problem by making different classes and objects to send a message to each other.

13) Explain about polymorphism?
Polymorphism helps a sub class to behave like a parent class. When an object belonging to different data types respond to methods which have a same name, the only condition being that those methods should perform different function.

14) Explain about overriding polymorphism?
Overriding polymorphism is known to occur when a data type can perform different functions. For example an addition operator can perform different functions such as addition, float addition etc. Overriding polymorphism is generally used in complex projects where the use of a parameter is more.

15) Explain about object oriented databases?
Object oriented databases are very popular such as relational database management systems. Object oriented databases systems use specific structure through which they extract data and they combine the data for a specific output. These DBMS use object oriented languages to make the process easier.

16) Explain about parametric polymorphism?
Parametric polymorphism is supported by many object oriented languages and they are very important for object oriented techniques. In parametric polymorphism code is written without any specification for the type of data present. Hence it can be used any number of times.

17) What are all the languages which support OOP?
There are several programming languages which are implementing OOP because of its close proximity to solve real life problems. Languages such as Python, Ruby, Ruby on rails, Perl, PHP, Coldfusion, etc use OOP. Still many languages prefer to use DOM based languages due to the ease in coding.

OOP

1) Explain what is object oriented programming language?
Object oriented programming language allows concepts such as modularity, encapsulation, polymorphism and inheritance. Objects are said to be the most important part of object oriented language. Concept revolves around making simulation programs around an object. Organize a program around its data (object)& set well define interface to that data. i.e. objects and a set of well defined interfaces to that data. OOP is the common abbreviation for Object-Oriented Programming. OOps have many properties such as DataHiding,Inheritence,Data Absraction,Data Encapsulation and many more.

2) Name some languages which have object oriented language and characteristics?
Some of the languages which have object oriented languages present in them are ABAP, ECMA Script, C++, Perl, LISP, C#, Tcl, VB, Ruby, Python, PHP, etc. Popularity of these languages has increased considerably as they can solve complex problems with ease.

3) Explain about UML?
UML or unified modeling language is regarded to implement complete specifications and features of object oriented language. Abstract design can be implemented in object oriented programming languages. It lacks implementation of polymorphism on message arguments which is a OOPs feature.

4) Explain the meaning of object in object oriented programming?
Languages which are called as object oriented almost implement everything in them as objects such as punctuations, characters, prototypes, classes, modules, blocks, etc. They were designed to facilitate and implement object oriented methods.

5) Explain about message passing in object oriented programming?
Message passing is a method by which an object sends data to another object or requests other object to invoke method. This is also known as interfacing. It acts like a messenger from one object to other object to convey specific instructions.

6) State about Java and its relation to Object oriented programming?
Java is widely used and its share is increasing considerably which is partly due to its close resemblance to object oriented languages such as C++. Code written in Java can be transported to many different platforms without changing it. It implements virtual machine.

7) What are the problems faced by the developer using object oriented programming language?

These are some of the problems faced by the developer using object oriented language they are: -

a) Object oriented uses design patterns which can be referred to as anything in general.
b) Repeatable solution to a problem can cause concern and disagreements and it is one of the major problems in software design.
8 ) State some of the advantages of object oriented programming?
Some of the advantages of object oriented programming are as follows: -
a) A clear modular structure can be obtained which can be used as a prototype and it will not reveal the mechanism behind the design. It does have a clear interface.
b) Ease of maintenance and modification to the existing objects can be done with ease.
c) A good framework is provided which facilitates in creating rich GUI applications.

9 ) Explain about inheritance in OOPS?
Objects in one class can acquire properties of the objects in other classes by way of inheritance. Reusability which is a major factor is provided in object oriented programming which adds features to a class without modifying it. New class can be obtained from a class which is already present.

10) Explain about the relationship between object oriented programming and databases?
Object oriented programming and relational database programming are almost similar in software engineering. RDBMS will not store objects directly and that’s where object oriented programming comes into play. Object relational mapping is one such solution.

11) Explain about a class in OOP?
In Object oriented programming usage of class often occurs. A class defines the characteristics of an object and its behaviors. This defines the nature and functioning of a specified object to which it is assigned. Code for a class should be encapsulated.

12) Explain the usage of encapsulation?
Encapsulation specifies the different classes which can use the members of an object. The main goal of encapsulation is to provide an interface to clients which decrease the dependency on those features and parts which are likely to change in future. This facilitates easy changes to the code and features.

13) Explain about abstraction?
Abstraction can also be achieved through composition. It solves a complex problem by defining only those classes which are relevant to the problem and not involving the whole complex code into play.

14) Explain what a method is?
A method will affect only a particular object to which it is specified. Methods are verbs meaning they define actions which a particular object will perform. It also defines various other characteristics of a particular object.

15) Name the different Creational patterns in OO design?
There are three patterns of design out of which Creational patterns play an important role the various patterns described underneath this are: -
a) Factory pattern
b) Single ton pattern
c) Prototype pattern
d) Abstract factory pattern
e) Builder pattern

16) Explain about realistic modeling?
As we live in a world of objects, it logically follows that the object oriented approach models the real world accurately. The object oriented approach allows you to identify entities as objects having attributes and behavior.

17) Explain about the analysis phase?
The anlaysis or the object oriented analysis phase considers the system as a solution to a problem in its environment or domain. Developer concentrates on obtaining as much information as possible about the problem. Critical requirements needs to be identified.

1) Explain the rationale behind Object Oriented concepts?

Object oriented concepts form the base of all modern programming languages. Understanding the basic concepts of object-orientation helps a developer to use various modern day programming languages, more effectively.

2) Explain about Object oriented programming?
Object oriented programming is one of the most popular methodologies in software development. It offers a powerful model for creating computer programs. It speeds the program development process, improves maintenance and enhances reusability of programs.

3) Explain what is an object?
An object is a combination of messages and data. Objects can receive and send messages and use messages to interact with each other. The messages contain information that is to be passed to the recipient object.

4) Explain the implementation phase with respect to OOP?
The design phase is followed by OOP, which is the implementation phase. OOP provides specifications for writing programs in a programming language. During the implementation phase, programming is done as per the requirements gathered during the analysis and design phases.

5) Explain about the Design Phase?
In the design phase, the developers of the system document their understanding of the system. Design generates the blue print of the system that is to be implemented. The first step in creating an object oriented design is the identification of classes and their relationships.

6) Explain about a class?
Class describes the nature of a particular thing. Structure and modularity is provided by a Class in object oriented programming environment. Characteristics of the class should be understandable by an ordinary non programmer and it should also convey the meaning of the problem statement to him. Class acts like a blue print.

7) Explain about instance in object oriented programming?
Every class and an object have an instance. Instance of a particular object is created at runtime. Values defined for a particular object define its State. Instance of an object explains the relation ship between different elements.

8 ) Explain about inheritance?
Inheritance revolves around the concept of inheriting knowledge and class attributes from the parent class. In general sense a sub class tries to acquire characteristics from a parent class and they can also have their own characteristics. Inheritance forms an important concept in object oriented programming.

9) Explain about multiple inheritance?
Inheritance involves inheriting characteristics from its parents also they can have their own characteristics. In multiple inheritance a class can have characteristics from multiple parents or classes. A sub class can have characteristics from multiple parents and still can have its own characteristics.

10) Explain about encapsulation?
Encapsulation passes the message without revealing the exact functional details of the class. It allows only the relevant information to the user without revealing the functional mechanism through which a particular class had functioned.

11) Explain about abstraction?
Abstraction simplifies a complex problem to a simpler problem by specifying and modeling the class to the relevant problem scenario. It simplifies the problem by giving the class its specific class of inheritance. Composition also helps in solving the problem to an extent.

12) Explain the mechanism of composition?
Composition helps to simplify a complex problem into an easier problem. It makes different classes and objects to interact with each other thus making the problem to be solved automatically. It interacts with the problem by making different classes and objects to send a message to each other.

13) Explain about polymorphism?
Polymorphism helps a sub class to behave like a parent class. When an object belonging to different data types respond to methods which have a same name, the only condition being that those methods should perform different function.

14) Explain about overriding polymorphism?
Overriding polymorphism is known to occur when a data type can perform different functions. For example an addition operator can perform different functions such as addition, float addition etc. Overriding polymorphism is generally used in complex projects where the use of a parameter is more.

15) Explain about object oriented databases?
Object oriented databases are very popular such as relational database management systems. Object oriented databases systems use specific structure through which they extract data and they combine the data for a specific output. These DBMS use object oriented languages to make the process easier.

16) Explain about parametric polymorphism?
Parametric polymorphism is supported by many object oriented languages and they are very important for object oriented techniques. In parametric polymorphism code is written without any specification for the type of data present. Hence it can be used any number of times.

17) What are all the languages which support OOP?
There are several programming languages which are implementing OOP because of its close proximity to solve real life problems. Languages such as Python, Ruby, Ruby on rails, Perl, PHP, Coldfusion, etc use OOP. Still many languages prefer to use DOM based languages due to the ease in coding.

Wednesday, November 4, 2015

Rails Models

Rails Models

  Generating models

$ rails g model User

  Associations

belongs_to
has_one
has_many
has_many :through
has_one :through
has_and_belongs_to_many

belongs_to :author,
  class_name: 'User',
  dependent: :destroy  // delete this

  Has many

has_many :comments, :order => "posted_on"
has_many :comments, :include => :author
has_many :people, :class_name => "Person", :conditions => "deleted = 0", :order => "name"
has_many :tracks, :order => "position", :dependent => :destroy
has_many :comments, :dependent => :nullify
has_many :tags, :as => :taggable
has_many :reports, :readonly => true
has_many :subscribers, :through => :subscriptions, :source => :user
has_many :subscribers, :class_name => "Person", :finder_sql =>
    'SELECT DISTINCT people.* ' +
    'FROM people p, post_subscriptions ps ' +
    'WHERE ps.post_id = #{id} AND ps.person_id = p.id ' +
    'ORDER BY p.first_name'

  Many-to-many

If you have a join model:
class Programmer < ActiveRecord::Base
  has_many :assignments
  has_many :projects, :through => :assignments
end

class Project < ActiveRecord::Base
  has_many :assignments
  has_many :programmers, :through => :assignments
end

class Assignment
  belongs_to :project
  belongs_to :programmer
end
Or HABTM:
has_and_belongs_to_many :projects
has_and_belongs_to_many :projects, :include => [ :milestones, :manager ]
has_and_belongs_to_many :nations, :class_name => "Country"
has_and_belongs_to_many :categories, :join_table => "prods_cats"
has_and_belongs_to_many :categories, :readonly => true
has_and_belongs_to_many :active_projects, :join_table => 'developers_projects', :delete_sql =>
"DELETE FROM developers_projects WHERE active=1 AND developer_id = #{id} AND project_id = #{record.id}"

  Polymorphic associations

class Post
  has_many :attachments, :as => :parent
end

class Image
  belongs_to :parent, :polymorphic => true
end
And in migrations:
create_table :images do |t|
  t.references :post, :polymorphic => true
end

  Migrations

  Run migrations

$ rake db:migrate

  Migrations

create_table :users do |t|
  t.string :name
  t.text   :description

  t.primary_key :id
  t.string
  t.text
  t.integer
  t.float
  t.decimal
  t.datetime
  t.timestamp
  t.time
  t.date
  t.binary
  t.boolean
end

options:
  :null (boolean)
  :limit (integer)
  :default
  :precision (integer)
  :scale (integer)

  Tasks

create_table
change_table
drop_table
add_column
change_column
rename_column
remove_column
add_index
remove_index

  Associations

t.references :category   # kinda same as t.integer :category_id

# Can have different types
t.references :category, polymorphic: true

  Add/remove columns

$ rails generate migration RemovePartNumberFromProducts part_number:string

class RemovePartNumberFromProducts < ActiveRecord::Migration
  def up
    remove_column :products, :part_number
  end

  def down
    add_column :products, :part_number, :string
  end
end

  Validation

  Validate checkboxes

class Person < ActiveRecord::Base
  validates :terms_of_service, :acceptance => true
end

  Validate associated records

class Library < ActiveRecord::Base
  has_many :books
  validates_associated :books
end

  Confirmations (like passwords)

class Person < ActiveRecord::Base
  validates :email, :confirmation => true
end

  Validate format

class Product < ActiveRecord::Base
  validates :legacy_code, :format => { :with => /\A[a-zA-Z]+\z/,
    :message => "Only letters allowed" }
end

  Validate length

class Person < ActiveRecord::Base
  validates :name, :length => { :minimum => 2 }
  validates :bio, :length => { :maximum => 500 }
  validates :password, :length => { :in => 6..20 }
  validates :registration_number, :length => { :is => 6 }

  validates :content, :length => {
    :minimum   => 300,
    :maximum   => 400,
    :tokenizer => lambda { |str| str.scan(/\w+/) },
    :too_short => "must have at least %{count} words",
    :too_long  => "must have at most %{count} words"
  }
end

  Numeric

class Player < ActiveRecord::Base
  validates :points, :numericality => true
  validates :games_played, :numericality => { :only_integer => true }
end

  Non-empty

class Person < ActiveRecord::Base
  validates :name, :login, :email, :presence => true
end

  custom

class Person < ActiveRecord::Base
  validate :foo_cant_be_nil

  def foo_cant_be_nil
    errors.add(:foo, 'cant be nil')  if foo.nil?
  end
end

  API

items = Model.find_by_email(email)
items = Model.where(first_name: "Harvey")

item = Model.find(id)

item.serialize_hash
item.new_record?

item.create     # Same an #new then #save
item.create!    # Same as above, but raises an Exception

item.save
item.save!      # Same as above, but raises an Exception

item.update
item.update_attributes
item.update_attributes!

item.valid?
item.invalid?

  Mass updates

# Updates person id 15
Person.update 15, name: "John", age: 24
Person.update [1,2], [{name: "John"}, {name: "foo"}]

  Joining

Student.joins(:schools).where(:schools => { :type => 'public' })
Student.joins(:schools).where('schools.type' => 'public' )

  Serialize

class User < ActiveRecord::Base
  serialize :preferences
end

user = User.create(:preferences => { "background" => "black", "display" => large })
You can also specify a class option as the second parameter that’ll raise an exception if a serialized object is retrieved as a descendant of a class not in the hierarchy.
class User < ActiveRecord::Base
  serialize :preferences, Hash
end

user = User.create(:preferences => %w( one two three ))
User.find(user.id).preferences    # raises SerializationTypeMismatch

  Overriding accessors

class Song < ActiveRecord::Base
  # Uses an integer of seconds to hold the length of the song

  def length=(minutes)
    write_attribute(:length, minutes.to_i * 60)
  end

  def length
    read_attribute(:length) / 60
  end
end

  Callbacks

after_create
after_initialize
after_validation
after_save
after_commit

FastAPI: The Modern Python Web Framework

  Introduction to FastAPI: The Modern Python Web Framework The world of web frameworks has always been competitive — from Django and Flask ...