Home / Past papers / MAD2 End Term / this paper

Suppose an application is loaded from an origin "https://abc.com". Which of the following origins will result in a CORS error, while making a fetch call, by default?

https://abc.com

https://xyz.abc.com

https://abc.com/page

https://abc8.com
Consider the following JavaScript code. ```javascript
function goUpDown(num) {
return new Promise((res, rej) => {
setTimeout(() => {
if (num < 20) {
return num > 10 ? res('Go Up') : res('Go Down')
} else {
return rej('Number Too Large')
}
}, 1000)
})
}
async function getData() {
const data3 = await goUpDown(8)
const data2 = await goUpDown(15)
const data1 = await goUpDown(12)
}
getData().then(
(data) => {
console.log(data)
},
(err) => {
console.log(err)
}
)
```
What will be logged on to console, if executed?
Consider the following JavaScript code. Suppose there is an network error and fetch request to the ‘url’ fails. What will be logged on to console, if the code is executed?```javascript
async function getResponse(url) {
try {
const response = await fetch(url)
try {
const data = await response.json()
if (response.ok) {
return data
} else {
return response.status
}
} catch {
return 'Network Error'
}
} catch {
return 'Response is not json'
}
}
getResponse('url').then((data) => {
console.log(data)
})
```
Consider the JavaScript code. Suppose the ‘url’ returns a JSON response with 500 status code. What will be logged on to console?```javascript
async function getResponse(url) {
try {
const response = await fetch(url)
try {
const data = await response.json()
if (response.ok) {
return data
} else {
return response.status
}
} catch {
return 'Network Error'
}
} catch {
return 'Response is not json'
}
}
getResponse('url').then((data) => {
console.log(data)
})
```
Consider the following JavaScript code. What will be logged on to console, if executed?```javascript
class Tshirt {
constructor(size, price) {
this.size = size
this.price = price
}
}
class LargeTshirt extends Tshirt {
constructor() {
super('large', 500)
}
}
class MediumTshirt extends Tshirt {
constructor() {
super('medium')
}
}
class Order {
constructor(item, count) {
this.item = item
this.count = count
}
totalPrice() {
try {
return this.item.price * this.count
} catch {
return 'Some Error'
}
}
}
const t1 = new MediumTshirt()
const order = new Order(t1, 5)
console.log(order.totalPrice())
```
Consider the following Vue application with JavaScript “app.js” and markup “index.html”
Consider the following Vue application with JavaScript “app.js” and markup “index.html” ```javascript
app.js
new Vue({
el: '#app',
template: `<div>
<div v-for="item in items">
Name: {{item.name}},Count:{{item.count}}, Price:
{{item.price*item.count}}
<button @click="inscreeseCount (item)">Increase Count</button>
<button @click="addToCart(item)">Add To Cart</button>
</div>
Total Amount: {{amount}} <button @click="buy"> Buy </button>
</div>`,
data: {
cart: [],
totalAmount: 50,
items: [
{ name: 'Apple', count: 1, price: 10},
{ name: 'Orange', count: 1, price: 5},
],
},
methods: {
buy() {
if (this.amount > this.totalAmount) {
console.log('Failure')
} else {
console.log('Success')
this.cart = []
}
},
inscreeseCount (item) {
item.count += 2
},
addToCart (item) {
this.cart.push(item)
},
},
computed: {
amount() {
let total = 0
this.cart.forEach((item) => {
total += item.count * item.price
})
return total
},
},
})
```
index.html
```html
<body>
<div id="app"></div>
</body>
```
Suppose the application is running on "http://127.0.0.1:8080/". If the user clicks on "Increase Count" and "Add to cart" button associated with the item name "Apple" once. Then user clicks on "Increase Count" and "Add to cart" button associated with the item name "Orange" once and then clicks on the button "Buy". What will be logged on to console?
Consider the following Vue app with markup “index.html” and JavaScript “app.js” app.js
```javascript
const Error = {
template: `<div>Result Not Found</div>`,
}
const Dashboard = {
template: `<div> This is dashboard of {{user}}</div>`,
props: ['user'],
}
const routes = [
{ path: '/dashboard/:user', component: Dashboard, props: true },
{ path: '*', component: Error },
]
const router = new VueRouter({
routes,
})
new Vue({
el: '#app',
template: `<router-view />`,
router,
})
```
index.html
```html
<body>
<div id="app"></div>
</body>
```
What will be rendered by the browser for the URL http://127.0.0.1:8080/#/dashboard/7"?
Consider the following Vue application with markup “index.html” and JavaScript “app.js” app.js
```javascript
const Home = {
template: `<div>
<slot name="navbar"> This is navbar</slot>
<slot></slot>
<slot name="footer"></slot>
</div>`,
}
new Vue({
el: '#app',
template: `<Home>
<template slot="footer">This is Footer</template>
<template slot="navbar"> This is header</template>
<div>Welcome to exam</div>
</Home>`,
components: {
Home,
},
})
```
index.html
```html
<body>
<div id="app"></div>
</body>
```
Suppose the application is running on “http://127.0.0.1:8080/”. What will be rendered by the browser for the URL “http://127.0.0.1:8080/”?
This is Footer This is Header

This is Footer This is Header Welcome to exam

This is Header This is Footer

This is Header Welcome to Exam This is Footer
Consider the following flask application. app.py
```python
from flask import Flask
from flask_caching import Cache
from time import sleep
config = {
"CACHE_TYPE": "RedisCache",
"CACHE_REDIS_HOST": "localhost",
"CACHE_REDIS_PORT": 6379,
"CACHE_REDIS_DB": 1
}
app = Flask(__name__)
app.config.from_mapping(config)
cache = Cache(app)
@app.get('/')
@cache.cached(timeout=40)
def home():
sleep(30)
return "hello world"
if __name__ == "__main__":
app.run(debug=True)
```
Suppose the application is running on "http://localhost:5000". If user1
visits the URL "http://localhost:5000" and after 3 minutes user2 visits the same URL.
What will be the approx difference between the response time for user1 and user2?
Consider the below javascript program.
```javascript
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), (i+1)*1000);
}
```
What will be the output of the above program, if executed? Also, predict the minimum number of seconds the program will take to complete the execution?
0 1 2 Minimum Time Taken: 6 seconds

0 1 2 Minimum Time Taken: 12 seconds

3 3 3 Minimum Time Taken: 12 seconds

3 3 3 Minimum Time Taken: 6 seconds
Consider the below javascript program. What will be the output of the above program, if executed?```javascript
async function func() {
const num = await Promise.resolve(2);
console.log("Second");
return num;
}
console.log("First");
func().then((data) => console.log(data));
console.log("Third");
```
First Second Third 2

First Error

First Third Second undefined

First Third Second 2

The output cannot be predicted
Consider the following JavaScript code. What will be logged on to console, if executed?```javascript
class TShirt {
constructor(size, price) {
this.size = size
this.price = price
}
}
class LargeTShirt extends TShirt {
constructor() {
super('large', 500)
}
}
class MediumTShirt extends TShirt {
constructor() {
super('medium')
}
}
class Order {
constructor(item, count) {
this.item = item
this.count = count
}
totalPrice() {
try {
return this.item.price * this.count * 2
} catch {
return 'Some Error'
}
}
}
const tl = new LargeTShirt()
const order = new Order(tl, 5)
console.log(order.totalPrice())
```
Consider the following Vue application with JavaScript “app.js” and markup “index.html”
Consider the following Vue application with JavaScript “app.js” and markup “index.html” ```javascript
app.js
new Vue({
el: '#app',
template: `<div>
<div v-for="item in items">
Name:{{item.name}},Count:{{item.count}}, Price:
{{item.price*item.count}}
<button @click="inscreeseCount(item)">Increase Count</button>
<button @click="addToCart(item)">Add To Cart</button>
</div>
Total Amount: {{amount}} <button @click="buy"> Buy </button>
</div>`,
data: {
cart: [],
totalAmount: 50,
items: [
{ name: 'Apple', count: 1, price: 10},
{ name: 'Orange', count: 1, price: 5},
],
},
methods: {
buy() {
if (this.amount > this.totalAmount) {
console.log('Failure')
} else {
console.log('Success')
this.cart = []
}
},
inscreeseCount(item) {
item.count += 2
},
addToCart(item) {
this.cart.push(item)
},
},
computed: {
amount() {
let total = 0
this.cart.forEach((item) => {
total += item.count * item.price
})
return total
},
},
})
```
index.html
```html
<body>
<div id="app"></div>
</body>
```
Suppose the application is running on "http://127.0.0.1:8080". Suppose the user clicks on "Increase Count" button associated with the item name "Apple" 5 times and then clicks on "Increase Count" button associated with the item name "Orange" once and then clicks on the button "Buy". What will be logged on to console?
Consider the following Vue app with markup “index.html” and JavaScript “app.js” app.js
```javascript
const Error = {
template: `<div>Result Not Found</div>`,
}
const Dashboard = {
template: `<div> This is dashboard of {{user}}</div>`,
props: ['user'],
}
const routes = [
{ path: '/dashboard/:user', component: Dashboard, props: true },
{ path: '*', component: Error },
]
const router = new VueRouter({
routes,
})
new Vue({
el: '#app',
template: `<router-view />`,
router,
})
```
index.html
```html
<body>
<div id="app"></div>
</body>
```
Suppose the application is running on “http://127.0.0.1:8080/”. What will be rendered by the browser for “http://127.0.0.1:8080/#/user”?
Consider the following flask application. app.py
```python
from flask import Flask
from flask_caching import Cache
from time import sleep
config = {
"CACHE_TYPE": "RedisCache",
"CACHE_REDIS_HOST": "localhost",
"CACHE_REDIS_PORT": 6379,
"CACHE_REDIS_DB": 1
}
app = Flask(__name__)
app.config.from_mapping(config)
cache = Cache(app)
@app.get('/')
@cache.cached(timeout=40)
def home():
sleep(30)
return "hello world"
if __name__ == "__main__":
app.run(debug=True)
```
Suppose the application is running on "http://localhost:5000". If user1 visits the URL "http://localhost:5000" and after 50 seconds user2 visits the same URL. What will be the approx difference between the response time for user1 and user2?
Consider the below javascript program. What will be the output of the above program, if executed?```javascript
var first = 1;
obj1 = {
'first' : 2,
'second' : function some () {
console.log(this.first);
}
}
obj2 = {
'first' : 3,
'second' : () => {
console.log("Function Invoked !!");
this.second();
}
}
obj2.second();
```
Function Invoked !! 2

Function Invoked !! 3

Function Invoked !! 1

Function Invoked !! Error

Error
Consider the below javascript program. What will be the output of the above program, if executed? Also, predict the minimum number of seconds the program will take to complete the execution?```javascript
exams = ['Jan 2023', 'May 2023', 'Sep 2023']
new Promise((rej, res) => {
let count = 2
let a = setInterval(() => {
count += 3;
const last = exams.pop();
if (count % 2) {
exams.push('May 2023')
}
else if (count % 5 == 0) {
clearInterval(a);
rej(last);
}
}, 1000)
}).then(d => console.log("Resolved", exams, d))
.catch(e => console.log("Rejected", exams, d))
```
Resolved [] Minimum Time Taken: 6 seconds

Resolved [] May 2023 Minimum Time Taken: 12 seconds

Rejected [May 2023] May 2023 Minimum Time Taken: 6 seconds

Resolved [] May 2023 Minimum Time Taken: 6 seconds

Rejected [May 2023] Minimum Time Taken: 12 seconds

Rejected [] May 2023 Minimum Time Taken: 12 seconds
Consider the following Vue application with markup “index.html” and javascript file “app.js”. Suppose you open “index.html” file in a browser, and type the text “IIT Madras” in the text box shown (after removing the previous text, if any), and hard refresh the page twice, without clicking anywhere. What will be the value shown in the text box, and the “age” placeholder, respectively?index.html:
```html
<div id = "app">
<input v-model = "name" @input = "do_something">
<p> {{age}} </p>
</div>
<script scr = "app.js"></script>
```
app.js:
```javascript
new Vue({
el : "#app",
data : {
name : "#app",
age : 0,
},
mounted () {
try {
this.name = localStorage.getItem("name").split(" ")[0];
this.age = localStorage.getItem("name").split(" ")[1];
localStorage.setItem("name",
localStorage.getItem("name").split(" ")[0] + " " + this.name);
}
catch {
this.name = "Default";
this.age = "Default";
}
},
methods : {
do_something() {
localStorage.setItem("name", this.name);
localStorage.setItem("age", this.age);
}
}
})
```
Fill in code1 & code2, which can be used in Vuex Store to update the “below_average” state variable with the objects of those students who have scored more than 50 marks. ```javascript
const store= new Vuex.Store({
state:{
student_total:0,
students:[
{
name : 'Akshay',
marks : 52
},
{
name : 'Vishwajeet',
marks : 78
},
{
name : 'Sonali',
marks : 43
}
],
below_average:[]
},
code1:{
belowAverageStudents(state){
code2
}
}
})
```
```
code1: mutations
code2: students.forEach(student=>{
if(student.marks > 50)
below_average.push(student)
})
```
```
code1: actions
code2: state.students.forEach(student=>{
if(student.mark > 50)
below_average.toppers.push(student)
})
```
```
code1: actions
code2: context.students.forEach(student=>{
if(student.marks < 55)
context.below_average.push(student)
})
```
```
code1: mutations
code2: state.students.forEach(student=>{
if(student.marks > 50)
state.below_average.push(student)
})
```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 core topics, concepts, and principles for the "Modern Application Development II" exam, along with key equations (where applicable) and Mermaid knowledge graphs to visualize relationships.
SMTP (Simple Mail Transfer Protocol)
IMAP (Internet Message Access Protocol)
POP3 (Post Office Protocol)
Webhooks:
CORS Headers:
Access-Control-Allow-Origin: Specifies allowed origins.Access-Control-Allow-Methods: Allowed HTTP methods (GET, POST, etc.).When CORS Errors Occur:
abc.com vs. def.com).http vs. https).:80 vs. :8080).abc.com vs. sub.abc.com).Mitigation:
How it Works:
| Method | Description | Pros | Cons |
|---|---|---|---|
| Short Polling | Client repeatedly asks the server for updates. | Simple to implement. | High latency, server load. |
| Long Polling | Client holds a request open until the server responds or times out. | Lower latency than short. | Complex, connection drops. |
| Webhooks | Server pushes data to a client URL when an event occurs. | Real-time, efficient. | Needs a public endpoint. |
| WebSockets | Persistent full-duplex connection between client and server. | Lowest latency, bidirectional. | Complex setup, stateful. |
Components:
Features:
Scaling:
Promise States:
Async/Await:
await pauses execution until the promise settles.try/catch.Example:
async function fetchData() {
try {
const data = await fetch(url);
return data.json();
} catch (err) {
console.error("Network Error");
}
}setTimeoutsetTimeout with var in loops:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000); // Logs 3, 3, 3 (closure issue)
}
let or an IIFE.v-for: Loop over arrays/objects.
<div v-for="(value, key, index) in obj"></div>v-model: Two-way data binding (e.g., <input v-model="name">).v-bind: Dynamically bind attributes (:class, :style).data() trigger UI updates.Computed Properties: Cached derived data.
computed: {
total() {
return this.items.reduce((sum, item) => sum + item.price, 0);
}
}Watchers: React to data changes.
watch: {
question(newVal) {
this.fetchAnswer(newVal);
}
}Dynamic Routes:
{ path: '/user/:id', component: User, props: true }
props: true passes route params as props.*): Catch-all for 404 pages.<slot></slot><slot name="header"></slot>Usage:
<Parent>
<template v-slot:header>...</template>
</Parent>Core Concepts:
Example:
mutations: {
updateStudents(state) {
state.below_average = state.students.filter(s => s.marks > 50);
}
}Types:
Mitigation:
<script> tags.< → <).Cache Types:
Cache-Control Headers:
max-age: Time in seconds before cache expires.no-store: Never cache.no-cache: Revalidate with server before using.What Not to Cache:
Flask-Caching:
Decorators:
@cache.cached(timeout=50) # Cache for 50 seconds
def home():
return "Hello"Redis as a Cache:
@cache.cached(timeout=40) caches responses for 40 seconds.Use Cases:
Connection Scaling:
javascript fetch(url) .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err)); ``javascript async function fetchData() { try { const res = await fetch(url); const data = await res.json(); return data; } catch (err) { console.error("Failed:", err); } } ``setTimeout in Loops (Closure Issue): ``javascript for (let i = 0; i < 3; i++) { // Use let instead of var setTimeout(() => console.log(i), 1000); // Logs 0, 1, 2 } ``javascript computed: { totalAmount() { return this.cart.reduce((sum, item) => sum + item.price * item.count, 0); } } ``javascript mutations: { addToCart(state, item) { state.cart.push(item); } } ``javascript const routes = [ { path: '/user/:id', component: User, props: true } ]; ``@app.route("/") @cache.cached(timeout=50) def home(): return "Cached for 50 seconds" ```
javascript import DOMPurify from 'dompurify'; const clean = DOMPurify.sanitize(userInput); ``python from flask_cors import CORS CORS(app, resources={r"/api/*": {"origins": "https://abc.com"}}) ``SMTP vs. IMAP:
CORS Errors:
Celery:
Vue Reactivity:
v-for can iterate over objects ((value, key, index) in obj).Webhooks:
XSS:
Caching:
Async/Await:
await pauses execution until the promise resolves.Flask-Caching:
@cache.cached(timeout=40) caches responses for 40 seconds.Vuex:
Final Note: Focus on asynchronous JavaScript, Vue.js reactivity, CORS/CSRF/XSS, and distributed task queues (Celery). The Mermaid graphs should help visualize relationships between concepts. Good luck! 🚀