Home / Past papers / MAD1 End Term / this paper

Consider the following Python code snippet.
```python
from string import Template as makeTemplate
from jinja2 import Template
import sys
var = sys.argv[0]
data = {"var1": "Data scientist", "var2": "programming",
"var3": "statistical", "var4": "insights"}
temp = "{{var1}} creates $var2 code with $var3 knowledge to create\
{{var4}}."
if var == "1":
temp = makeTemplate(temp)
output = temp.substitute(data)
print(output)
else:
temp = Template(temp)
output = temp.render(data)
print(output)
```
What will be printed on the terminal for the command `python app.py 1 2`?
```
{{var1}} creates programming code with statistical knowledge to create {{var4}}.
```
Data scientist creates $var2 code with $var3 knowledge to create insights.

```
{{var1}} creates $var2 code with $var3 knowledge to create {{var4}}
```
Data scientist creates programming code with statistical knowledge to create insights.

Consider the following flask application running locally on http://127.0.0.1:5000 ?
```python
from flask import Flask
app = Flask(__name__)
@app.route('/home/<string:url>')
def get_url_str(url):
return "string "+url
@app.route('/home/<path:url>')
def get_url_pth(url):
return "path "+url
app.run(debug = True)
```
Which of the following URLs will throw a 404 Not Found error?
http://127.0.0.1:5000/home/modules

http://127.0.0.1:5000/home/modules/chapters/one

``` http://127.0.0.1:5000/home/library/modules/chapters/one ```

None

Consider the following view function.
```python
from flask import Flask, request
app = Flask(__name__)
@app.route('/student', methods = ['GET', 'POST'])
def show_details():
cred = request.args
details = {
'Stream': cred['dept'],
'Roll': cred['roll'],
'Course': cred['course']
}
return details
app.run()
```
If this flask app is running locally on http://127.0.0.1:5000, which of the following URLs will be handled by the controller correctly?
``` http://127.0.0.1:50000?dept=data_science&roll=cs10018&course=cs2003 ```

http://127.0.0.1:5000/data_science/cs1001/cs2003

http://127.0.0.1:5000/student?dept=data_science&roll=cs1001&course=cs2003

http://127.0.0.1:5000/student/data_science/cs1001/cs2003

Consider the following snippet of HTML and its output rendered on the browser:
post
index.html
```html
<form action="/" method="POST">
<label for="fname">What is your first name?</label><br>
<input type="text" name="fname" id="fname"><br>
<input type="submit" value="Submit">
</form>
```
Diagram: Browser window showing a web page.
The browser window has a dark grey title bar with "Form" as the tab title, a close button, a plus button, a dropdown arrow, a purple infinity symbol with "Private browsing", minimize, maximize, and close buttons.
Below the title bar is a navigation bar with back, forward, reload, home, shield, padlock, "localhost:5000", star, L, and menu icons.
The main content area of the browser window is white and displays:
"What is your firstname?"
Below this text is an empty rectangular input field.
Below the input field is a button labeled "Submit".
Which HTTP request would be sent to the server if the user enters "Mahesh" into the text box and clicks submit?
``` git new-branch <branch_name> ```

``` git branch <branch_name> ```

``` git new <branch_name> ```

``` git create-branch <branch_name> ```

In the code snippet given below, what should come in place of code 1 and code 2 such that one book can have multiple sections and the converse does not hold true?
```python
from sqlalchemy import ForeignKey
from sqlalchemy import Integer, Column
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import relationship
class Base(DeclarativeBase):
Pass
class Section(Base):
__tablename__ = "section_table"
id = Column(Integer, primary_key=True)
# write your code 1 here
class Book(Base):
__tablename__ = "book_table"
id = Column(Integer, primary_key=True)
# write your code 2 here
```
```python
code 1: book_id=Column(Integer, ForeignKey("book_table.id"))
code 2: books = relationship("Section")
```
```python
code 1: books = relationship("Section")
code 2: section_id=Column(Integer, ForeignKey("book_table.id"))
```
```python
code 1: books = relationship("Book")
code 2: section_id=Column(Integer, ForeignKey("section_table.id"))
```
```python
code 1: book_id=Column(Integer, ForeignKey("book_table.id"))
code 2: sections = relationship("Book")
```
Consider the following flask app and Jinja2 template.
app.py
```python
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template("index.html", data=['Harry', 'Karl', 'John', 'Jason', 'Ros'])
app.run()
```
index.html
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Macro</title>
</head>
<body>
{% macro unordered_list(items)%}
<ul>
{% for item in items %}
{% if item|length <= 4 %}
<li>{{item}}</li>
{% endif %}
{% endfor %}
</ul>
{% endmacro %}
{{ unordered_list(data) }}
</body>
</html>
```
If the flask app is running locally on http://127.0.0.1:5000. What will be the output on the browser for the base URL?
- Harry - Karl - John - Jason - Ros

- Karl - John

- Harry - Jason

* Karl * John * Ros

Match the following types of testing with their functionality. | | | |---|---| | A. White Box Testing | 1. Beta Testing | | B. User Acceptance testing | 2. One step beyond integration Testing | | C. System testing | 3. Simulates actual user interaction, allows to script browser | | D. System testing Automation | 4. Considers internal functioning of the system | Which of the following is the correct matching?

A → 1, B → 2, C → 3, D → 4

A → 4, B → 3, C → 2, D → 1

A -> 4, B -> 1, C -> 2, D -> 3

A → 3, B → 2, C → 1, D → 4

Consider the following flask application.
```python
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def square():
val = request.args
if val['num'] == '':
return "<h1>Enter a valid number</h1>"
elif val['num'].isalpha()==True:
return "<h1>Invalid number</h1>"
else:
out = (int(val['num'])) * (val['num'])
return f'<h1>{out}</h1>'
if(__name__ == "__main__"):
app.run(debug=True)
```
If this flask app is running locally on http://localhost:5000, what is the output for the URL
http://localhost:5000/?num=2 ?
Consider the following Python code snippet.
log.py
```python
import logging
import sys
logging.basicConfig(level=logging.WARNING,
format='%(asctime)s - %(levelname)s - %(message)s')
def check_val(value):
if value < 0:
raise ValueError("Invalid value: Please enter a positive value.")
else:
logging.info("Value added: %s", value)
try:
input_value = int(sys.argv[1])
check_val(input_value)
except ValueError as ve:
logging.exception("Exception occurred: %s", str(ve))
```
What will be the output on the terminal for the command: `python log.py -34`?
2023-08-14 21:01:05,684 - INFO - Value added: 34

``` 2023-08-14 21:01:05,684 - WARNING - Value added: 34 ```

Error: Exception occurred: Invalid value: Please enter a positive value.

None.

Consider the following flask resource created using flask_restful.
```python
from flask import Flask, request
from flask_restful import Api, Resource, reqparse
app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument("val")
class RestApi(Resource):
def post(self, val):
arg1 = parser.parse_args()
arg2 = request.args
return {
"Course_1": arg1["val"],
"Course_2": arg2["val"],
"Course_3": val
}
api.add_resource(RestApi, "/api/courses/<val>")
app.run(debug = True)
```
If the application is running locally on http://127.0.0.1:5000, What will be the output on the terminal for the command:
```bash
curl http://127.0.0.1:5000/api/courses/DBMS?val=JAVA -d "{\"val\":\"PDSA\"}" -X POST -H "Content-Type: application/json"
```
```json
{
"Course_1": "JAVA",
"Course_2": "PDSA",
"Course_3": "DBMS"
}
```
```json
{
"Course_1": "DBMS",
"Course_2": "JAVA",
"Course_3": "PDSA"
}
```
```json
{
"Course_1": "PDSA",
"Course_2": "JAVA",
"Course_3": "DBMS"
}
```
```json
{
"Course_1": "PDSA",
"Course_2": "DBMS",
"Course_3": "JAVA"
}
```
What will be the output of the following Python code?
```python
from jinja2 import Template
my_statement = Template("The special series is:{% for n in
range(1,15)%} {{n/3}}" "{% endfor %}")
out = my_statement.render()
print(out)
```
Consider that there are two HTML files. i) index.html - Home page of the application ii) login.html - Login page of the application Which of the following code will navigate the user between **index.html** and **login.html**, and vice versa?

```html <!-- index.html contains--> <a src="index.html">Signin</a> <!-- login.html contains -> <a src="login.html">Home</a> ```

```html <!-- index.html contains -> <a href="index.html">Signin</a> <!-- login.html contains -> <a href="login.html">Home</a> ```

```html <!-- index.html contains -> <a href="login.html">Signin</a> <!-- login.html contains -> <a href="index.html">Home</a> ```

```html <!-- index.html contains -> <a src="login.html">Signin</a> <!-- login.html contains -> <a src="index.html">Home</a> ```

Consider the below two data models Author and Book using SQLite database.
```python
class Author(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
dob = db.Column(db.String)
class Book(db.Model):
id = db.Column(db.Integer(), primary_key=True)
title = db.Column(db.String())
publisher = db.Column(db.String())
written_by = db.Column(db.Integer(), db.foreign_key("author.id"))
```
What kind of relationship exists between Author and Book classes?
Consider a function func, and a set of test cases given below.
Filename: test_file.py
```python
import pytest
def func(x,y):
out = x**2+y**2
return out
class Test_class0():
def test_case1(self):
assert func(1,2) == 5
def case_test2(self):
assert func(2,3) == 13
def test_case3(self):
assert func(6,2) == 38
class Test_class1():
def test_case1(self):
assert func(5,2) == 29
def case_test2(self):
assert func(1,1) == 2
```
What will be the output on the terminal for the command below?
pytest test_file.py -k Test_class
``` == 1 failed, 4 passed in 0.17s === ```

``` == 1 failed, 2 passed, 2 deselected in 0.17s === ```

``` == 2 failed, 1 deselected in 0.17s === ```

``` == 1 failed, 2 passed in 0.14s === ```

Consider the following python code snippet app.py, the HTML files, base.html and home.html residing in "templates" folder.
app.py
```python
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
app.run(debug=True)
```
home.html
```html
{% extends "base.html" %}
{% block content %}
<p>MAD I</p>
<span>MAD II</span>
<span>DBMS</span>
{% endblock %}
```
base.html
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>IITM</title>
</head>
<body>
<h2 style="color: violet;"> Diploma Courses </h2>
{% block content %}
{% endblock %}
</body>
</html>
```
What will be the rendered output for base URL if flask app is running locally on
http://localhost:5000 ?
MAD I MAD II DBMS

Diploma Courses MAD I MAD II DBMS

Diploma Courses MAD I MAD II DBMS

MAD I MAD II DBMS
Consider the following graph that represents the variation in bandwidth of a network for an entire day (24 hours). Three users were connected to the network at three different times of the day. What is the total data consumed in GigaBytes by all the users in 24 hrs? This is a 2D line graph with a horizontal axis labeled "Time (Hours)" ranging from 0 to 24, and a vertical axis labeled "BandWidth" with units "Megabits/s" ranging from 0 to 12. There are three horizontal colored lines at the top of the graph, each labeled: - A blue line labeled "user 1" extends from Time 0 to 4. - A yellow line labeled "user 2" extends from Time 8 to 14. - A green line labeled "user 3" extends from Time 14 to 24. There is an orange step-function line representing bandwidth over time: - From Time 0 to 4, BandWidth is 8 Megabits/s. - From Time 4 to 8, BandWidth is 10 Megabits/s. - From Time 8 to 12, BandWidth is 6 Megabits/s. - From Time 12 to 16, BandWidth is 8 Megabits/s. - From Time 16 to 20, BandWidth is 2 Megabits/s. - From Time 20 to 24, BandWidth is 4 Megabits/s. Vertical dashed lines extend from the horizontal axis at Time 4, 8, 12, 14, 16, 20, and 24, indicating the points where the bandwidth or user activity changes.

Consider the following restful implementation using flask.
```python
from flask import Flask, request
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
student_info = {"name": "Ramesh", "Roll_No":"user123",
"Email":"ramesh.user@kmail.com"}
class Student(Resource):
def delete(self):
data = request.json
student_info.update(data)
return student_info
def put(self):
student_info.popitem()
return "success", 200
api.add_resource(Student, '/')
app.run()
```
If the above application is running on http://127.0.0.1:5000 then what will be the final output on terminal on executing these two curl commands in the order mentioned?
1:
```bash
curl -X PUT -H "Content-Type: application/json" -H "Accept-Type: application/json" -d "{\"Roll_No\":\"user321\", \"Email\":\"r.user@kmail.com\"}" http://127.0.0.1:5000/
```
2:
```bash
curl -X DELETE -H "Content-Type: application/json" -H "Accept-Type: application/json" -d "{\"Roll_No\":\"user321\", \"Email\":\"r.user@kmail.com\"}" http://127.0.0.1:5000/
```
```json
{
"name": "Ramesh",
"Roll_No": "user321",
"Email": "r.user@kmail.com"
}
```
```json
{
"name": "Ramesh",
"Roll No": "user321"
}
```
```json
{
"Roll No":"user321",
"Email":"r.user@kmail.com"
}
```
```json
{
"name": "Ramesh",
"Roll_No": "user123",
"Email": "r.user@kmail.com"
}
```
An HTML code and CSS code is given below. Which of the following correctly represents
its rendered output?
CSS Code:
```css
#one{color: blue;}
.two{color: red !important;}
#two{color: green}
#three{color: green;}
```
HTML Code:
```html
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
<link href="style.css" rel="stylesheet">
<style>
body{font-weight: bold;}
p{color: violet !important ;}
</style>
</head>
<body>
<span id="one">Content 1</span>
<span class="two" id="two">Content 2</span>
<p id="three">Content 3</p>
</body>
</html>
```
Content 1 Content 2 Content 3

Content 1 Content 2 Content 3

Content 1 Content 2 Content 3

Content 1 Content 2 Content 3

Consider the below two python files code snippets app.py and test_app_route.py.
app.py
```python
from flask import Flask
app = Flask(__name__)
@app.route("/greet/<string:name>")
def home(name):
return "Hello, " + name
if __name__ == "__main__":
app.run()
```
test_app_route.py:
```python
import pytest, requests
@pytest.fixture
def get_response():
resp = requests.get("http://127.0.0.1:5000/greet/IITM")
return resp
def test_response(get_response):
assert get_response.text == "Hello, IITM"
```
Assume that app.py and test_app_route.py are running on two different terminals and all required modules are installed, then which of the following is the correct option for the statements given below?
i) Executing the command `pytest test_app_route.py` on the terminal returns
`=========== 1 passed ===========`
ii) Executing the command `pytest test_app_route.py` on the terminal returns
`=========== 1 failed ===========`
iii) Executing the command `pytest test_app_route.py` on the terminal returns
`=========== 1 selected, 1 passed ===========`
iv) Executing the command `pytest test_app_route.py` on the terminal returns
`=========== 1 deselected ===========`
What can be inferred from the Entity-Relationship Diagram below: ER Diagram: - Two entities: `Salary_Slip` and `Employee`. - `Salary_Slip` entity has the following attributes: - `slip_id` (PK) - `Year` (DateTime) - `Month` (DateTime) - `Salary_issued` (Boolean) - `Total_salary` (Integer) - `Employee` entity has the following attributes: - `Employee_id` (PK) - `Employee_name` (Text) - A relationship exists between `Salary_Slip` and `Employee`. - The relationship line connects `Salary_Slip` to `Employee`. - The `Salary_Slip` side of the relationship has a crow's foot (many) and a single line (exactly one or more). - The `Employee` side of the relationship has two vertical lines (exactly one). - This indicates a many-to-one relationship where many `Salary_Slip` records can be associated with exactly one `Employee`.

Consider the following python code snippet. ```python from string import Template statement = "The $animal jumped over the $obstacle." temp = Template(statement) print(=== OUTPUT ===) ``` Which of the following statements, when substituted in place of === OUTPUT ===, will not throw a KeyError?

```python
temp.substitute({"animal": "cat"})
```
```python
temp.safe_substitute({"animal": "dog", "obstacle": "fence"})
```
```python
temp.safe_substitute({"animal": "rabbit"})
```
```python
temp.substitute({"animal": "horse", "obstacle": "wall"})
```
Consider the following flask app. Given that `test_request_context()` allows text to be printed on the terminal, which of the following statements is/are correct?
```python
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/library')
def home():
return 'Select your course!'
@app.route('/student/<username>/<roll>')
def dashboard(username):
return f'{username}\'s dashboard'
with app.test_request_context():
#== print statement ==#
```
If `print statement` is replaced by:
```python
print(url_for('home', user = "mad1_cs2003"))
```
the output on the terminal will be;
`/library/mad1_cs2003.`
If `#== print statement ==#` is replaced by:
```python
print(url_for('home', user = "mad1_cs2003")),
```
the output on the terminal will be;
`/library?user=mad1_cs2003.`
If #== *print statement* ==# is replaced by:
```python
print(url_for('dashboard', username = "mad1", roll = "cs2003", term = "jan2024"))
```
the output on the terminal will be;
`/student/mad1/cs2003?term=jan2024.`
If #== *print statement* ==# is replaced by:
```python
print(url_for('dashboard', username = "mad1", roll = "cs2003", term = "jan2024"))
```
the output on the terminal will be:
/student/mad1/cs2003/jan2024.
Consider the following function to be tested and test functions given in the Python code snippet below.
**test_file.py**
```python
import pytest
def square(x):
sum = 0
for counter in range(x):
sum += x
return sum
@pytest.mark.marker1
def testcase_1():
assert square(10) == 100
@pytest.mark.marker2
def testcase_2():
assert square(4) == 4
@pytest.mark.marker3
def testcase_3():
assert square(5) == 25
@pytest.mark.marker4
def testcase_4():
assert square(6) == 6
```
On running this file on the terminal using pytest, the summary of the output is:
`========= 1 failed, 3 deselected, 4 warnings in 0.17s =========`
What command will result into the outcome given above?
``` pytest test_file.py -m marker4 ```

``` pytest test_file.py -m marker1 ```

``` pytest test_file.py -m marker2 ```

``` pytest test_file.py -m marker3 ```


What will be output on the terminal for the command python file.py course 2?

course found App Dev II

course found App Dev III

No course found!

```text course found App Dev I course found App Dev II ```

What will be output on the terminal for the command python file.py course 3?

course found App Dev III

``` course found App Dev I course found App Dev II ```

``` course found App Dev I course found App Dev II course found App Dev III ```

``` IndexError: list index out of range ```
Auto-generated summary from the source site. Handy as a checklist; the lessons above explain each idea from scratch.
Here’s a structured summary of the core topics, concepts, principles, and equations essential for the exam, along with Mermaid knowledge graphs to visualize relationships.
Python String Templating
string.Template vs. jinja2.Template:
string.Template: Uses $var syntax (e.g., "Hello ${name}").
.substitute() (raises KeyError if missing), .safe_substitute() (ignores missing keys).jinja2.Template: Uses {{ var }} syntax.
.render() (handles missing keys gracefully).Example:
from string import Template as makeTemplate
temp = makeTemplate("${var1} creates ${var2}")
output = temp.substitute(var1="Data scientist", var2="code") # Requires all keys.Flask Routing & Request Handling
Route Parameters:
<string:url>: Matches a single path segment (e.g., /home/abc).<path:url>: Matches multiple segments (e.g., /home/abc/def/ghi).HTTP Methods:
GET: Query parameters (request.args).POST: Form/data (request.form or request.json).Example:
@app.route('/student', methods=['GET', 'POST'])
def show_details():
cred = request.args # For GET: ?dept=CSE&roll=1
return {"stream": cred['dept'], "Roll": cred['roll']}Flask-Jinja2 Macros & Templating
Macros: Reusable HTML blocks (e.g., lists, forms).
{% macro unordered_list(items) %}
<ul>{% for item in items %}<li>{{ item }}</li>{% endfor %}</ul>
{% endmacro %}Template Inheritance:
{% extends "base.html" %}: Inherit from a parent template.{% block content %}...{% endblock %}: Override sections.Flask-RESTful
get, post, put, delete).Request Parsing:
from flask_restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument("val", type=str)
args = parser.parse_args() # Parses JSON/form data.Flask Testing
test_request_context(): Simulates a request for testing URLs.
with app.test_request_context():
print(url_for('home', user="test")) # Output: /library?user=testPytest Fixtures:
@pytest.fixture
def client():
app.config['TESTING'] = True
return app.test_client()DRAM Bandwidth Calculation:
Network Latency:
v or double D).HTTP Methods:
GET: Fetch data (query params in URL).POST: Submit data (body payload).PUT: Update/replace resource.DELETE: Remove resource.HTML Forms:
method="POST": Sends data in request body.action="/post": Endpoint URL.Example:
<form action="/post" method="POST">
<input type="text" name="fname">
<input type="submit">
</form>
→ Submits fname=Mahesh in request body.
CSS Specificity:
!important > Inline > ID (#one) > Class (.two) > Element (p).Example:
.two { color: red !important; } /* Wins over #two { color: green; } */JavaScript Console Logging:
console.log(): Prints to browser console.window.alert(): Shows popup.document.write(): Writes to HTML body.Relationships:
One-to-Many: Foreign key in "many" table (e.g., Book → Section).
class Section(Base):
__tablename__ = "section"
id = Column(Integer, primary_key=True)
book_id = Column(Integer, ForeignKey("book.id")) # Foreign key
book = relationship("Book", back_populates="sections") # Relationshipback_populates or backref.Indexes:
UNIQUE constraint is set).ER Diagrams:
Cardinality:
| Command | Description |
|---|---|
git branch <name> | Create a new branch. |
git checkout <branch> | Switch branches. |
git merge <branch> | Merge branches. |
Pytest:
Markers: @pytest.mark.marker1 to select tests.
pytest -m "marker1" # Run only marker1 tests.
pytest -m "not marker2" # Exclude marker2.assert func(1, 2) == 5.Statelessness:
Bandwidth vs. Data Transfer:
| Concept | Equation |
|---|---|
| DRAM Bandwidth | \( \text{GB/s} = \frac{\text{Bus Width (bits)} \times \text{Clock (Hz)} \times 2}{8 \times 10^9} \) |
| Network RTT | \( \text{RTT} = \frac{2 \times \text{Distance}}{\text{Speed of Light}} \) |
| Requests per Second | \( N = \frac{1}{\text{RTT}} \) |
| Data Transfer | \( \text{GB} = \frac{\text{Bandwidth (Mb/s)} \times \text{Time (s)}}{8 \times 10^3} \) |
Flask/Jinja2:
string.Template and jinja2.Template.<string> vs. <path>).request.args (GET) vs. request.json (POST).Databases:
UNIQUE.Testing:
-m) and fixtures are critical.pytest -m "not marker1").Networking:
Git:
git branch (create), git checkout (switch), git merge (combine).Performance:
N) requires doubling RTT (e.g., halve speed or double distance).