Techletter #87 | August 24, 2024
What is enumerate in Python?
The enumerate()
function in Python is a built-in function that simplifies the process of iterating over a collection while keeping track of the index of each item.
fruits = ['apple', 'banana', 'cherry']
for index, value in enumerate(fruits):
print(index, value)
How to use cache in Python?
Caching in Python is a technique used to store frequently accessed data in a temporary location to improve application performance.
from functools import cache
@cache
def compute_square(n):
return n * n
print(compute_square(5)) # Calculating square of 5...
print(compute_square(5)) # Cached result
What is the use of a decorator in Python?
A decorator in Python is a function that modifies the behavior of another function.
def simple_decorator(func):
def wrapper():
print("1")
func()
print("3")
return wrapper
@simple_decorator
def say_hello():
print("Hello!")
say_hello()
How do you get the binary number from an integer?
In JavaScript
const binary = num.toString(2); // output 101
In python
binary = bin(num)[2:] #output: 101
# if you don't use [2:]
# you will get 0b101
How to use SQLite in your node project?
Basically, I got to know about SQLite while I was working on Python Django. So, here is how you can integrate SQLite into your node projects:
The complete code can be found here
import sqlite3_package from "sqlite3";
import * as uuid from "uuid";
const sqlite3 = sqlite3_package.verbose();
class DB {
constructor() {
this.db = new sqlite3.Database(":memory:", (error) => {
if (error) {
console.log("Error while connecting to the sqlite db", error.message);
}
console.log("connected to sqlite database");
});
this.db.serialize(() => {
this.db.run(`CREATE TABLE IF NOT EXISTS process_info (
id INTEGER PRIMARY KEY,
uuid BLOB NOT NULL,
step INTEGER,
message TEXT
)`);
});
this.insert = this.db.prepare(`INSERT INTO process_info (uuid, step, message) VALUES(?, ?, ?)`);
this.insert.run(uuid.v4(), 1, "List fetched");
}
getProcessInfo = (requestId) => {
return new Promise((resolve, reject) => {
this.db.all(`SELECT * FROM process_info WHERE uuid="${requestId}"`, [], (err, rows) => {
if (err) {
reject(err);
}
resolve(rows);
});
});
}
addProcessInfo = (requestId, step, message) => {
return new Promise((resolve, reject) => {
this.insert.run(requestId, step, message, (err) => {
if (err) {
reject(err);
}
resolve(true);
});
})
}
}
const DbInstance = new DB();
export {
DbInstance
}