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}}.
```
```
{{var1}} creates $var2 code with $var3 knowledge to create {{var4}}
```
Data scientist creates programming code with statistical knowledge to create insights.

Data scientist creates $var2 code with $var3 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/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?
Match the type of service approaches from column A to their correct examples in column B. | | Column A | | Column B | |---|---|---|---| | a | SaaS | 1 | Replit | | b | PaaS | 2 | Office 365 | | c | IaaS | 3 | Amazon Web Services |

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"))
```
```
code 1: book_id=Column(Integer, ForeignKey("book_table.id"))
code 2: sections = relationship("Book")
```
```python
code 1: books = relationship("Book")
code 2: section_id=Column(Integer, ForeignKey("section_table.id"))
```
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 >= 5 %}
<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. Regression testing | 1. Beta Testing | | B. User Acceptance testing | 2. Considers internal functioning of the system | | C. White Box Testing | 3. Simulates actual user interaction, allows to script browser | | D. System testing Automation | 4. Type of testing that runs after every change to ensure that the change introduces no unintended breaks. | 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=4 ?
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 -12`?
2023-08-14 21:01:05,684 - INFO - Value added: 12

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

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

None.

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 throw a KeyError?

```python
temp.substitute({"animal": "cat"})
```
```python
temp.safe_substitute({"animal": "dog", "obstacle": "fence"})
```
```python
temp.safe_substitute({"animal": "rabbit"})
```
```python
temp.safe_substitute({"obstacle": "wall", "place": "park town"})
```
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 src="login.html">Signin</a> <!-- login.html contains -> <a src="index.html">Home</a> ```

```html <!-- index.html contains -> <a href="login.html">Signin</a> <!-- login.html contains -> <a href="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"),unique=True)
```
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 case_test3(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 === ```

``` == 2 passed, 3 deselected in 0.17s === ```

``` == 2 passed in 0.07s === ```

``` == 3 failed, 2 passed in 0.17s === ```

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>
<p>DBMS</p>
{% 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 below Flask Restful API code snippet:
**app.py**
```python
from flask import Flask, request
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
data_info = [
{"name": "IITM", "mail": "abc@study.iitm.ac.in"}
]
class Data(Resource):
def get(self):
return data_info
def post(self):
name = request.json["name"]
mail = request.json["mail"]
data = {}
data["name"] = name
data["mail"] = mail
data_info.append(data)
return "Saved data", 200
api.add_resource(Data, "/")
if __name__ == "__main__":
app.run()
```
Assume that above **app.py** is running on http://127.0.0.1:5000/. What will be the outputs of the below sequence of CURL commands:
i)
```
curl -X POST -H "Content-Type: application/json" -H "Accept-Type: application/json" -d "{\"name\":\"Javed\",\"mail\":\"javed@study.iitm.ac.in\"}" "http://127.0.0.1:5000/"
```
ii)
```
curl -X GET "http://127.0.0.1:5000"
```
i) "Saved data"
ii)
```
[
{
"name": "IITM",
"mail": "abc@study.iitm.ac.in"
},
{
"name": "Javed",
"mail": "javed@study.iitm.ac.in"
}
]
```
i)
```json
[
{
"name": "IITM",
"mail": "abc@study.iitm.ac.in"
},
{
"name": "Javed",
"mail": "javed@study.iitm.ac.in"
}
]
```
ii) "Saved data"
i)
```
[
{
"name": "Javed",
"mail": "javed@study.iitm.ac.in"
}
]
```
ii)
```
[
{
"name": "IITM",
"mail": "abc@study.iitm.ac.in"
}
]
```
i)
```
[
{
"name": "IITM",
"mail": "abc@study.iitm.ac.in"
}
]
```
ii)
```
[
{
"name": "Javed",
"mail": "javed@study.iitm.ac.in"
}
]
```
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 x-axis labeled "Time (Hours)" and a vertical y-axis labeled "BandWidth Megabits/s". The x-axis ranges from 0 to 24, with major tick marks at 0, 4, 8, 12, 14, 16, 20, and 24. The y-axis ranges from 0 to 12, with major tick marks at 0, 2, 4, 6, 8, 10. There is an orange step-function line plotted on the graph. - 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 10 Megabits/s. Three horizontal colored lines are drawn above the step function, each labeled with a user. - A blue line labeled "user 1" extends from Time 0 to Time 4. - A yellow line labeled "user 2" extends from Time 8 to Time 14. - A green line labeled "user 3" extends from Time 16 to Time 24. Vertical dashed lines extend from the x-axis tick marks at 4, 8, 12, 14, 16, 20, and 24 up to the top of the graph.

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>
<p class="two" id="two">Content 2</p>
<span id="three">Content 3</span>
</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 also all required modules are installed. Which of the below statement(s) are True?
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:
The image displays an Entity-Relationship Diagram (ERD) with two entities: "Salary_Slip" and "Employee".
**Entity: Salary_Slip**
* **Attributes:**
* slip_id (PK)
* Year (DateTime)
* Month (DateTime)
* Salary_issued (Boolean)
* Total_salary (Integer)
**Entity: Employee**
* **Attributes:**
* Employee_id (PK)
* Employee_name (Text)
**Relationship:**
There is a relationship line connecting "Salary_Slip" and "Employee".
* The "Salary_Slip" side of the relationship has a crow's foot symbol with a single line, indicating "many".
* The "Employee" side of the relationship has two vertical lines, indicating "exactly one".
This represents a "many-to-one" relationship where many Salary_Slips can be associated with exactly one Employee.
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/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?term=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 passed, 3 deselected, 4 warnings in 0.04s =========`
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 4?`

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

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

No course found!

``` IndexError: list index out of range ```

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

No course found!

``` course found App Dev I ```

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

``` 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 "Modern Application Development I" exam, along with Mermaid knowledge graphs to visualize relationships.
String Templating (string.Template vs jinja2.Template)
string.Template:
$var syntax.substitute() raises KeyError if a placeholder is missing.safe_substitute() ignores missing placeholders.jinja2.Template:
{{ var }} syntax.{% for %}), conditionals ({% if %}), and macros.render() substitutes variables from a dictionary.Command-Line Arguments (sys.argv)
sys.argv[0] = Script name.sys.argv[1:] = User-provided arguments.Python String Formatting
.format(), %-formatting.### string.Template
from string import Template
temp = Template("Hello, $name!")
print(temp.substitute(name="World")) # "Hello, World!"
### jinja2.Template
from jinja2 import Template
temp = Template("Hello, {{ name }}!")
print(temp.render(name="World")) # "Hello, World!"
### Command-line args
import sys
print(sys.argv[0]) # Script name
print(sys.argv[1]) # First argument
Routing (@app.route)
<string:var>, <path:var>, <int:var>.GET, POST, PUT, DELETE.Request Handling (flask.request)
request.args.get("key").request.form["key"].request.json["key"].Jinja2 Templating in Flask
render_template("file.html", data=data).{% extends "base.html" %}.Flask-RESTful
GET, POST, etc.Api.add_resource(ResourceClass, "/endpoint").from flask import Flask, request, render_template
app = Flask(__name__)
@app.route("/user/<string:name>")
def greet(name):
return f"Hello, {name}!"
@app.route("/data", methods=["POST"])
def handle_data():
data = request.json
return {"received": data}
if __name__ == "__main__":
app.run(debug=True)
HTML & CSS
<header>, <section>, <footer>).!important > inline > ID > class > element.margin, border, padding, content.Frontend Frameworks
Navigation Between Pages
<a href="page.html">Link</a> (correct).<a src="page.html">Link</a> (incorrect).Database Indexes
SELECT query performance.Relationships in SQLAlchemy
One-to-Many:
relationship("Child", back_populates="parent").One-to-One:
unique=True.Many-to-Many:
ER Diagrams
Book → Many Sections.Author → One Book (unique=True).### One-to-Many (Book → Sections)
class Book(Base):
__tablename__ = "books"
id = Column(Integer, primary_key=True)
sections = relationship("Section", back_populates="book")
class Section(Base):
__tablename__ = "sections"
id = Column(Integer, primary_key=True)
book_id = Column(Integer, ForeignKey("books.id"))
book = relationship("Book", back_populates="sections")
Pytest Basics
test_*.py or *_test.py.def test_*().assert condition.Fixtures (@pytest.fixture)
Markers (@pytest.mark.*)
pytest -m marker_name.Flask Testing
app.test_request_context(): Simulate HTTP requests.url_for(): Generate URLs for routes.### pytest example
import pytest
@pytest.mark.slow
def test_add():
assert 1 + 1 == 2
### Flask test
def test_home_route():
with app.test_request_context():
assert url_for("home") == "/"
Default Branch
main (modern repos) or master (older repos).Basic Commands
git init, git add, git commit, git push.Bandwidth & Data Transfer
(Megabits / 8) / 1024.Latency & Speed of Light
distance / speed.\[ \text{Data (GB)} = \frac{\text{Bandwidth (Mbps)} \times \text{Time (s)}}{8 \times 1024} \]
| Type | Example | Description |
|---|---|---|
| SaaS | Office 365, Gmail | Software as a service. |
| PaaS | Replit, Heroku | Platform for app development. |
| IaaS | AWS, Azure | Infrastructure (VMs, storage). |
paths: Contains all API endpoints.schema: Defines data models.info: Metadata (title, version).responses: HTTP response codes.| Type | Description |
|---|---|
| Regression Testing | Ensures new changes don’t break existing functionality. |
| User Acceptance Testing | Validates software with real users (e.g., beta testing). |
| White Box Testing | Tests internal logic (code coverage). |
| System Testing | End-to-end testing of the full system. |
| Automation Testing | Uses tools (Selenium) to simulate user interactions. |
Data Transfer (GB): \[ \text{Data (GB)} = \frac{\text{Bandwidth (Mbps)} \times \text{Time (s)}}{8 \times 1024} \]
10 Mbps × 4 hours × 3600 s/hour = 144,000 Mb. Convert to GB: 144,000 / 8 / 1024 ≈ 17.58 GB.Latency (Time for Data Travel): \[ \text{Latency (s)} = \frac{\text{Distance (m)}}{\text{Speed (m/s)}} \]
Disk RPM Calculation: \[ \text{RPM} = \frac{\text{Read Speed (bits/s)}}{\text{Bits per Revolution}} \times 60 \]
42,000 bits/s ÷ 600 bits/rev × 60 = 4,200 RPM.Flask Routes:
/home/<string:url> matches /home/abc but not /home/abc/def./home/<path:url> matches /home/abc/def.Jinja2 vs string.Template:
{% if %}), while string.Template does not.SQLAlchemy Relationships:
unique=True.Pytest:
test_* are run.-k filters tests by name, -m by markers.Git:
main (new repos) or master (old repos).Networking:
Frontend:
<a href="..."> is correct; <a src="..."> is wrong.Cloud: