Sei sulla pagina 1di 55

Type equation here.Cookies and Sessions are used to store information.

Cookies are only stored


on the client-side machine, while sessions get stored on the client as well as a server.

Session

A session creates a file in a temporary directory on the server where registered session variables
and their values are stored. This data will be available to all pages on the site during that visit.

A session ends when the user closes the browser or after leaving the site, the server will
terminate the session after a predetermined period of time, commonly 30 minutes duration.

Cookies

Cookies are text files stored on the client computer and they are kept of use tracking purpose.
Server script sends a set of cookies to the browser. For example name, age, or identification
number etc. The browser stores this information on a local machine for future use.

When next time browser sends any request to web server then it sends those cookies information
to the server and server uses that information to identify the user.

Session
1. Session can store any type of data because the value is of data type of “object”

2. These are stored at server side.

3. Sessions are secured because it is stored in binary format/encrypted form and gets decrypted at
server.

4. Session is independent for every client i.e. individual for every client.

5. There is no limitation on the size or number of sessions to be used in an application.

6. We cannot disable the sessions. Sessions can be used without cookies also.

7. The disadvantage of session is that it is a burden or an overhead on server.

8. Sessions are called as Non-Persistent cookies because its life time can be set manually

Cookies
1. Cookies can store only “string” datatype.

2. They are stored at client side.


3. Cookie is non-secure since stored in text-format at client side.

4. Cookies may or may not be individual for every client.

5. Size of cookie is limited to 40 and number of cookies to be used is restricted to 20.

6. Cookies can be disabled.

7. Since the value is in string format there is no security.

8.We have persistent and non-persistent cookies.

Cookie Session
Client-side file Server-side file
Carries risk (unless secured) Secure
Remembers info until deleted by you or
Remembers info until web site time-out
expiry
Usually contains more complex
Usually contains an id string
information
Specific identifier links to server Specific identifier links to user

Read more: The Difference Between a Cookie and a Session | Difference Between
http://www.differencebetween.net/technology/the-difference-between-a-cookie-and-a-
session/#ixzz5ySgmguKT

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Import Database Connection Class file


import code.DatabaseConnection;

// Servlet Name
@WebServlet("/InsertData")
public class InsertData extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
try {

// Initialize the database


Connection con = DatabaseConnection.initializeDatabase();

// Create a SQL query to insert data into demo table


// demo table consists of two columns, so two '?' is used
PreparedStatement st = con
.prepareStatement("insert into demo values(?, ?)");

// For the first parameter,


// get the data using request object
// sets the data to st pointer
st.setInt(1, Integer.valueOf(request.getParameter("id")));

// Same for second parameter


st.setString(2, request.getParameter("string"));

// Execute the insert command using executeUpdate()


// to make changes in database
st.executeUpdate();

// Close all the connections


st.close();
con.close();

// Get a writer pointer


// to display the succesful result
PrintWriter out = response.getWriter();
out.println("<html><body><b>Successfully Inserted"
+ "</b></body></html>");
}
catch (Exception e) {
e.printStackTrace();
}
}
}

There are mainly two types of servlets -

1. Generic Servlet - Generic servlet is protocol independent servlet. It implements the


Servlet and Servlet Config interface. It may be directly extended by the servlet. Writing a
servlet in in Generic Servlet is very easy. It has only init() and destroy() method of
Servlet Config interface in its life cycle. It also implements the log method of Servlet
Context interface.
2. Http Servlet - Http Servlet is HTTP (Hyper Text Transfer Protocol ) specific servlet. It
provides an abstract class Http Servlet for the developers for extend to create there own
HTTP specific servlets. The sub class of Http Servlet must overwrite at least one method
given below-
There is no need to overrride service() method. All the servlet either Generic Servlet or Http
Servlet passes there config parameter to the Servlet interface.

What is the difference between EJB and Java beans?


Java Beans :

- Java beans are reusable components that can be used for customized user objects.

- Java beans adhere to two methods known as setter and getter methods and one public constructor.

- For example: an employee object can be used to set (setter method) and get (getter method)
employee details which are a customized object.

- AWT and Swing components are based on java beans.

Enterprise Java Beans (EJB) :

- EJB are reusable components that are developed to comply with enterprise specification adhering to
setter and getter methods and one public constructor.

- These beans are running in an EJB container of J2EE architecture.

What is the difference between EJB and Java beans?

JavaBeans :

- JavaBeans may be visible or nonvisible at runtime.

- JavaBeans are intended to be local to a single process and are primarily intended to run on the client
side.

- Although one can develop server-side JavaBeans, it is far easier to develop them using the EJB
specification instead.

- JavaBean is a component technology to create generic java components that can be composed
together into applets and applications.

- JavaBeans have an external interface called the properties interface, which allows a builder tool to
interpret the functionality of the bean.

- JavaBeans may have BeanInfo classes,property editors or Customizers.

- JavaBeans have no types.

- No explicit support exists for transactions in JavaBeans.


- Component bridges are available for JavaBeans.

EJB :

- An EJB is a nonvisual, remote object.

- EJB's are remotely executable components or business objects that can be deployed only on the
server.

- Even though EJB is a component technology, it neither builds upon nor extends the original JavaBean
specification.

- EJBs have a deployment descriptor that describes its functionality to an external builder tool or IDE.

- EJB's have no concept of BeanInfo classes, property editors or customizers and provide no additional
information other than that described in the deployment descriptor.

- EJBs are of two types - session beans and entity beans.

- EJB's may be transactional and the EJB servers provide the transactional support.

- An EJB cannot be deployed as an ActiveX control because ActiveX controls are intended to run at the
desktop and EJB's are server side components. However CORBA-IIOP compatibility via the EJB-to-CORBA
mapping is defined by the OMG.

• Functions of DSS: • There are five functions of a DSS facilitating managerial decision making. They are
1. Model building 2. 'What if' analysis 3. Goal seeking 4. Risk analysis 5. Graphical analysis Model
building: • This allows decision makers to identify the most appropriate model for solving the problem
on hand. It takes into account input variables, interrelationships among the variables, problem
assumptions and constraints. • 'What-if' analysis : This is the process of assessing the impact of changes
to model variables, the values of the variables, or the interrelationships among variables. This helps
managers to be proactive, rather than reactive, in their decision making• Goal seeking : It is the process
of determining the input values required to achieve a certain goal. For example, house buyers determine
the monthly payment they can afford (say for example, Rs. 5,000) and calculate the number of such
payments required to pay the desired house • ) Risk analysis : It is a function of DSS that allows
managers to assess the risks associated with various alternatives. Decisions can be classified as low risk,
medium risk, and high risk. A DSS is particularly useful in medium risk and high risk environments•
Graphical analysis : This helps managers to quickly digest large volumes of data and visualize the impacts
of various courses of action. graphical analysis can be used in following situations: • Seeking a quick
summary of data • Detecting trends over time • Comparing points and patterns at different variables •
Forecasting activities • Seeking relatively simple impressions from a vast amount of information.
Definition - What does Data Modeling mean?

Data modeling is a representation of the data structures in a table for a company’s database and
is a very powerful expression of the company's business requirements. This data model is the
guide used by functional and technical analysts in the design and implementation of a database.

Data models are used for many purposes, from high-level conceptual models to physical data
models.

[Free eBook] Essential Guide to Machine Data: Network Machine Data | DOWNLOAD TODAY

Techopedia explains Data Modeling

Data modeling explores data-oriented structures and identifies entity types. This is unlike class
modeling, where classes are identified.

Three basic styles of data modeling are generally used in practice today.

 Conceptual Data Models: High-level, static business structures and concepts


 Logical Data Models (LDMs): Entity types, data attributes and relationships between entities
 Physical Data Models (PDMs): The internal schema database design

The main difference between logical and physical data model is that logical data model helps
to define the data elements and their relationships, while physical data model helps to
design the actual database based on the requirements gathered during the logical data

modelling.

1.Logical database modeling is mainly for gathering information about business needs and does not
involve designing a database; whereas physical database modeling is mainly required for actual
designing of the database.
2.Logical database modeling does not include indexes and constraints; the logical database model for an
application can be used across various database software and implementations; whereas physical
database modeling is software and hardware specific and has indexes and constraints.
3.Logical database modeling includes; ERD, business process diagrams, and user feedback
documentation; whereas physical database modeling includes; server model diagram, database design
documentation, and user feedback documentation.
A systems analyst is an IT professional who works on a high level in an organization to ensure
that systems, infrastructures and computer systems are functioning as effectively and efficiently
as possible. System analysts carry the responsibilities of researching problems, finding solutions,
recommending courses of actions and coordinating with stakeholders in order to meet specified
requirements. They study the current system, procedures and business processes of a company
and create action plans based on the requirements set.

Systems analysts need to be familiar with different operating systems, hardware configurations,
programming languages, and software and hardware platforms. They can be involved starting
from the analysis phase of the project until the post deployment assessment review.

INTERPERSONAL SKILLS

Systems analyst works extensively with staff in key positions in an organization. So,
interpersonal skills are necessary for success of him/her. These skills can be classified as:

Communication Skills

A Systems analyst should be able to communicate clearly and effectively with others. He must
establish a good relationship with clients early in the project and maintain it throughout the
project. Communication takes many forms from written to verbal to visual. The analyst must be
able to master as many forms of communication as possible.

Interpersonal communication subjects are:

 Business speaking
 Business writing
 Interviewing
 Listening
 Technical discussion
 Technical writing.
Working Alone as well as in a Team: As many people in the organization will depend on his
individual performance therefore a systems analyst must be able to organize and manage his own
schedule, commitments and deadlines. He must work with the team towards achieving project
goals. To work together effectively and to ensure the quality of the product, the team must
establish standards of cooperation and coordination that guide their work.

There are 12 characteristics of a high performance team that influence team work:

 Shared and elevated vision


 Sense of team identity: Result-driven structure
 Competent team members
 Commitment to the team
 Mutual trust
 Interdependency among team members
 Effective communication
 Sense of autonomy
 Sense of empowerment
 Small team size.

Facilitating Groups

While working in a Joint application development approach a system analyst require this skill. In
this approach there is group of members and systems analyst works with that group during
system development. Analysts use JAD sessions to gather systems requirements and to conduct
design reviews. Systems analyst can be asked to work as a facilitator. The facilitator must guide
the group without being a part of the group and must work to keep the effort on track by helping
the group by resolving the differences.

Facilitator's guidelines are as follows:

 Purpose should be made clear


 Make sure that the group understands what is expected of them and of you
 Use physical movement to focus on yourself or on the group
 Reward group member participation with thanks and respect
 Ask questions instead of making statement
 Wait patiently for answers
 Be a good listener
 Encourage group members to feel ownership of the group's goal and of their attempts to
reach those goals.

Managing Expectations

System development is a change process, and members of any organization greet any
organizational change with anticipation and uncertainty. Organizational members will have
certain ideas about what new information system will be able to do for them. Ginsberg found that
successfully managing user expectations is related to successful systems implementation. The
systems analyst needs to understand the technology. S/he must understand the work flows that
the technology will support and how the new system will affect them. The important ability of
systems analyst is to communicate a realistic picture of the new system and what it will do for
users and managers. Managing expectations begins with the development of the business case for
the system and extends all the way through training people to use the finished system.

The following requirements must be fulfilled by the system analyst:

 Working knowledge of information technology


 Computer programming experience and expertise
 General business knowledge
 Problem solving skills
 Communication skills
 Interpersonal skills
 Flexibility and adaptability
 Thorough knowledge of analysis and design methodologies.

Skill # 1 – Analytical

At the beginning of a project, a systems analyst has to understand the requirements of the client
and study the various ways in which the requirements can be met. Once the various ways are
found out, the onus is on the systems analyst to thoroughly analyze the pros and cons of every
solution before deciding on a best feasible solution. The system analyst also has to analyze the
ways and means of applying a solution which has been zeroed upon.

Skill # 2 – Efficient Planning and Execution

A systems analyst is expected to have a keen eye for detail and has to plan the various stages in
which the project has to be executed. He/she has to come up with a skeleton plan of how the
product would look like and has to chalk out the deliverables. After defining the plan, he/she has
to ensure that all the details of the plan are adhered to and the different stages are executed
perfectly.

You may be interested: Top Ten Responsibilities of an ERP project manager in IT industry

Skill # 3 – Technical Knowledge

A systems analyst must have ample technical skills because they have to help the technical team
design a product which is to suit the customer’s needs. He/She must have a working knowledge
of the prevalent operating systems, programming languages and hardware platforms. A systems
analyst is expected to help in coding and debugging of a customized product. Further, he/she
should also be able to tweak up the initial design based on the customer’s feedback. The systems
analyst is expected to constantly help in redesigning till the end product has been delivered to the
client and has got the approval.

Skill # 4 – Man Management

Any systems analyst has to have great interpersonal skills and the ability to manage people.
He/she has to coordinate with the different technical teams and get the product customized as per
requirement delivered within the deadline agreed upon. The systems analyst should ensure that
no feathers have been ruffled and the whole team functions smoothly.

Overall a systems analyst has to multi- task effectively and helps the company deliver high class
products, thereby increasing their client base and profits.

ISSUE IN SYSTEM ANALYSIS

1. Conflicting Requirements: No matter the scope and context of your project or business
analysis exercise, you are certain to have more than 3 stakeholders or stakeholder groups
whose requirements and needs must be managed (starting right from elicitation). And
because these stakeholders or stakeholder groups have different needs and represent
different interests within the business, there are always issues aligning their requirements.
From my experience, this is the topmost challenge I have faced in managing
requirements. I recall having this major challenge on one of the projects I managed for a
top stockbroking firm in Africa. The project involved deploying a self-service, interactive
and transactional trading portal for the firm’s clients where the clients can trade on stocks
and shares directly from the portal without recourse to the company. One of the major
requirements on the project was “User Idle Timeout (a maximum time for the user to stay
logged in and not perform any activity on the portal). The business wanted to have the
clients perpetually logged on (set at infinity), except if they decide to log out solely
because the clients need to do some research before taking a position on a particular
stock, while the IT Security Executive, another stakeholder on the project, recommended
an idle timeout of 2 minutes. This conflicting requirement took us about 4 additional days
of back and forth before agreeing to a 5-minute idle timeout. This happens on almost
every project I have handled until I started using Facilitated Workshop technique
for Requirement Elicitation.
2. Customers don’t know what they want: Let’s be factual, more often than not,
customers don’t know exactly what they want. This is a huge challenge for the Business
Analyst and Project Manager during Requirement Gathering. How do you elicit, analyse
or document what is not knows? This challenge often leads to the technique called
IKIWISI (I’ll know It When I See It). But a downside of IKIWISI is that it can easily
lead to Scope Creep, which is an ingredient to Project Failure in itself.
3. Unavailability of Stakeholders: Irrespective of the technique you have chosen to use in
your requirement elicitation, be it interview, observation/shadowing, focus group,
requirement workshop, prototyping, name it. You need to meet with Stakeholders. These
are the guys with needs and expectations for the change or project you are working on,
but scheduling a meeting or session with these stakeholders has always been a challenge.
They are just not available, either due to their busy schedule or they are not interested in
the CHANGE or project (hopefully, this is not the case). I had a key stakeholder, a
representative from the user community on one project I worked on in the past who took
over 2 weeks to track and get him to sit with me for 30 minutes to elicit their
requirements. Unfortunately, no one could take his place. Imagine 2 weeks added to a 3
months change project.

Advertisement

4. Changing Priorities: For a lack of better word, I have used the word “Changing
Priorities”, but more bluntly said, it would be “Customers keep changing their minds”.
This is a VERY common, rampant, and tiring challenge I and couple of other
practitioners have experienced on BA and PM engagements. I can authoritatively say I
have experienced this challenge in 7 out of every 10 projects I worked on in the past. The
customer comes with one set of requirements, the next hour, they are changing the
requirements, irrespective of whether the Business Requirement Document has been
signed-off. A typical example of this challenge was while working on an initiative for a
stock broking firm to develop a self-service trading portal for their investors, same
project I referenced above. During requirement elicitation, the business owner was very
emphatic about online chat integration as a Must-Have requirement/feature. During
implementation, the stakeholder called a meeting and decided to expunge that
requirement, and replace with google map integration in the contact us page. The next
review process, she was thinking and having another idea, hence a completely new
requirement, different from what was elicited earlier. I find this challenge quite common
when doing Requirement Management.
5. Unsupportive Stakeholders: Well, maybe this is not as rampant on projects as the other
four, but I have faced lots of challenges on requirement management when the
stakeholders do not buy into the change. This could be as a result of a segregation
between senior management and the user community or sheer lack of enthusiasm towards
the change being implemented. A while ago, I was working on an automation initiative as
part of a firm’s digital transformation program, and part of the process included
understanding the current (manual) process (AS-IS), identifying bottlenecks and
improvements, to be able to develop the future (TO BE) process. Unfortunately, the key
stakeholders felt this automation would render them redundant and threaten their jobs.
So, we faced a lot of restriction and challenges while meeting with them to elicit
requirements of the current process or identify improvement opportunities.

Whilst I believe some of the highlighted challenges can be addressed by implementing the Agile
method, there are still some residual challenges.

So, I would like to end by asking you to confirm if you have experienced any of those challenges
identified above and provide comments on those other challenges you have encountered and
possible solutions.
here are some of the problems faced by business analysts during the requirements
elicitation/gathering activities:

Contradicting/Conflicting Requirements - These are requirements received from different


stakeholders or from same stakeholder at different times and which cannot all be met at the same
time because their are in conflict. What the BA can do: get all stakeholders in the same room (if
possible), document and publish stakeholder requirements or meeting notes while they are fresh.

Communication Problems - This is a broad category of requirements issues and includes:


miscommunication, language barriers, wrong assumptions, unclearly defined vocabulary or
domain model, variance in vertical domain knowledge, using only one-way communication
channels (over the wall requirements), notation differences (lack of standards), etc. What the BA
can do: continuously improve communication skills, document info gathered and publish for
review/feedback, verify assumptions, create a glossary of terms, use multiple subject matter
experts, etc.

Undocumented Processes - This is the reality in most organizations. The business runs with
"word of mouth" or poorly documented processes and procedures. In these situations, to the
high-level executive it may look like everybody is doing the work the same way when the actual
details/steps of the process vary from end-user to end-user. The business analyst is often forced
to reverse engineer the business processes every time a new projects is started. What the BA can
do: Document existing business processes and the differences among the various users. Present
the documented processes to the stakeholders/high-level executives. If possible and within the
scope of duty, create and maintain an up-to-date library of existing business processes/operating
procedures.

Lack of access to end-users - On many projects the stakeholders and IT management "think"
they understand the requirements and what happens in the business and do not enable or allow
the business analyst to have direct access to the end-users. What the BA can do: Present your
case to the project sponsor as to why it is key to observe the users at work and find out how each
activity is actually performed and the types of problems faced by the user in their day-to-day
work.

Instability of UI Preferences - Stakeholders and end-users who are new to the requirement
elicitation process or who are faced with new or unprecedented concepts or processes tend to
have a hard time identifying (and feeling good about) their preferences and, therefore, they tend
to keep changing their minds. What the BA can do: use prototypes and other visual tools such as
diagrams to gather, document, and verify requirements.

Abundance of Choice - When stakeholders or end-users are presented with too many choices
they generally have a harder time deciding the option to select. When they do make a decision
they are less satisfied than if those who have to pick from a much smaller list of options. What
the BA can do: provide stakeholders and decision makers with more than option (when possible),
however do not give them more than 3 options to choose from.
Stakeholder Design - This is the case when the stakeholders or end-user have the urge to design
the system (how the system should work) rather than providing the requirements (what the
system should do). The problem with this pattern is that the BA is no longer able to distinguish
between requirements and design decisions. What the BA can do: ask the stakeholders/users what
the system should do and when you get the answer keep asking "Why?". Eventually you should
be able to get to the actual problems faced by the user and you'll be able to understand the "real"
requirements.

Bad Requirements - Requirements are considered "bad" if they are: ambiguous, incomplete, not
verifiable, etc. When stakeholders provide and analysts document bad requirements, they result
in systems which are not completed or not used. What the BA can do: develop a checklist of
characteristics and tests which you can check for each requirement to ensure all the requirements
send for sign-off are all good to go.

These are just some of the problems faced by requirements analysts during the elicitation
process. There certainly are many more.

Risk management is the process of identifying, assessing and controlling threats to an organization's
capital and earnings. These threats, or risks, could stem from a wide variety of sources, including
financial uncertainty, legal liabilities, strategic management errors, accidents and natural disasters. IT
security threats and data-related risks, and the risk management strategies to alleviate them, have
become a top priority for digitized companies. As a result, a risk management plan increasingly includes
companies' processes for identifying and controlling threats to its digital assets, including proprietary
corporate data, a customer's personally identifiable information and intellectual property.

Risk management strategies and processes

All risk management plans follow the same steps that combine to make up the overall risk
management process:

 Risk identification. The company identifies and defines potential risks that may negatively
influence a specific company process or project.
 Risk analysis. Once specific types of risk are identified, the company then determines the odds
of it occurring, as well as its consequences. The goal of the analysis is to further understand each
specific instance of risk, and how it could influence the company's projects and objectives.
 Risk assessment and evaluation. The risk is then further evaluated after determining the risk's
overall likelihood of occurrence combined with its overall consequence. The company can then
make decisions on whether the risk is acceptable and whether the company is willing to take it
on based on its risk appetite.
 Risk mitigation. During this step, companies assess their highest-ranked risks and develop a plan
to alleviate them using specific risk controls. These plans include risk mitigation processes, risk
prevention tactics and contingency plans in the event the risk comes to fruition.
 Risk monitoring. Part of the mitigation plan includes following up on both the risks and the
overall plan to continuously monitor and track new and existing risks. The overall risk
management process should also be reviewed and updated accordingly.
Transformation
means changing some graphics into something else by applying rules. We can have various types
of transformations such as translation, scaling up or down, rotation, shearing, etc. When a
transformation takes place on a 2D plane, it is called 2D transformation.

Transformations play an important role in computer graphics to reposition the graphics on the
screen and change their size or orientation.

Homogenous Coordinates

To perform a sequence of transformation such as translation followed by rotation and scaling, we


need to follow a sequential process −

 Translate the coordinates,


 Rotate the translated coordinates, and then
 Scale the rotated coordinates to complete the composite transformation.

To shorten this process, we have to use 3×3 transformation matrix instead of 2×2 transformation
matrix. To convert a 2×2 matrix to 3×3 matrix, we have to add an extra dummy coordinate W.

In this way, we can represent the point by 3 numbers instead of 2 numbers, which is called
Homogenous Coordinate system. In this system, we can represent all the transformation
equations in matrix multiplication. Any Cartesian point P(X, Y) can be converted to homogenous
coordinates by P’ (Xh, Yh, h).

Translation

A translation moves an object to a different position on the screen. You can translate a point in
2D by adding translation coordinate (tx, ty) to the original coordinate (X, Y) to get the new
coordinate (X’, Y’).
From the above figure, you can write that −

X’ = X + tx

Y’ = Y + ty

The pair (tx, ty) is called the translation vector or shift vector. The above equations can also be
represented using the column vectors.

$P = \frac{[X]}{[Y]}$ p' = $\frac{[X']}{[Y']}$T = $\frac{[t_{x}]}{[t_{y}]}$

We can write it as −

P’ = P + T

Rotation

In rotation, we rotate the object at particular angle θ (theta) from its origin. From the following
figure, we can see that the point P(X, Y) is located at angle φ from the horizontal X coordinate
with distance r from the origin.

Let us suppose you want to rotate it at the angle θ. After rotating it to a new location, you will get
a new point P’ (X’, Y’).
Using standard trigonometric the original coordinate of point P(X, Y) can be represented as −

$X = r \, cos \, \phi ...... (1)$

$Y = r \, sin \, \phi ...... (2)$

Same way we can represent the point P’ (X’, Y’) as −

${x}'= r \: cos \: \left ( \phi \: + \: \theta \right ) = r\: cos \: \phi \: cos \: \theta \: − \: r \: sin \: \phi
\: sin \: \theta ....... (3)$

${y}'= r \: sin \: \left ( \phi \: + \: \theta \right ) = r\: cos \: \phi \: sin \: \theta \: + \: r \: sin \: \phi \:
cos \: \theta ....... (4)$

Substituting equation (1) & (2) in (3) & (4) respectively, we will get

${x}'= x \: cos \: \theta − \: y \: sin \: \theta $

${y}'= x \: sin \: \theta + \: y \: cos \: \theta $

Representing the above equation in matrix form,

$$[X' Y'] = [X Y] \begin{bmatrix} cos\theta & sin\theta \\ −sin\theta & cos\theta


\end{bmatrix}OR $$

P’ = P . R
Where R is the rotation matrix

$$R = \begin{bmatrix} cos\theta & sin\theta \\ −sin\theta & cos\theta \end{bmatrix}$$

The rotation angle can be positive and negative.

For positive rotation angle, we can use the above rotation matrix. However, for negative angle
rotation, the matrix will change as shown below −

$$R = \begin{bmatrix} cos(−\theta) & sin(−\theta) \\ -sin(−\theta) & cos(−\theta)


\end{bmatrix}$$

$$=\begin{bmatrix} cos\theta & −sin\theta \\ sin\theta & cos\theta \end{bmatrix} \left (\because
cos(−\theta ) = cos \theta \; and\; sin(−\theta ) = −sin \theta \right )$$

Scaling

To change the size of an object, scaling transformation is used. In the scaling process, you either
expand or compress the dimensions of the object. Scaling can be achieved by multiplying the
original coordinates of the object with the scaling factor to get the desired result.

Let us assume that the original coordinates are (X, Y), the scaling factors are (SX, SY), and the
produced coordinates are (X’, Y’). This can be mathematically represented as shown below −

X' = X . SX and Y' = Y . SY

The scaling factor SX, SY scales the object in X and Y direction respectively. The above
equations can also be represented in matrix form as below −

$$\binom{X'}{Y'} = \binom{X}{Y} \begin{bmatrix} S_{x} & 0\\ 0 & S_{y} \end{bmatrix}$$

OR

P’ = P . S

Where S is the scaling matrix. The scaling process is shown in the following figure.
If we provide values less than 1 to the scaling factor S, then we can reduce the size of the object.
If we provide values greater than 1, then we can increase the size of the object.

Reflection

Reflection is the mirror image of original object. In other words, we can say that it is a rotation
operation with 180°. In reflection transformation, the size of the object does not change.

The following figures show reflections with respect to X and Y axes, and about the origin
respectively.
Shear

A transformation that slants the shape of an object is called the shear transformation. There are
two shear transformations X-Shear and Y-Shear. One shifts X coordinates values and other
shifts Y coordinate values. However; in both the cases only one coordinate changes its
coordinates and other preserves its values. Shearing is also termed as Skewing.

X-Shear

The X-Shear preserves the Y coordinate and changes are made to X coordinates, which causes
the vertical lines to tilt right or left as shown in below figure.
The transformation matrix for X-Shear can be represented as −

$$X_{sh} = \begin{bmatrix} 1& shx& 0\\ 0& 1& 0\\ 0& 0& 1 \end{bmatrix}$$

Y' = Y + Shy . X

X’ = X

Y-Shear

The Y-Shear preserves the X coordinates and changes the Y coordinates which causes the
horizontal lines to transform into lines which slopes up or down as shown in the following
figure.
The Y-Shear can be represented in matrix from as −

$$Y_{sh} \begin{bmatrix} 1& 0& 0\\ shy& 1& 0\\ 0& 0& 1 \end{bmatrix}$$

X’ = X + Shx . Y

Y’ = Y

Comparion of perspective and parallel

 Perspective projection is located as a finite point whereas Parallel projection is located at


infinite points.
 Perspective projection form a realistic picture of object whereas Parallel projection do not
form realistic view of object.
 Perspective projection can not preserve the relative proportion of an object whereas
Parallel projection can preserve the relative proportion of an object.
 Projector in perspective projection is not parallel whereas Projector in parallel projection
is parallel.
 Perspective projection represents the object in three dimensional way whereas Parallel
projection projection represents the object in a different way like telescope.
 The lines of perspective projection are not parallel whereas The lines of parallel
projection are parallel.
 Perspective projection can not give the accurate view of object whereas Parallel
projection projection can give the accurate view of object.

1.3.4 Definition of Bézier curve and its properties


A Bézier curve is a parametric curve that uses the Bernstein polynomials as a basis. A Bézier curve of

degree (order ) is represented by

(1.40)

The coefficients, , are the control points or Bézier points and together with the basis function

determine the shape of the curve. Lines drawn between consecutive control points of the
curve form the control polygon. A cubic Bézier curve together with its control polygon is shown in
Fig. 1.3 (a). Bézier curves have the following properties:
 Geometry invariance property: Partition of unity property of the Bernstein polynomial assures
the invariance of the shape of the Bézier curve under translation and rotation of its control
points.
 End points geometric property:
o The first and last control points are the endpoints of the curve. In other words,

and .
o The curve is tangent to the control polygon at the endpoints. This can be easily observed
by taking the first derivative of a Bézier curve

(1.41)

In particular we have and . Equation

(1.41) can be simplified by setting :

(1.42)

o
The first derivative of a Bézier curve, which is called hodograph, is another Bézier curve

whose degree is lower than the original curve by one and has control points ,

. Hodographs are useful in the study of intersection (see Sect.


5.6.2) and other interrogation problems such as singularities and inflection points.

 Convex hull property: A domain is convex if for any two points and in the domain,

the segment is entirely contained in the domain [335]. It can be shown that the
intersection of convex domains is a convex domain. The convex hull of a set of points is the
boundary of the smallest convex domain containing . There are several efficient algorithms
for computing the convex hull of a set of points [335,66,292].

Using the above definitions and facts, the convex hull of a Bézier curve is the boundary
of the intersection of all the convex sets containing all vertices or the intersection of the
half spaces generated by taking three vertices at a time to construct a plane and having all
other vertices on one side. The convex hull can also be conceptualized at the shape of a
rubber band in 2-D or a sheet in 3-D stretched taut over the polygon vertices [75]. The
entire curve is contained within the convex hull of the control points as shown in Fig. 1.3
(b). The convex hull property is useful in intersection problems (see Fig. 1.4), in
detection of absence of interference and in providing estimates of the position of the
curve through simple and efficiently computable bounds.

 Variation diminishing property:


o 2-D: The number of intersections of a straight line with a planar Bézier curve is no
greater than the number of intersections of the line with the control polygon. A line
intersecting the convex hull of a planar Bézier curve may intersect the curve
transversally, be tangent to the curve, or not intersect the curve at all. It may not,
however, intersect the curve more times than it intersects the control polygon. This
property is illustrated in Fig. 1.5.
o 3-D: The same relation holds true for a plane with a space Bézier curve.

From this property, we can roughly say that a Bézier curve oscillates less than its control
polygon, or in other words, the control polygon's segments exaggerate the oscillation of the
curve. This property is important in intersection algorithms and in detecting the fairness of
Bézier curves.

 Symmetry property: If we renumber the control points as , or in other words

relabel from to and using the symmetry property of the


Bernstein polynomial (1.20) the following identity holds:

(1.43)


Figure 1.3: A cubic Bézier curve: (a) with control polygon, (b) with convex hull

Figure 1.4: Comparison of convex hulls of Bézier curves as means of detecting intersection
Figure 1.5: Variation diminishing property of a cubic Bézier curve

PART-I: MCS-051 (Advanced Internet Technologies)


Question 1:
Develop a web page using servlet to display your profile. Make necessary assumptions.
Ans. In this page, we have getting input from the user using text fields and combobox. The
information
entered by the user is forwarded to Register servlet, which is responsible to store the data into the
database.
<html>
<body>
<form action="servlet/Register" method="post">
Name:<input type="text" name="userName"/><br/><br/>
Password:<input type="password" name="userPass"/><br/><br/>
Email Id:<input type="text" name="userEmail"/><br/><br/>
Country:
<select name="userCountry">
<option>India</option>
<option>Pakistan</option>
<option>other</option>
</select>
<br/><br/>
<input type="submit" value="register"/>
</form>
</body>
</html>
Register.java
This servlet class receives all the data entered by user and stores it into the database. Here, we
are
performing the database logic. But you may separate it, which will be better for the web
application.
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class Register extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
String e=request.getParameter("userEmail");
String c=request.getParameter("userCountry");
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement(
"insert into registeruser values(?,?,?,?)");
ps.setString(1,n);
ps.setString(2,p);
ps.setString(3,e);
ps.setString(4,c);
int i=ps.executeUpdate();
if(i>0)
out.print("You are successfully registered...");
}catch (Exception e2) {System.out.println(e2);}
out.close();
}
}
web.xml file
The is the configuration file, providing information about the servlet.
<web-app>
<servlet>
<servlet-name>Register</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/servlet/Register</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>register.html</welcome-file>
</welcome-file-list>
</web-app>
Question 2:
Write a JSP program for your Study Centre , which displays a web page containing two web
links,
one for Counselling Schedule and other for Examination Schedule. On clicking Counselling
Schedule link, it goes to a JSP page which display course wise counselling schedule with name
of
counsellors, class room/ laboratory. On clicking the Examination Schedule link JSP page with
schedule of Viva- Voce schedule for assignments of courses of MCA 5
th
Semester is opened.
Ans.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Main</title>
</head>
<body>
<br><br><br>
<center> <a href="detailofstudycenter.jsp"><h2>View Details of study
center</h2></a></center> <br>
<center> <a href="faqonpracticls.jsp"><h2>View Faq on MCA
Practils</h2></a></center>
</body>
</html>
detailofstudycenter.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Student Centre Detail Page:</title>
</head>
<body>
<table align="center" border="1">
<tr>
<td>Study Centre Name :</td>
<td> Karrox IGNOU Study Centre </td>
</tr>
<tr> <td>Address :</td>
<td> karrox technologies Ltd, Opp Shreyas Cinema, Ghatkopar(w),Mumbai-86
</td>
</tr>
<tr>
<td>Phone Number :</td>
<td> 022-25699002 </td>
</tr>
<tr>
<td>Email :</td>
<td> ignou@karrox.com </td>
</tr>
<tr>
<td>Program Coordinator :</td>
<td> Mudadi Sanyasi J</td> </tr>
<tr> <td> counselling schedule for MCA :</td>
<td><a href =”schedule.doc”> click here</a></td> </tr>
</table>
</body>
</html>
faqonpracticls.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>FAQs</title>
</head>
<body><br><br><br>
<center><h2><u> FAQs on Practicls </u></h2></center><br>

<p>

Q1. If attendance is less than 75% in practical session of a course due to some

reasons can student get any help/consideration?

<br><br>

Ans : The student will NOT be allowed to appear in Term-End Practical Exam.

</p> <p>

Q2. If Attendance is less than 75% then how can a student give Term-End Practical

Exam?

<br><br>

Ans : The student will NOT be allowed to appear in Term-End Practical Exam. </p>

<p>

Q3. Can the MCA students appear in the Term-End Practical Exam without filling

the Term-End Exam Form ?

<br><br>

Ans : No. </p> <p>Q4. What should we do to give my Backlog Term End Practical

Exam ? <br><br>

Ans : Collect attendance proof from the study Centre & then submit to IGNOU
Regional Centre before your Term End Examination (Theory).

</p>

</body>

</html>

Question 3:

Write a program using JDBC and JSP to display the current balance from a saving bank account.

The program should take account number or registered mobile number as input.

Ans.

Program for Customer Login Page

//signin.html

<html>

<title><signin></title>

<form method="Get" action="Check"> <FONT SIZE="20" FACE="courier" COLOR=blue> <body

bgcolor="#E7E7EF"><br><br><br>

<center><table>
<tr><td><h3>Account No</h3></td><td ><input type=text name="user"></td></tr>
<tr><td><h3>Password</h3></td><td><input type=password name="pass"></td></tr> <tr><th
COLSPAN="2"><input type=submit value="SUBMIT" name="SUBMIT"></th></tr>
</table>
</center>
</body>
</html>
//Check.java
import javax.servlet.*;
import java.io.*;
import java.sql.*;
import javax.servlet.http.*;
public class Check extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response) throws
ServletException, java.io.IOException {
PrintWriter out=response.getWriter();
String acno=request.getParameter("user");
System.out.println(acno);
String pass=request.getParameter("pass");
HttpSession session=request.getSession();
session.setAttribute("sess",acno);
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:ques");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from bank where pass='"+pass+"' and Acno="+acno );
if(rs.next()) {
String s1=rs.getString(1);
out.println("name"+s1);
RequestDispatcher rd=request.getRequestDispatcher("/user.jsp");
rd.forward(request,response);
} else {
RequestDispatcher
rd=request.getRequestDispatcher("signin.html");
rd.forward(request,response);
}
} catch(Exception e){
}
}
}
User operation page //user.jsp
<html>
<body bgcolor="#ccccdd">
<% String acno=(String)session.getAttribute("sess");
System.out.println(acno); %>
<center>
<a href="debit.html">Debit the Amount</a><br> <a href="credit.html">Credit the
Amount</a><br>
<a href="month.jsp">Monthly Record</a><br>
</center>
</body>
</html>
Credit Design Page
//credit.html
<html>
<Head>
<center>Welcome to the credit page</center></head> <form action="credit.jsp">
<body bgcolor="#ccccdd"><center><table>
<tr><td>Enter the Account NO</td><td><input type="text" name="ac"></td></tr>
<tr><td>Enter the Amount</td><td><input type="text" name="amnt"></td></tr>
<tr><td><input type="submit" value="credit"></tr></td></table></center>
</body>
</form>
</html>
Debit Design Page
//debit.html
<html>
<Head>
<center> Welcome to the Debit page</center>
</head>
<form action="debit.jsp">
<body bgcolor="#ccccdd"><center><table>
<tr><td>Enter the Account NO</td><td><input type="text" name="ac"></td></tr>
<tr><td>Enter the Amount</td><td><input type="text" name="amnt"></td></tr>
<tr><td><input type="submit" value="Debit"></td></tr></table></center>
</body>
</form>
</html>
Program to Credit the Amount and Display the balance
//credit.jsp
<html>
<%@ page import="java.sql.*"%>
<%@ page import="java.util.*"%>
<%
String amount=request.getParameter("amnt");
int iamount=Integer.parseInt(amount);
String acnt=request.getParameter("ac");
int acno=Integer.parseInt(acnt);
String type="Credit";
Calendar calendar = new GregorianCalendar();
System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
System.out.println("MONTH: " + calendar.get(Calendar.MONTH));
System.out.println("DATE: " + calendar.get(Calendar.DATE));
String dor
=String.valueOf(calendar.get(Calendar.DATE))+"/"+String.valueOf(calendar.get(Calendar.MO
NTH
))+"/"+String.valueOf(calendar.get(Calendar.YEAR));
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:ques");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from bank where Acno="+acno);
int totbal=0;
while(rs.next())
{
int s1=rs.getInt(5);
totbal=s1-iamount;
if(totbal<=0) { out.println("Your amount is credited you have to pay Rs"+totbal);
} else { out.println("Your amount is credited Your balance is"+totbal);
}
}
PreparedStatement pstmt = con.prepareStatement("update bank set balance=? where
Acno="+acno);
pstmt.setInt(1,totbal);
int i = pstmt.executeUpdate();
PreparedStatement pstmt1 = con.prepareStatement("insert into month values(?,?,?,?,?)");
pstmt1.setString(1,dor);
pstmt1.setInt(2,totbal);
pstmt1.setInt(3,acno); pstmt1.setString(4,type);
pstmt1.setInt(5,iamount);
int i1 = pstmt1.executeUpdate();
}
catch(Exception e){
}
%>
</html>
Program to Credit the Amount and Display the balance
//debit.jsp
<html>
<body>
<%@ page import="java.sql.*"%>
<%@ page import="java.util.*"%>
<%
String amount=request.getParameter("amnt");
int iamount=Integer.parseInt(amount);
String acnt=request.getParameter("ac");
int acno=Integer.parseInt(acnt);
String type="Debit";
Calendar calendar = new GregorianCalendar();
System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
System.out.println("MONTH: " + calendar.get(Calendar.MONTH));
System.out.println("DATE: " + calendar.get(Calendar.DATE));
String dor
=String.valueOf(calendar.get(Calendar.DATE))+"/"+String.valueOf(calendar.get(Calendar.MO
NTH
))+"/"+String.valueOf(calendar.get(Calendar.YEAR));
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:ques");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from bank where Acno="+acno);
int totbal=0;
while(rs.next())
{ int s1=rs.getInt(5);
if(s1>=500) { totbal=s1-iamount; out.println("Amount is Debited successfully");
out.println("Your balance is"+totbal);
}
else{
out.println("Your balance is less than 500,You can't debit the amount"); totbal=s1;
}
}
PreparedStatement pstmt = con.prepareStatement("update bank set balance=? where
Acno="+acno);
pstmt.setInt(1,totbal);
int i = pstmt.executeUpdate();
PreparedStatement pstmt1 = con.prepareStatement("insert into month values(?,?,?,?,?)");
pstmt1.setString(1,dor);
pstmt1.setInt(2,totbal);
pstmt1.setInt(3,acno);
pstmt1.setString(4,type);
pstmt1.setInt(5,iamount);
int i1 = pstmt1.executeUpdate();
}
catch(Exception e){
}
%>
</html>
Program to print the monthly Report
//month.jsp
<html>
<%@ page import="java.sql.*"%>
<%
String acno=(String)session.getAttribute("sess");
System.out.println(acno); int chk=Integer.parseInt(acno);
int l=0;
int rowcu=0;
int totalRecords=0;
ResultSetMetaData rsmt=null;
ResultSet datars=null;
try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cot=DriverManager.getConnection("jdbc:odbc:ques");
Statement stmtt=cot.createStatement();
Statement rowc=cot.createStatement();
Statement datas=cot.createStatement();
ResultSet resultt=stmtt.executeQuery("select * from month");
ResultSet resucourow=datas.executeQuery("select * from month where Acno="+chk);
int x=0;
while(resucourow.next()){ x++;
} resultt.next(); rsmt=resultt.getMetaData();
l=rsmt.getColumnCount(); System.out.println("Column Count"+l);
System.out.println("Column Count Rowssss "+x);
datars=rowc.executeQuery("select * from month where Acno="+chk);
} catch(Exception e1){
}
%>
<table border="1" bordercolorlight="#CCCC99" bordercolordark="#999966">
<tr> <%for(int v=1;v<=l;v++){System.out.println("l value"+l);
String cnames=rsmt.getColumnName(v);%>
<td width="50%"><font face="Arial, Helvetica" color = 'red'
size='5'><b><i><%=cnames.toUpperCase()%></i></b></font></td> <%}%> </tr><%
while(datars.next()){%>
<tr><%for(int vc=1;vc<=l;vc++){%> <td width="50%"><font face="Arial,
Helvetica"><%=datars.getString(vc)%></font></td><% } }%>
</html>
Question 1:
Write a program in C/C++ using OpenGL to draw a circle of orange colour and inside
that draw a square of blue colour.
Ans.
#include <windows.h>
#include <gl/glut.h>
#include <math.h>
const float PI=3.14;
void drawCircle(){
glBegin(GL_LINE_LOOP);
glColor3f(1.0,0.0,0.0);
for(int i =0; i <= 300; i++){
double angle = 2 * PI * i / 300;
double x = 5*cos(angle);
double y = 5*sin(angle);
glVertex2d(x,y);
}
glEnd();
}
void drawRect(){
glColor3f(0.0,0.0,1.0);
glRectf(-5.0,5.0,5.0,-5.0);
}
void init(void){
glClearColor(0.0,1.0,0.0,0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-10.0,10.0,-10.0,10.0,-10.0,10.0);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
drawRect();
drawCircle();
glutSwapBuffers();
}
int main(int argc, char** argv){
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutInitWindowSize(320,320);
glutInitWindowPosition(50,50);
glutCreateWindow("2D Shapes");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
Question 2:
Write a program in C/C++ using OpenGL to draw a hard wire house as shown in figure given
below. Use basic primitives of openGL.
Ans.
#include<Windows.h>
// for MS Windows
#include<GL\glut.h>
// GLUT, include glu.h and gl.h
//Note: GLglut.h path depending on the system in use
void init()
{
// Set display window color to as glClearColor(R,G,B,Alpha)
glClearColor(0.5, 0.9, 0.4, 0.0);
// Set projection parameters.
glMatrixMode(GL_PROJECTION);
// Set 2D Transformation as gluOrtho2D(Min Width, Max Width, Min Height, Max Height)
gluOrtho2D(0.0, 800, 0.0, 600);
}
void home()
{
//Roof
glClear(GL_COLOR_BUFFER_BIT); // Clear display window
// Set line segment color as glColor3f(R,G,B)
glColor3f(0.3, 0.5, 0.8);
glBegin(GL_POLYGON);
glVertex2i(200, 500);
glVertex2i(600, 500);
glVertex2i(700, 350);
glVertex2i(300, 350);
glEnd();
// Top of Front Wall
glColor3f(0.1, 0.5, 0.0);
glBegin(GL_TRIANGLES);
glVertex2i(200, 500);
glVertex2i(100, 350);
glVertex2i(300, 350);
glEnd();
// Front Wall
glColor3f(0.7, 0.2, 0.3);
glBegin(GL_POLYGON);
glVertex2i(100, 350);
glVertex2i(300, 350);
glVertex2i(300, 100);
glVertex2i(100, 100);
glEnd();
// Front Door
glColor3f(0.7, 0.2, 0.9);
glBegin(GL_POLYGON);
glVertex2i(150, 250);
glVertex2i(250, 250);
glVertex2i(250, 100);
glVertex2i(150, 100);
glEnd();
// Front Door Lock
glColor3f(0.3, 0.7, 0.9);
glPointSize(15);
glBegin(GL_POINTS);
glVertex2i(170, 170);
glEnd();
//side Wall
glColor3f(0.1, 0.2, 0.3);
glBegin(GL_POLYGON);
glVertex2i(300, 350);
glVertex2i(700, 350);
glVertex2i(700, 100);
glVertex2i(300, 100);
glEnd();
// window one
glColor3f(0.2, 0.4, 0.3);
glBegin(GL_POLYGON);
glVertex2i(330, 320);
glVertex2i(450, 320);
glVertex2i(450, 230);
glVertex2i(330, 230);
glEnd();
// line of window one
glColor3f(0.1, 0.7, 0.5);
glLineWidth(5);
glBegin(GL_LINES);
glVertex2i(390, 320);
glVertex2i(390, 230);
glVertex2i(330, 273);
glVertex2i(450, 273);
glEnd();
// window two
glColor3f(0.2, 0.4, 0.3);
glBegin(GL_POLYGON);
glVertex2i(530, 320);
glVertex2i(650, 320);
glVertex2i(650, 230);
glVertex2i(530, 230);
glEnd();
// lines of window two
glColor3f(0.1, 0.7, 0.5);
glLineWidth(5);
glBegin(GL_LINES);
glVertex2i(590, 320);
glVertex2i(590, 230);
glVertex2i(530, 273);
glVertex2i(650, 273);
glEnd();
// Entrance Path
glColor3f(0.3, 0.5, 0.7);
glLineWidth(3);
glBegin(GL_POLYGON);
glVertex2i(150, 100);
glVertex2i(250, 100);
glVertex2i(210, 0);
glVertex2i(40, 0);
glEnd();
// Process all OpenGL routine s as quickly as possible
glFlush();
}
int main(int argc, char ** argv)
{
// Initialize GLUT
glutInit(&argc, argv);
// Set display mode
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
// Set top - left display window position.
glutInitWindowPosition(100, 100);
// Set display window width and height
glutInitWindowSize(800, 600);
// Create display window with the given title
glutCreateWindow("2D House in OpenGL ");
// Execute initialization procedure
init();
// Send graphics to display window
glutDisplayFunc(home);
// Display everything and wait.
glutMainLoop();
}
Question 3:
Write a program in C/C++ to implement
Bresenham's circle generation algorithm.
Ans.
# include<stdio.h>
# include<conio.h>
# include<graphics.h>
# include<math.h>
void main()
{
int gd=DETECT,gm; int r,x,y,p,xc=320,yc=240;
initgraph(&gd,&gm,"C:\\TC\\BGI");
cleardevice();
printf("Enter the radius ");
scanf("%d",&r);
x=0;
y=r;
putpixel(xc+x,yc-y,1);
p=3-(2*r);
for(x=0;x<=y;x++)
{
if (p<0) { y=y; p=(p+(4*x)+6);
}
Else
{ y=y-1; p=p+((4*(x-y)+10));
}
putpixel(xc+x,yc-y,1);
putpixel(xc-x,yc-y,2);
putpixel(xc+x,yc+y,3);
putpixel(xc-x,yc+y,4);
putpixel(xc+y,yc-x,5);
putpixel(xc-y,yc-x,6);
putpixel(xc+y,yc+x,7);
putpixel(xc-y,yc+x,8);
}
getch();
closegraph();
}
Question 4:
Write a program in C/C++ to implement Cohen-Sutherland line clipping algorithm. In this
implementation consider two cases of a line: totally visible, totally invisible, against the
rectangular clipping window.
Ans
This is one of the oldest and most popular line clipping algorithm. To speed up the process this
algorithm performs initial tests that reduce number of intersections that must be calculated. It
does so
by using a 4 bit code called as region code or outcodes. These codes identify location of the end
point
of line.
Each bit position indicates a direction, starting from the rightmost position of each bit indicates
left,
right, bottom, top respectively.
Once we establish region codes for both the endpoints of a line we determine whether the
endpoint is
visible, partially visible or invisible with the help of ANDing of the region codes.
Algorithm
1. Read 2 end points of line as p1(x1,y1) and p2(x2,y2)
2. Read 2 corner points of the clipping window (left-top and right-bottom) as (wx1,wy1) and
(wx2,wy2)
3. Assign the region codes for 2 endpoints p1 and p2 using following steps:-
initialize code with 0000
Set bit 1 if x<wx1
Set bit 2 if x>wx2
Set bit 3 if y<wy2
Set bit 4 if y>wy1
4. Check for visibility of line
If region codes for both endpoints are zero then line is completely visible. Draw the line go to
step 9.
If region codes for endpoints are not zero and logical ANDing of them is also nonzero then line
is
invisible. Discard the line and move to step 9.
If it does not satisfy 4.a and 4.b then line is partially visible.
5. Determine the intersecting edge of clipping window as follows:-
If region codes for both endpoints are nonzero find intersection points p1’ and p2’ with boundary
edges.
If region codes for any one end point is non zero then find intersection point p1’ or p2’.
6. Divide the line segments considering intersection points.
7. Reject line segment if any end point of line appears outside of any boundary.
8. Draw the clipped line segment.
9. Stop.
Simple C program for Scan Line Polygon Filling Algorithm

#include <stdio.h>
#include <conio.h>
#include <graphics.h>

main()
{

int n,i,j,k,gd,gm,dy,dx;
int x,y,temp;
int a[20][2],xi[20];
float slope[20];

clrscr();
printf("\n\n\tEnter the no. of edges of polygon : ");
scanf("%d",&n);
printf("\n\n\tEnter the cordinates of polygon :\n\n\n ");

for(i=0;i<n;i++)
{
printf("\tX%d Y%d : ",i,i);
scanf("%d %d",&a[i][0],&a[i][1]);
}

a[n][0]=a[0][0];
a[n][1]=a[0][1];

detectgraph(&gd,&gm);
initgraph(&gd,&gm,"c:\\tc\\bgi");

/*- draw polygon -*/

for(i=0;i<n;i++)
{
line(a[i][0],a[i][1],a[i+1][0],a[i+1][1]);
}

getch();

for(i=0;i<n;i++)
{
dy=a[i+1][1]-a[i][1];
dx=a[i+1][0]-a[i][0];

if(dy==0) slope[i]=1.0;
if(dx==0) slope[i]=0.0;

if((dy!=0)&&(dx!=0)) /*- calculate inverse slope -*/


{
slope[i]=(float) dx/dy;
}
}

for(y=0;y< 480;y++)
{
k=0;
for(i=0;i<n;i++)
{

if( ((a[i][1]<=y)&&(a[i+1][1]>y))||
((a[i][1]>y)&&(a[i+1][1]<=y)))
{
xi[k]=(int)(a[i][0]+slope[i]*(y-a[i][1]));
k++;
}
}

for(j=0;j<k-1;j++) /*- Arrange x-intersections in order -*/


for(i=0;i<k-1;i++)
{
if(xi[i]>xi[i+1])
{
temp=xi[i];
xi[i]=xi[i+1];
xi[i+1]=temp;
}
}

setcolor(35);
for(i=0;i<k;i+=2)
{
line(xi[i],y,xi[i+1]+1,y);
getch();
}

}
Program for Cohen Sutherland Line Clipping Algorithm in C and C++
C Program
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<graphics.h>
#include<dos.h>

#include<stdio.h>

#include<stdlib.h>

#include<math.h>

#include<graphics.h>

#include<dos.h>

typedef struct coordinate

int x,y;

char code[4];

}PT;

void drawwindow();

void drawline(PT p1,PT p2);

PT setcode(PT p);

int visibility(PT p1,PT p2);

PT resetendpt(PT p1,PT p2);

void main()

{
int gd=DETECT,v,gm;

PT p1,p2,p3,p4,ptemp;

printf("\nEnter x1 and y1\n");

scanf("%d %d",&p1.x,&p1.y);

printf("\nEnter x2 and y2\n");

scanf("%d %d",&p2.x,&p2.y);

initgraph(&gd,&gm,"c:\\turboc3\\bgi");

drawwindow();

delay(500);

drawline(p1,p2);

delay(500);

cleardevice();

delay(500);

p1=setcode(p1);

p2=setcode(p2);

v=visibility(p1,p2);

delay(500);

switch(v)

case 0: drawwindow();

delay(500);

drawline(p1,p2);

break;

case 1: drawwindow();

delay(500);
break;

case 2: p3=resetendpt(p1,p2);

p4=resetendpt(p2,p1);

drawwindow();

delay(500);

drawline(p3,p4);

break;

delay(5000);

closegraph();

void drawwindow()

line(150,100,450,100);

line(450,100,450,350);

line(450,350,150,350);

line(150,350,150,100);

void drawline(PT p1,PT p2)

line(p1.x,p1.y,p2.x,p2.y);

}
PT setcode(PT p) //for setting the 4 bit code

PT ptemp;

if(p.y<100)

ptemp.code[0]='1'; //Top

else

ptemp.code[0]='0';

if(p.y>350)

ptemp.code[1]='1'; //Bottom

else

ptemp.code[1]='0';

if(p.x>450)

ptemp.code[2]='1'; //Right

else

ptemp.code[2]='0';

if(p.x<150)

ptemp.code[3]='1'; //Left

else

ptemp.code[3]='0';

ptemp.x=p.x;

ptemp.y=p.y;

return(ptemp);

int visibility(PT p1,PT p2)


{

int i,flag=0;

for(i=0;i<4;i++)

if((p1.code[i]!='0') || (p2.code[i]!='0'))

flag=1;

if(flag==0)

return(0);

for(i=0;i<4;i++)

if((p1.code[i]==p2.code[i]) && (p1.code[i]=='1'))

flag='0';

if(flag==0)

return(1);

return(2);

PT resetendpt(PT p1,PT p2)

PT temp;

int x,y,i;

float m,k;

if(p1.code[3]=='1')
x=150;

if(p1.code[2]=='1')

x=450;

if((p1.code[3]=='1') || (p1.code[2]=='1'))

m=(float)(p2.y-p1.y)/(p2.x-p1.x);

k=(p1.y+(m*(x-p1.x)));

temp.y=k;

temp.x=x;

for(i=0;i<4;i++)

temp.code[i]=p1.code[i];

if(temp.y<=350 && temp.y>=100)

return (temp);

if(p1.code[0]=='1')

y=100;

if(p1.code[1]=='1')

y=350;

if((p1.code[0]=='1') || (p1.code[1]=='1'))

m=(float)(p2.y-p1.y)/(p2.x-p1.x);

k=(float)p1.x+(float)(y-p1.y)/m;

temp.x=k;

temp.y=y;

for(i=0;i<4;i++)
temp.code[i]=p1.code[i];

return(temp);

else

return(p1);

C++ Program
#include<iostream.h>
#include<stdlib.h>
#include<math.h>
#include<graphics.h>
#include<dos.h>

#include<iostream.h>

#include<stdlib.h>

#include<math.h>

#include<graphics.h>

#include<dos.h>

typedef struct coordinate

int x,y;

char code[4];

}PT;

void drawwindow();

void drawline(PT p1,PT p2);

PT setcode(PT p);
int visibility(PT p1,PT p2);

PT resetendpt(PT p1,PT p2);

void main()

int gd=DETECT,v,gm;

PT p1,p2,p3,p4,ptemp;

cout<<"\nEnter x1 and y1\n";

cin>>p1.x>>p1.y;

cout<<"\nEnter x2 and y2\n";

cin>>p2.x>>p2.y;

initgraph(&gd,&gm,"c:\\turboc3\\bgi");

drawwindow();

delay(500);

drawline(p1,p2);

delay(500);

cleardevice();

delay(500);

p1=setcode(p1);

p2=setcode(p2);

v=visibility(p1,p2);

delay(500);

switch(v)

case 0: drawwindow();
delay(500);

drawline(p1,p2);

break;

case 1: drawwindow();

delay(500);

break;

case 2: p3=resetendpt(p1,p2);

p4=resetendpt(p2,p1);

drawwindow();

delay(500);

drawline(p3,p4);

break;

delay(5000);

closegraph();

void drawwindow()

line(150,100,450,100);

line(450,100,450,350);

line(450,350,150,350);

line(150,350,150,100);

}
void drawline(PT p1,PT p2)

line(p1.x,p1.y,p2.x,p2.y);

PT setcode(PT p) //for setting the 4 bit code

PT ptemp;

if(p.y<100)

ptemp.code[0]='1'; //Top

else

ptemp.code[0]='0';

if(p.y>350)

ptemp.code[1]='1'; //Bottom

else

ptemp.code[1]='0';

if(p.x>450)

ptemp.code[2]='1'; //Right

else

ptemp.code[2]='0';

if(p.x<150)

ptemp.code[3]='1'; //Left

else

ptemp.code[3]='0';

ptemp.x=p.x;
ptemp.y=p.y;

return(ptemp);

int visibility(PT p1,PT p2)

int i,flag=0;

for(i=0;i<4;i++)

if((p1.code[i]!='0') || (p2.code[i]!='0'))

flag=1;

if(flag==0)

return(0);

for(i=0;i<4;i++)

if((p1.code[i]==p2.code[i]) && (p1.code[i]=='1'))

flag='0';

if(flag==0)

return(1);

return(2);

PT resetendpt(PT p1,PT p2)


{

PT temp;

int x,y,i;

float m,k;

if(p1.code[3]=='1')

x=150;

if(p1.code[2]=='1')

x=450;

if((p1.code[3]=='1') || (p1.code[2]=='1'))

m=(float)(p2.y-p1.y)/(p2.x-p1.x);

k=(p1.y+(m*(x-p1.x)));

temp.y=k;

temp.x=x;

for(i=0;i<4;i++)

temp.code[i]=p1.code[i];

if(temp.y<=350 && temp.y>=100)

return (temp);

if(p1.code[0]=='1')

y=100;

if(p1.code[1]=='1')

y=350;

if((p1.code[0]=='1') || (p1.code[1]=='1'))

{
m=(float)(p2.y-p1.y)/(p2.x-p1.x);

k=(float)p1.x+(float)(y-p1.y)/m;

temp.x=k;

temp.y=y;

for(i=0;i<4;i++)

temp.code[i]=p1.code[i];

return(temp);

else

return(p1);

Potrebbero piacerti anche