Home / Past papers / MAD2 End Term / this paper

https://api.example.com

http://example.com/api

https://example.com:8080

https://example.com/subdir
Match the following technologies with their typical use cases: | | | |---|---| | 1. Webhooks | A. Real-time communication in chat applications | | 2. Web Sockets | B. Fetching data periodically from an API endpoint | | 3. API | C. Receiving notifications when a specific event occurs | | 4. Polling | D. Exchanging data between client and server using HTTP requests | | 5. Pub/Sub | E. Broadcasting messages to multiple subscribers simultaneously |

Consider the below javascript program.
```javascript
function parent() {
var a = 1;
function child() {
console.log(a);
}
a = 2;
return child;
}
var closure = parent();
closure();
```
What will be the output of the above program, if executed?
Consider the following JavaScript code snippet.
```javascript
// Code Snippet 1
sessionStorage.setItem('username', 'course_user');
let storedUsername = sessionStorage.getItem('username');
// Code Snippet 2
sessionStorage.removeItem('username');
let removedUsername = sessionStorage.getItem('username');
// Code Snippet 3
sessionStorage.clear();
let clearedStorage = sessionStorage.username;
```
What will be the values of 'storedUsername', 'removedUsername', and 'clearedStorage' after the execution of the above code snippets?
Consider the following javascript code
```javascript
const obj = {
num: 40,
regularFunction: function() {
return this.value;
},
arrowFunction: () => {
return this.value;
}
};
const regularResult = obj.regularFunction();
const arrowResult = obj.arrowFunction();
```
What are the values of regularResult and arrowResult?
Consider the below 2 approaches:
Approach 1:
```html
<script>
setInterval(() => document.title = "Title A", 2000)
setInterval(() => document.title = "Title B", 1000)
</script>
```
Approach 2:
```html
<script>
setInterval(() => document.title = "Title A", 1000)
setInterval(() => document.title = "Title B", 2000)
</script>
```
Choose the correct statement:
Consider the below JavaScript program.
```html
<script>
for (var i = 0; i <= 3; i++) {
setTimeout(() => console.log(i), (i+1)*1500);
}
</script>
```
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 3 Minimum time taken will be: 15 sec

1 2 3 4 Minimum time taken will be: 9 sec

3 3 3 3 Minimum time taken will be: 6 sec

4 4 4 4 Minimum time taken will be: 6 sec

```html <div :class="[isActive ? 'activeClass' : 'errorClass']"></div> ```

```html
<div :class="[{ isActive : 'activeClass' }, 'errorClass']"></div>
```
```html <div :class="[activeClass ? 'isActive' : '', 'errorClass']"></div> ```

```html
<div :class="[{'activeClass': isActive }, 'errorClass']"></div>
```
Consider the following Vue.js 2 component using CDN. After entering "Orange" in the input box and clicking the "Add" button, what will be seen in the browser?```html
<div id="app">
<input v-model="newItem" placeholder="Add an item" />
<button @click="addItem">Add</button>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ index + 1 }}. {{ item }}
</li>
</ul>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script>
new Vue({
el: '#app',
data: {
newItem: '',
items: ['Apple', 'Banana']
},
methods: {
addItem() {
if (this.newItem) {
this.items.push(this.newItem, this.newItem);
this.newItem = '';
}
}
}
});
</script>
```
Consider the following javascript code running on browser What will be the output in the browser console?```javascript
localStorage.setItem('counter', '0');
sessionStorage.setItem('total', '5');
for (let i = 0; i < 3; i++) {
let counter = localStorage.getItem('counter');
let total = sessionStorage.getItem('total');
counter += 2;
total *= 2;
localStorage.setItem('counter', counter);
sessionStorage.setItem('total', total);
}
sessionStorage.clear();
console.log(localStorage.getItem('counter'));
console.log(sessionStorage.getItem('total'));
```
Consider the below JavaScript program.
```javascript
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks`);
}
}
const d = new Dog('Rex');
d.speak();
console.log(d.__proto__ === Dog.prototype);
console.log(d.__proto__.__proto__ === Animal.prototype);
```
What will be the output of the above program?
Consider the below flask application. 1. First visit 2. Second visit after 2 minutes and 30 seconds 3. Third visit after 1 minute from the second visit What will be the approximate difference in response times between the first and third requests?```python
from flask import Flask
from flask_caching import Cache
from time import sleep
config = {
"CACHE_TYPE": "SimpleCache",
"CACHE_DEFAULT_TIMEOUT": 180
}
app = Flask(__name__)
app.config.from_mapping(config)
cache = Cache(app)
@cache.memoize(timeout=180)
def get_data(param):
sleep(5)
return f"Data for {param}"
@app.route('/data/<param>')
def data(param):
result = get_data(param)
return f"Result: {result}"
if __name__ == '__main__':
app.run(debug=True)
```
If the application is running on "http://127.0.0.1:5000" and the user visits the URL "http://127.0.0.1:5000/data/test" three times in the following sequence:
Consider the below JavaScript program.
Consider the below JavaScript program. What will be the output of the above program?```javascript
new Promise((resolve, reject) => {
const num = 0.6;
if (num > 0.5) {
resolve(num);
} else {
reject(num);
}
})
.then(data => {
console.log("Step 1:", data);
if (data > 0.75) {
return data * 2;
} else {
return Promise.reject(new Error("Less than 0.75"));
}
})
.then(data => {
console.log("Step 2:", data);
return data + 5;
})
.catch(error => {
console.log("Step 3:", error.message);
if (error.message === "Less than 0.75") {
return 1;
} else {
throw error;
}
});
```
```javascript
})
.then(data => {
console.log("Step 4:", data);
if (data === 1) {
throw new Error("Fallback value");
} else {
return data * 3;
}
})
.catch(error => {
console.log("Step 5:", error.message);
return "Error handled";
})
.finally(() => {
console.log("Step 6: Finally block executed");
})
```
In a Vue CLI project with Vuex, you have the following configuration:
In a Vue CLI project with Vuex, you have the following configuration: src/store/index.js:
```javascript
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
value: "",
},
mutations: {
setValue(state, payload) {
state.value = payload;
}
},
actions: {
async fetchValue({ commit }) {
// Simulate async API call
const response = await new Promise(resolve => setTimeout(() =>
resolve('API Value'), 500));
commit('setValue', response);
}
}
});
```
src/App.vue:
```html
<template>
<div>
<p>{{ value }}</p>
<button @click="updateValue">Update Value</button>
</div>
</template>
<script>
export default {
computed: {
value() {
return this.$store.state.value;
},
},
methods: {
async updateValue() {
await this.$store.dispatch('fetchValue');
},
},
};
</script>
```
After running "npm run serve", if you click the "Update Value" button, what will be displayed in the `<p>` tag?
API Value

"" ""

undefined

null

Consider the below JavaScript code.
```javascript
async function newFetch(url) {
try {
console.log(url)
const res = await fetch(url)
if (!res.ok) {
throw new Error(`HTTP Error: ${res.status}`)
}
try {
const data = await res.json()
console.log(data)
} catch {
throw new Error('Error')
}
} catch {
throw new Error('Data is not JSON serializable')
}
}
newFetch('https://example.com/api/users/23').catch((err) => {
console.error(err)
})
```
Suppose the API URL "https://example.com/api/users/23" returns a valid HTML output. What will be logged on to console?
Consider the following Flask application with Redis caching. Redis is running
normally on port 6379.
```python
from flask import Flask, jsonify
from flask_caching import Cache
app = Flask(__name__)
app.config['CACHE_TYPE'] = 'redis'
app.config['CACHE_REDIS_HOST'] = 'localhost'
app.config['CACHE_REDIS_PORT'] = 6379
cache = Cache(app)
def compute_value(x, y):
result = x * y
return result
@app.route('/compute/<int:x>/<int:y>')
@cache.cached(timeout=60, key_prefix='compute')
def compute(x, y):
result = compute_value(x, y)
return jsonify({'result': result})
if __name__ == '__main__':
app.run(debug=True, port=5000)
```
Options:
Options: Based on the above data, answer the given subquestions.



Suppose the application is running on port 8080. What will be rendered inside router-view for the URL "http://127.0.0.1:8080/#/profile/1235"?

Suppose the application is running on port 8080. What will be rendered inside router-view for the URL "http://127.0.0.1:8080/#/profile/Arnav"?
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 essential for the "Modern Application Development II" exam, along with a Mermaid knowledge graph to visualize relationships.
CSRF (Cross-Site Request Forgery)
SameSite cookies, or double-submit cookies.CORS (Cross-Origin Resource Sharing)
Allowed Origins:
https://example.com → https://example.com/subdir).Access-Control-Allow-Origin header.OPTIONS request for non-simple methods (e.g., PUT, custom headers).Same-Origin Policy (SOP)
Core Flow:
Dispatch Action → Commit Mutation → State Change → Reactivity
store.dispatch().store.commit().store.state.Async Workflow Example:
actions: {
async fetchData({ commit }) {
const response = await api.call();
commit('SET_DATA', response); // Mutation updates state
}
}Job Queues (Scalability)
Order for Async Tasks:
Queue Job → Process Job → Save Result → Callback/NotificationCelery Use Cases:
Closures
Example:
function outer() {
let x = 10;
return function inner() { console.log(x); }; // Logs 10
}Hoisting
var: Hoisted with undefined; initialization stays in place.let/const: Hoisted but uninitialized (Temporal Dead Zone).this Binding
this depends on call context.this (inherits from parent scope).Example:
const obj = {
val: 42,
regular: function() { return this.val; }, // 42
arrow: () => this.val // undefined (global/window)
};Event Loop & Timers
setTimeout/setInterval delays are minimum guarantees (not exact).Example:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000); // Logs 3, 3, 3 (closure over `i`)
}let or IIFE to capture i per iteration.Promises & Async/Await
.then() for success, .catch() for errors.Async/Await: Syntactic sugar for promises.
async function fetchData() {
try {
const data = await api.call();
console.log(data);
} catch (err) {
console.error(err);
}
}localStorage | Per-origin | Persists across sessions | ~5MB | | sessionStorage | Per-tab | Cleared on tab close | ~5MB | | IndexedDB | Per-origin | Persists | ~50MB+ |Server-Side Caching
Redis: In-memory key-value store (supports strings, lists, sets, hashes).
Flask-Caching:
@cache.cached(timeout=60) (caches response).Example:
@app.route('/data')
@cache.cached(timeout=50, key_prefix='data')
def get_data():
return expensive_computation()Cache-Control | Directives (e.g., max-age=3600, no-store) | | Expires | Absolute expiry time (legacy) | | ETag | Version identifier for validation |Reactivity
v-model: Two-way binding (e.g., <input v-model="msg">).v-for: Render lists (:key required for efficiency).Vuex Binding in Templates
Dynamic class binding:
<div :class="['errorClass', isActive ? 'activeClass' : '']"></div>Vue Router
/profile/:id).Example:
const routes = [
{ path: '/profile/:id', component: Profile },
{ path: '*', component: NotFound }
];Pub/Sub Model
Example:
# Publisher
redis.publish("channel", "message")# Subscriber pubsub = redis.pubsub() pubsub.subscribe("channel") for message in pubsub.listen(): print(message) ```
Promise Error Propagation
.then() propagate to .catch().Example:
fetch(url)
.then(res => res.json())
.catch(err => console.error("Failed:", err));Async/Await Errors
Use try/catch:
async function loadData() {
try {
const data = await fetchData();
} catch (err) {
console.error(err);
}
}plaintext Dispatch Action → Commit Mutation → State Change ``plaintext Queue Job → Process Job → Save Result → Invoke Callback ``javascript for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); // Logs 0, 1, 2 } ``python @app.route('/data') @cache.cached(timeout=60, key_prefix='data') def get_data(): return expensive_computation() ``python from flask_wtf.csrf import CSRFProtect app = Flask(__name__) CSRFProtect(app) ``python @app.route('/stream') def stream(): def generate(): while True: yield f"data: {datetime.now()}\n\n" time.sleep(1) return Response(generate(), mimetype='text/event-stream') ``python @app.route('/webhook', methods=['POST']) def webhook(): data = request.json print("Received:", data) return 'OK', 200 ``Cache-Control, ETag) and Redis basics..catch() in promises.