Skip to content

Instantly share code, notes, and snippets.

View AnshKapoor's full-sized avatar
🌏
Always up in this ever connected world

Ansh Kapoor AnshKapoor

🌏
Always up in this ever connected world
View GitHub Profile
@AnshKapoor
AnshKapoor / Instance.js
Created February 24, 2023 06:18
Changing behavior of instanceOf in Javascript
class MyArray {
static [Symbol.hasInstance](instance) {
return Array.isArray(instance);
}
}
const arr = [1, 2, 3];
console.log(arr instanceof MyArray); // true
@AnshKapoor
AnshKapoor / Symbol.js
Last active February 24, 2023 06:14
An example to demonstrate the usage of Symbol.toPrimitive
// Taken from https://h3manth.com/posts/Well-known-symbols/
class Life {
[Symbol.toPrimitive](hint) {
switch (hint) {
case "number":
return 100;
case "string":
return "Hundred";
case "default":
return true;
@AnshKapoor
AnshKapoor / App.js
Created October 8, 2020 07:51
From Handling in React
import React,{Component} from 'react'
class App extends Component{
constructor(){
super()
this.state = {
firstName : "",
lastName :"",
isFriendly:false,
defaultText:"This is textArea"
}
@AnshKapoor
AnshKapoor / image_save.py
Created August 17, 2020 17:42
A code snippet to save an image from a url in Python
import requests
from io import BytesIO
from PIL import Image
r = requests.get("https://cutewallpaper.org/21/anything-wallpapers/Anything-Wallpapers-Wallpaper-Cave.png")
image = Image.open(BytesIO(r.content))
path = "./image."+image.format
try:
image.save(path, image.format)
@AnshKapoor
AnshKapoor / Json.py
Created August 15, 2020 13:08
This code snippet shows how to handle json with python
# pip install simplejson
import simplejson as json # Importing simplejson with a different name for ease of use
import os
if os.path.isfile("./ages.json") and os.stat("./ages.json").st_size !=0: # Checking if a file exists and size is not zero
old_file = open("./ages.json", "r+")
data = json.loads(old_file.read())
print("Current age is:", data["age"])
data["age"] = data["age"]+1
else:
newFile = open("newFile.txt", "w+") # Opening the file in writing mode
string = "This is the content to be written into the file" # Content to be inserted into the file
newFile.write(string) # Writing the content to file