Home / MAD2 / Week 2 / Real questions
60 questions pulled from past papers whose wording matches this week's topics, newest first, duplicates removed. Pick your answers, then press Check answers. Figures and answer keys are the originals.
and JavaScript
for a Vue application: File: index.html
File: app.js
Suppose the application is running on
, and the user visits the URL:
What will be rendered by the browser? [NOTE:
is divided in two images, consider them as one file content.]

index.html
app.js
```html
<div id="app">
<router-view></router-view>
</div>
```
```javascript
const Flights = {
template: `<h2>{{ result }}</h2>`,
data() {
return {
routes: [
{ city: "Delhi", connectedTo: ["Mumbai", "Pune"] },
{ city: "Indore", connectedTo: ["Bhopal", "Jaipur"] },
{ city: "Raipur", connectedTo: ["Nagpur", "Hyderabad"] },
{ city: "Rewa", connectedTo: ["Delhi", "Indore", "Raipur"] }
],
result: ""
};
},
created() {
const destination = this.$route.params.city.toLowerCase();
for (let i = 0; i < this.routes.length; i++) {
const connections = this.routes[i].connectedTo;
for (let j = 0; j < connections.length; j++) {
if (connections[j].toLowerCase() === destination) {
this.result = this.routes[i].city;
break;
}
}
if (this.result) {
break;
}
}
}
};
```
```
http://localhost:8080
```
```
http://localhost:8080/#/raipur
```
app.js
```javascript
const router = new VueRouter({
routes: [
{
path: "/:city",
component: Flights
}
]
});
new Vue({
el: "#app",
router
});
```
The
getter is used in a Vue component as shown below:
Now suppose the Vuex getter
is removed, while the temperature state continues to be updated through Vuex mutations. Which of the following implementations correctly recreates
in the component so that it automatically reacts whenever the Vuex
changes?```javascript
const store = new Vuex.Store({
state: {
temperature: 30
},
getters: {
weatherStatus(state) {
return state.temperature >= 35 ? "Hot" : "Normal"
}
}
})
```
weatherStatus
```javascript
computed: {
weatherStatus() {
return this.$store.getters.weatherStatus
}
}
```
weatherStatus
weatherStatus
temperature
```javascript
computed: {
weatherStatus() {
return this.$store.state.temperature >= 35
? "Hot"
: "Normal"
}
}
```
```javascript
watch: {
weatherStatus() {
return this.$store.state.temperature >= 35
? "Hot"
: "Normal"
}
}
```
```javascript
methods: {
weatherStatus() {
this.$store.state.temperature >= 35
? "Hot"
: "Normal"
}
}
```
```javascript
watch: {
weatherStatus() {
return this.$store.state.temperature >= 35
}
}
```
```javascript
const user = {
id: 1,
profile: {
name: "Riya",
address: {
city: "Pune",
zip: "411001"
}
}
};
const {
profile: {
name,
address: { city, state = "Maharashtra" }
},
role = "guest",
profile
} = user;
console.log(name, city, state, role);
console.log(profile);
```

Riya Pune Maharashtra guest
```
{ name: "Riya", address: { city: "Pune", zip: "411001" } }
```

Riya Pune Maharashtra guest undefined

```
undefined undefined Maharashtra guest
```
```json
{ "name": "Riya", "address": { ...} }
```
, because you cannot destructure profile into nested variables and also assign it to a plain variable profile in the same statement.SyntaxError
What is the order of console output?```javascript
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");
Promise.resolve().then(() => {
console.log("5");
setTimeout(() => console.log("6"), 0);
});
```
```javascript
const calculator = {
value: 10,
add(a, b) {
return this.value + a + b;
}
};
const rawAdd = calculator.add;
const boundAdd = calculator.add.bind({ value: 100 }, 5);
console.log(rawAdd(1, 2));
console.log(boundAdd(10));
console.log(calculator.add.apply({ value: 50 }, [1, 2]));
```
evaluates to 
``` rawAdd(1, 2) ``` NaN
evaluates to 
``` boundAdd(10) ``` 115
evaluates to 
```
calculator.add.apply({ value: 50 }, [1, 2])
```
53
throws a 
```
calculator.add.apply({ value: 50 }, [1, 2])
```
TypeError
A client first accesses
and then tries to access
. Which of the following statements are correct?```python
from flask import Flask, jsonify
from flask_jwt_extended import JWTManager, create_access_token, \
jwt_required
app = Flask(__name__)
app.config["JWT_SECRET_KEY"] = "secret"
jwt = JWTManager(app)
@app.route("/token")
def token():
access_token = create_access_token(identity="Ravi")
return jsonify(access_token=access_token)
@app.route("/dashboard")
@jwt_required()
def dashboard():
return jsonify(message="Dashboard Access Granted")
```
/token
/dashboard
can only be accessed if a valid JWT token is sent with the request./dashboard
header while accessing protected routes.Authorization
is automatically stored by Flask and reused for future requests./token
about its output:

TRUE
```javascript
const value = "global";
const obj = {
value: "objectValue",
regularMethod: function () {
console.log(this.value);
},
arrowMethod: () => {
console.log(this.value);
},
nested: {
value: "nestedValue",
regularInNested: function () {
console.log(this.value);
},
arrowInNested: () => {
console.log(this.value);
},
},
delayedRegular: function () {
setTimeout(function () {
console.log(this.value);
}, 100);
},
delayedArrow: function () {
setTimeout(() => {
console.log(this.value);
}, 100);
},
};
```
```javascript
obj.regularMethod();
obj.arrowMethod();
obj.nested.regularInNested();
obj.nested.arrowInNested();
obj.delayedRegular();
obj.delayedArrow();
```
logs "objectValue"``` obj.regularMethod() ```
logs "objectValue"``` obj.arrowMethod() ```
logs "nestedValue"``` obj.nested.regularInNested() ```
logs 
``` obj.nested.arrowInNested() ``` undefined
logs "objectValue"``` obj.delayedArrow() ```
logs "objectValue"``` obj.delayedRegular() ```
Based on the above data, answer the given subquestions.
pauses the execution of the
function until the Promise resolves.await ``` display() ```
immediately returns the resolved string "Data Received".``` fetchData() ```
functions cannot return a
.async Promise
would cause
to store a
object instead of the resolved value.await result Promise
Called from a view/script:
Checked immediately, right after delay() — worker hasn't processed it yet:
Called separately, after waiting for the worker to finish the task:


10 **and** <class 'int'>

A task ID string and <class 'celery.result.AsyncResult'>

None and <class 'NoneType'>

10 and <class 'celery.result.AsyncResult'>
component's method:

component, what expression correctly reads the
value from the URL after navigation?SearchResults keyword
file:index.html
Select all statements that correctly describe the console output:```javascript
new Vue({
el: "#app",
data: {
message: "Hello"
},
beforeCreate() {
console.log("1:", this.message);
},
created() {
console.log("2:", this.message);
},
beforeMount() {
console.log("3:", this.$el.textContent);
},
mounted() {
console.log("4:", this.$el.textContent);
}
});
```
```html
<div id="app">{{ message }}</div>
```
undefined

hello

hello

hello
Assume the API returns:
Complete the missing code so that all course names are rendered correctly. Which of the following code snippets can correctly replace
?```html
<div id="app">
<ul>
<!-- Missing Code -->
</ul>
</div>
<script>
new Vue({
el: '#app',
data: {
courses: []
},
async mounted() {
const response = await fetch('https://example.com/api/courses')
this.courses = await response.json()
}
})
</script>
```
```json
[
{ "id": 1, "name": "MAD-2" },
{ "id": 2, "name": "DBMS" }
]
```
```html
<!-- Missing Code -->
```
```html
<li v-for="course in courses" :key="course.id">
{{ course.name }}
</li>
```
```html
<li v-for="(course, index) in courses" :key="index">
{{ course.name }}
</li>
```
```html
<li v-if="course in courses">
{{ course.name }}
</li>
```
```html
<li v-for="courses in course">
{{ courses.name }}
</li>
```
would make the task run faster by giving it more CPU cores.``` .delay() ```

```javascript
const products = [
{ name: "Laptop", price: 1200, inStock: true },
{ name: "Mouse", price: 25, inStock: false },
{ name: "Keyboard", price: 75, inStock: true },
{ name: "Monitor", price: 300, inStock: false }
];
const result = products.filter(item => item.inStock && item.price < 500);
```
```json
{ "name": "Keyboard", "price": 75, "inStock": true }
```
```
[[{ name: "Laptop", price: 1200, inStock: true }, { name: "Keyboard", price: 75, inStock: true }]]
```
```
[[{ name: "Keyboard", price: 75, inStock: true }]]
```
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: lightblue;
margin: 10px;
border: 1px solid black;
}
.container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: flex-start;
align-items: flex-start;
align-content: flex-start;
height: 300px;
border: 2px solid red;
}
</style>
</head>
<body>
<div class="container">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
<div class="box">Box 4</div>
<div class="box">Box 5</div>
<div class="box">Box 6</div>
</div>
</body>
</html>
```
Based on the above data, answer the given subquestions.
gets its own
binding.```javascript
setTimeout(function(){})
```
this
from the surrounding lexical scope.this
automatically binds
to the surrounding object.``` setTimeout ``` this
in
, it will print "Rahul".``` setTimeout ``` ``` normalFunction ```
component

is defined as a
while
is defined as an
?``` increment ``` mutation ``` incrementAsync ``` action
Why does this fail?```javascript
const heading = document.querySelector("h1")
```
document
works only after using 
```javascript document.querySelector() ``` ``` setTimeout() ```

```javascript
async function getUser() {
const response = await fetch("https://api.example.com/user/1");
if (!response.ok) {
throw new Error("Request failed");
}
const data = await response.json();
console.log(data.name);
}
getUser();
```
should use POST method by default, not GET``` fetch() ```
and
will throw errors because response is a 
response.ok ``` response.json() ``` Promise
cannot be called on a
response; use
instead``` .json() ``` fetch ``` .text() ```
does not work inside
functions``` fetch() ``` async

```javascript
console.log("A")
setTimeout(() => console.log("B"), 0)
Promise.resolve().then(() => console.log("C"))
console.log("D")
```
What happens to
?```javascript
const settings = { theme: "light", layout: { sidebar: true } }
const copy = { ...settings }
copy.layout.sidebar = false
```
```
settings.layout.sidebar
```
because spread syntax always creates a deep copy.true
because the nested object is still shared in a shallow copy.false
because
is removed from the original object.undefined layout
What will be the output of above code on the browser’s console?```javascript
async function fetchData() {
console.log("1");
const result = await new Promise((resolve) => {
setTimeout(() => resolve("done"), 1000);
console.log("2");
});
console.log("3:", result);
}
fetchData();
console.log("4");
```
```
mutations: {
ADD_TO_CART(state, product) {
state.cart.push(product)
}
}
```
```javascript
mutations: {
ADD_TO_CART(state, product) {
setTimeout(() => {
state.cart.push(product)
}, 500)
}
}
```
```javascript
mutations: {
ADD_TO_CART(state, product) {
fetch('/api/add').then(() => {
state.cart.push(product)
})
}
}
```
```javascript
mutations: {
ADD_TO_CART(state, product) {
Promise.resolve().then(() => {
state.cart.push(product)
})
}
}
```
Which of the following statements are correct?```html
<div class="card" data-price="499">
<span id="title">Vue Book</span>
</div>
```
returns
.```javascript
document.querySelector(".card").dataset.price
```
"499"
converts the value to numeric
.```javascript
Number(document.querySelector(".card").dataset.price)
```
499
can read the visible text
.```javascript
document.getElementById("title").innerText
```
"Vue Book"
returns a single element, not a collection.```javascript
document.querySelectorAll(".card")
```
header.``` Authorization: Bearer <token> ```
can read the identity stored in the token.``` get_jwt_identity() ```
inside a parent route, •
, •
inside a method. Which statements are correct?children
```
{ path: '*', component: NotFound }
```
```javascript
this.$router.go(-1)
```
can be used to organize nested routes under a parent route.children
can act as a fallback for unknown routes.*
tries to go back one step in browser history.```javascript this.$router.go(-1) ```

```javascript
const store = new Vuex.Store({
state: {
discount: 10,
products: [
{name: 'apple',
price: 120
},
{
name: 'banana',
price: 60
}
]
},
mutations: {
reducePrice: state=>{
// Code1
}
}
})
```
```javascript
this.$store.state.products.forEach(product => { product.price -= (state.discount)/100*product.price; })
```
```javascript
state.products.forEach(product => { product.price -= (state.discount)/100*product.price;})
```
```javascript
commit.products.forEach(product => { product.price -= (state.discount)/100*product.price;})
```
```javascript
dispatch.products.forEach(product => { product.price -= (state.discount)/100*product.price;})
```
Component.vue
After triggering all three methods (
,
and
) one by one, which of the following statements is correct?```javascript
const store = new Vuex.Store({
state: {
cart: []
},
mutations: {
ADD_TO_CART(state, product) {
state.cart.push(product)
}
},
actions: {
addToCart({ commit }, product) {
setTimeout(() => {
commit('ADD_TO_CART', product)
}, 500)
}
}
})
```
```javascript
methods: {
addItem_A(product) {
this.$store.commit('ADD_TO_CART', product)
},
addItem_B(product) {
this.$store.dispatch('addToCart', product)
},
addItem_C(product) {
this.$store.state.cart.push(product)
}
}
```
addItem_A
addItem_B
addItem_C
and
will appear in Vue DevTools mutation history, but
will appear with a delay.addItem_A addItem_B addItem_B
will update the cart because mutations cannot be called directly from components.addItem_B
will throw an error because Vuex prevents direct state modification.addItem_C
What will be logged in the console when this component first loads?```html
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
data() {
return {
message: ""
};
},
beforeCreate() {
console.log("A:", this.message);
},
created() {
console.log("B:", this.message);
this.message = "Hello from Vue!";
},
mounted() {
console.log("C:", document.querySelector("p").textContent);
}
};
</script>
```
A: "" → B: Hello from Vue! → C: Hello from Vue!

A: undefined -> B: Hello from Vue! -> C: Hello from Vue!

A: undefined → B: "" → C: Hello from Vue!

A: undefined → B: undefined → C: Hello from Vue!

A: "" -> B: "" -> C: Hello from Vue!
file2: ProfileComponent.vue


``` this.$router.params.username ```

``` this.$route.params.username ```

``` this.$router.query.username ```

``` this.$route.query.username ```
Which of the following statements are correct?```javascript console.log(typeof setTimeout) console.log(typeof document) ```
."function"
."undefined"
will work in Browser by default because V8 provides the DOM.```javascript document.querySelector() ```

```javascript items.forEach(item => console.log(item)) ```

```javascript setTimeout(showMessage, 1000) ```

```javascript const result = showMessage() ```

```javascript
button.addEventListener("click", handleClick)
```
```javascript
console.log("1")
setTimeout(() => {
console.log("2")
setTimeout(() => console.log("3"), 0)
}, 0)
console.log("4")
```
What will be the output of the above code on the browsers’ console?```javascript
const obj1 = {
prop1: "Germany",
prop2: "Spain",
prop3: 50,
method1: function(){
console.log(`The European countries are ${this.prop2} and ${this.prop1}.`)
},
method2: function(param){
let value = param + 2*this.prop3;
console.log(`The final numerical value is: ${value}.`)
}
}
const obj2 = {
prop1: "England",
prop2: "Italy",
prop3: "25"
}
const func1 = obj1.method1;
const func2 = obj1.method2;
func1.apply(obj1);
func2.bind(obj2)(15);
```
and inside the child:
Which statements are correct?```html
<child-box :message="parentMsg" @reply="handleReply"></child-box>
```
```javascript
this.$emit('reply', 'ok')
```
flows from parent to child through props.message
is a custom event sent from child to parent.reply
to update the parent source of truth.message
changes in the parent, the child can receive the updated prop value.parentMsg
Why does the
value not update correctly when the button is clicked?```html
<div id="app">
<p>{{ message }}</p>
<button @click="changeMessage">Click</button>
</div>
<script>
new Vue({
el: '#app',
data: {
message: "Hello"
},
methods: {
changeMessage: () => {
this.message = "Updated"
}
}
})
</script>
```
message
should be used instead of 
v-on ``` @click ```

this
should be a function in all Vue instancesdata
Which of the following statements is/are correct?```javascript
class MathUtils {
static add(a, b) {
return a + b;
}
multiply(a, b) {
return a * b;
}
}
const utils = new MathUtils();
```
will work correctly and return 8``` MathUtils.add(5, 3) ```
will work correctly and return 8``` utils.add(5, 3) ```
will work correctly and return 15``` utils.multiply(5, 3) ```
will work correctly and return 15``` MathUtils.multiply(5, 3) ```
What will be the output of the above code on the browsers’ console?```javascript
var var1 = 25;
var var2 = 35;
const obj = {
var1: 45,
var2: 55,
func1: function(){
console.log(`You are accessing: ${var1}`)
},
func2: () => {
console.log(`You are accessing: ${this.var2}`)
},
}
obj.func1()
obj.func2()
```
What will be the output of the above code on the browsers’ console?```javascript
function first() {
console.log("First start");
setTimeout(function () {
console.log("First timeout");
}, 0);
console.log("First end");
}
function second() {
console.log("Second start");
setTimeout(function () {
console.log("Second timeout");
}, 0);
}
console.log("Program start");
first();
second();
console.log("Program end");
```
In another file app.js, which of the following import statements will correctly import both strikeRate and playerName ? ( Assume both files are in the same directory )```javascript
export const strikeRate = (runs, balls) => {
return (runs / balls) * 100;
};
export const playerName = "Virat Kohli";
```
```javascript import strikeRate, playerName from "./battingStats.js"; ```

```javascript
import { strikeRate, playerName } from "./battingStats.js";
```
```javascript import * as stats from "./battingStats.js"; ```

```javascript
require("./battingStats.js");
```
What will be the output of the above program?```javascript
const promise = new Promise((resolve, reject) => {
resolve('Success!');
reject('Error!');
});
promise.then(console.log).catch(console.log);
```
If the addItemAsync action is dispatched with the item 'React', what will be the state of items after 2 seconds?```javascript
const store = new Vuex.Store({
state: {
items: ['Angular', 'Vue'],
},
mutations: {
addItem(state, item) {
state.items.push(item);
},
},
actions: {
addItemAsync({ commit }, item) {
setTimeout(() => {
commit('addItem', item);
}, 500);
},
},
});
```
What will be the output of the above program on a browser's console?```javascript
class Animal {
constructor(type) {
this.type = type;
}
speak() {
console.log(`${this.type} makes a sound`);
}
getType() {
return `This is a ${this.type}`;
}
}
class Dog extends Animal {
constructor(type, breed) {
super(type);
this.breed = breed;
}
speak() {
console.log(`${this.type} ${this.breed} barks`);
}
}
const myDog = new Dog('Dog', 'Labrador');
myDog.speak();
console.log(myDog.getType());
console.log(myDog instanceof Dog);
console.log(myDog instanceof Animal);
console.log(Dog.prototype.__proto__ === Animal.prototype);
```
``` Dog Labrador barks This is a Dog true true true ```

``` Dog makes a sound This is a Dog Labrador true false true ```

``` Dog Labrador barks This is a Dog Labrador true true false ```

``` Dog Labrador barks This is a Dog false true true ```
If requests for user IDs 1, 2, 1 are made within 5 minutes, what's the total response time?```python
from flask import Flask
from flask_caching import Cache
import time
app = Flask(__name__)
app.config['CACHE_TYPE'] = 'SimpleCache'
app.config['CACHE_DEFAULT_TIMEOUT'] = 300
cache = Cache(app)
@cache.memoize(timeout=300)
def compute_data(user_id):
time.sleep(5)
return f"Data for user {user_id}"
@app.route('/api/info/<int:user_id>')
def get_info(user_id):
return compute_data(user_id)
```
What will be printed in the console when the above code is executed?```javascript
const CAPACITY = 75;
const TOTAL_PEOPLE = 213;
function allocatePeople() {
return new Promise((resolve, reject) => {
let slots = [0, 0, 0];
let remaining = TOTAL_PEOPLE;
for (let i = 0; i < slots.length; i++) {
if (remaining >= CAPACITY) {
slots[i] = CAPACITY;
remaining -= CAPACITY;
} else {
slots[i] = remaining;
remaining = 0;
}
}
reject(slots);
});
}
async function startAllocation() {
try {
const result = await allocatePeople();
console.log("Passed " + JSON.stringify(result));
} catch (error) {
console.log("Failed " + JSON.stringify(error));
}
}
startAllocation();
```
Suppose the application is running on http://127.0.0.1:8080. What will be rendered by the browser?File: index.html
```html
<div id="app"></div>
<script src="script.js"></script>
```
File: script.js
```javascript
new Vue({
el: '#app',
template: `<div>
Status: {{status}}<br>
Value: {{value}}
</div>`,
data: {
status: "Initial",
value: 10,
},
beforeCreate() {
this.status = this.status + " -> Created"
this.value = this.value + 5
},
beforeMount() {
this.status = this.status + " -> Ready"
this.value = this.value - 2
},
created() {
this.status = this.status + " -> Mounted"
this.value = this.value * 2
},
mounted() {
this.status = this.status + " -> Done"
this.value = this.value / 2
},
})
```
Three requests are made to this application: GET /api/open (no authentication headers)1. GET /api/secure (no authentication headers)2. GET /api/superuser with valid authentication token but user has role 'basic' (not 'superuser')3. What will be the response status codes for these requests, respectively?```python
@app.route('/api/open')
def open_endpoint():
return jsonify({'message': 'Open access', 'status': 'success'})
@app.route('/api/secure')
@auth_required('token')
def secure_endpoint():
return jsonify({'message': 'Secure access', 'status': 'authenticated'})
@app.route('/api/superuser')
@auth_required('token')
@roles_required('superuser')
def superuser_endpoint():
return jsonify({'message': 'Superuser access', 'status': 'authorized'})
```
```javascript
const obj = {
value: 100,
outerFunc: function () {
const innerFunc = () => {
console.log(this.value);
};
return innerFunc;
},
otherFunc: function () {
console.log(this.value);
}
};
const func1 = obj.outerFunc();
const func2 = obj.outerFunc;
const func3 = obj.otherFunc;
func1(); // #1
func2()(); // #2
func3(); // #3
```
If a user visit index.html at 10:10:10 AM, what will be logged in the console?

app.py:
```python
from flask import Flask, jsonify
from datetime import datetime
import time
app = Flask(__name__)
@app.route('/')
def home():
time.sleep(10)
return jsonify(datetime.now().second), 200, \
{'Access-Control-Allow-Origin': '*'}
@app.route('/profile')
def profile():
time.sleep(30)
return jsonify(datetime.now().second), 200, \
{'Access-Control-Allow-Origin': '*'}
if __name__ == "__main__":
app.run(debug=True)
```
index.html:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<script>
function test() {
const res1 = fetch('http://127.0.0.1:5000')
const res2 = fetch('http://127.0.0.1:5000/profile')
res1
.then((res) => {
return res.json()
})
.then((data) => {
console.log(data)
})
res2
.then((res) => {
return res.json()
})
.then((data) => {
console.log(data)
})
}
test()
</script>
</body>
</html>
```
Which of the following options correctly fills Line X and Line Y so that the application works as expected?```html
<div id="app">
<h3>Trip Essentials</h3>
<ul>
<li v-for="item in packedItems" :key="item">
{{ item }}
</li>
</ul>
<button @click="packItem('Passport')">Pack Passport</button>
</div>
<script>
const store = new Vuex.Store({
state: {
packed: []
},
mutations: {
ADD_ITEM(state, item) {
state.packed.push(item);
}
}
});
new Vue({
el: "#app",
store,
computed: {
/* Line X */
},
methods: {
packItem(item) {
/* Line Y */
}
}
});
</script>
```
```javascript
// Line X
packedItems() {
return this.store.state.packed;
}
// Line Y
this.store.commit("ADD_ITEM", item);
```
```javascript
// Line X
packedItems() {
return this.$store.state.packed;
}
// Line Y
this.$store.commit("ADD_ITEM", item);
```
```javascript
// Line X
packedItems() {
return this.$store.packed;
}
// Line Y
this.commit("ADD_ITEM", item);
```
```javascript
// Line X
packedItems: this.$store.state.packed
// Line Y
this.$store.dispatch("ADD_ITEM", item);
```
You are developing an analytics platform using Flask and Flask-JWT-Extended. A user sends a POST request to
with:
. Then tries to access
. Which of the following statements are correct?```python
from flask import Flask, jsonify, request
from flask_jwt_extended import JWTManager, create_access_token, \
jwt_required, get_jwt_identity
app = Flask(__name__)
app.config["JWT_SECRET_KEY"] = "secret"
jwt = JWTManager(app)
@app.route("/login", methods=["POST"])
def login():
username = request.json.get("username")
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token)
@app.route("/stats")
@jwt_required()
def stats():
current_user = get_jwt_identity()
return jsonify(message=f"Welcome {current_user}")
```
/login
```json
{ "username": "Jassi" }
```
/stats
route will return "Welcome Jassi" only if a valid JWT token is sent in the Authorization header/stats
will result in an unauthorized error/stats

/stats
Which of the following statements correctly explain why the Assignments page takes time to load?```javascript
export default {
data() {
return {
assignments: []
}
},
created() {
fetch("/api/assignments")
.then(res => res.json())
.then(data => {
this.assignments = data;
});
}
}
```
Based on the above data, answer the given subquestions.
method is modified as follows:
What will happen when the button is clicked?```
calculate()
```
```
calculate() {
this.a = this.a + 1;
}
```
will not run again``` bigNumber() ```
will run again because a dependency changed``` bigNumber() ```
Assume the Vue application is loaded at the url
. The user then clicks on the Item 2 router link. Based on the above data, answer the given subquestions.
lifecycle hook triggered in this scenario?``` updated() ```
Backend: app.py

```javascript
methods: {
async login() {
const response = await fetch('/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: this.email, password: this.password })
});
const data = await response.json();
console.log(data.message);
}
}
```
```python
@app.route('/login', methods=['POST'])
def login():
email = request.json['email']
password = request.json['password']
query = f"SELECT * FROM users WHERE email = '{email}'" \
f" AND password = '{password}'"
result = db.execute(query)
if result:
return jsonify({"message": "Login successful"})
return jsonify({"message": "Invalid credentials"})
```
What will be printed on the console first?```javascript
const store = new Vuex.Store({
state: { todos: [] },
mutations: {
addTodo(state, todo) { state.todos.push(todo) }
},
actions: {
async addTodoAsync({ commit }, todo) {
commit('addTodo', { text: todo, done: false });
return 'done';
}
}
});
store.dispatch('addTodoAsync', 'Learn Vuex')
.then(msg => console.log(msg));
console.log(store.state.todos.length);
```
If the developer changed the template to use displayedProducts instead of filteredProducts, What would be the most likely issue?```javascript
const ProductList = {
template: `<div>{{ filteredProducts }}</div>`,
data() {
return {
allProducts: [
{ id: 1, name: 'Laptop', category: 'electronics' },
{ id: 2, name: 'Novel', category: 'books' },
{ id: 3, name: 'Phone', category: 'electronics' }
],
displayedProducts: null
}
},
computed: {
filteredProducts() {
return this.allProducts.filter(p => p.category ===
this.$route.params.category);
}
},
watch: {
'$route.params.category': function(newCategory) {
this.displayedProducts = this.filteredProducts;
}
}
}
```
What will be printed to the console?```javascript
function task(value) {
return new Promise((resolve, reject) => {
if (value > 5) {
resolve(value + 2);
} else {
reject(value - 2);
}
});
}
async function execute() {
try {
const a = await task(7);
const b = await task(a - 4);
return a + b;
} catch (err) {
return err;
}
}
execute().then(result => console.log(result));
```
Suppose the following mutation is committed:store.commit("updateUserStatus", { userId: 2, status: "active" });. Which of the following statements is TRUE after this mutation is executed?```javascript
const store = new Vuex.Store({
state: {
users: [
{ id: 1, name: 'Alice', status: 'active', role: 'admin' },
{ id: 2, name: 'Bob', status: 'inactive', role: 'user' },
{ id: 3, name: 'Charlie', status: 'active', role: 'user' }
]
},
getters: {
activeUsers(state) {
return state.users.filter(user => user.status === 'active');
},
activeUserCount(state, getters) {
return getters.activeUsers.length;
},
adminUsers(state) {
return state.users.filter(user => user.role === 'admin');
}
},
mutations: {
updateUserStatus(state, { userId, status }) {
const user = state.users.find(u => u.id === userId);
if (user) {
user.status = status;
}
}
}
});
```
will return 3``` activeUserCount ```
will return two usersadminUsers
will include only Alice and CharlieactiveUsers