Snippets

Like most programmers, I keep going to some projects to copy some bits of code. From now on, I'm going to list them in one place.

Bash

Gource

Make a video of the evolution of a git repo

gource \
--hide dirnames,filenames \
--seconds-per-day 0.1 \
--auto-skip-seconds 1 -1280x720 -o - |
ffmpeg \
-y -r 60 -f image2pipe\
-vcodec ppm -i -\
-vcodec libx264 \
-preset ultrafast \
-pix_fmt yuv420p \
-crf 1 \
-threads 0 \
-bf 0 \
gource.mp4

Python

Custom Errors

To create custom errors

class AgeNotInRangeError(Exception):
"""
Exception raised for errors in the input age.

- age - age which caused the error
- message - explanation of the error
"""


def __init__(self, age, message="Age is not in range"):
self.age = age
self.message = message
super().__init__(self.message)

def __str__(self):
return f'{self.age} -> {self.message}'


age = int(input("Enter age amount: "))
if age <= 18:
raise AgeNotInRangeError(age)

Tests

To do some test-driven development, create a file at tests/test_{name}.py with some tests:

import unittest

class TestEvents(unittest.TestCase):
def test_{name}(self):
self.assertEqual(1, 1)

To run the tests, use python -m unittest discover -s tests/

Django

Create a model with a created_at and udpated_at:

class MyModel(models.Model):
# ...
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

Typescript and/or javascript

Custom Errors

To create custom errors

class HttpStatusError extends Error {
private data: Errors
private status: number

constructor(status: number, data: Errors) {
const message = `Got status ${status} for request`
super(message)
this.name = 'HttpStatusError'
this.data = data
this.status = status
}
}

To use and throw them

throw new HttpStatusError(500, { error: 'Try again later' })

Later, to catch and use them

if (err instanceof HttpStatusError) {
// ...
}

if (err.name == 'HttpStatusError') {
// ...
}

React

Dump some variable so we can visually inspect it:

<pre>{JSON.stringify(variable, null, 4)}</pre>

Tailwind

Rows and columns

<div class="container mx-auto max-w-6xl mt-8">
<div class="flex border border-blue-600 -mx-4">
<div class="w-1/4 border border-red-600 mx-4">1</div>
<div class="w-1/4 border border-red-600 mx-4">2</div>
<div class="w-1/4 border border-red-600 mx-4">3</div>
<div class="w-1/4 border border-red-600 mx-4">4</div>
</div>
</div>

Subscribe to the newsletter

As a full-stack web developer I write about both the backend and frontend. If you liked what you read and want more, subscribe to my newsletter and I'll be sure to let you know once I release new articles.

I hope you like it! Share it with others who could enjoy it too.