Skip to content

Instantly share code, notes, and snippets.

View pointofpresence's full-sized avatar
🏠
Working from home

ReSampled pointofpresence

🏠
Working from home
View GitHub Profile
@pointofpresence
pointofpresence / memoize.js
Last active March 31, 2024 20:02
Функция memoize() сохраняет результаты каждого вызова принимаемой функции в виде [ключ:значение].
// Приведенная ниже функция memoize() сохраняет результаты каждого вызова принимаемой функции в виде [ключ:значение].
// Функция, генерирующая ключ исходя из параметров
const generateKey = args => (
args.map(x => `${x.toString()}:${typeof(x)}`).join('|') // Результат: "x1:number|x2:number|..."
);
// Принимает функцию в качестве параметра
const memoize = fn => {
const cache = {};
@pointofpresence
pointofpresence / HTTP_requests_and_JSON_parsing.py
Last active March 31, 2024 20:01
Python: Запрос JSON методом GET и парсинг
import requests
url = 'http://maps.googleapis.com/maps/api/directions/json'
params = dict(
origin='Chicago,IL',
destination='Los+Angeles,CA',
waypoints='Joplin,MO|Oklahoma+City,OK',
sensor='false'
)
@pointofpresence
pointofpresence / color functions.py
Last active March 31, 2024 19:05
python color functions
import math
# Function to Parse Hexadecimal Value
def parse_hex_color(string):
if string.startswith("#"):
string = string[1:]
r = int(string[0:2], 16) # red color value
g = int(string[2:4], 16) # green color value
b = int(string[4:6], 16) # blue color value
@pointofpresence
pointofpresence / audioextract.py
Last active March 31, 2024 19:01
Python extract audio from video
import moviepy.editor as mp
def extract_audio(video, audio):
my_clip = mp.VideoFileClip(video)
my_clip.audio.write_audiofile(audio)
@pointofpresence
pointofpresence / understanding_slicing.py
Last active March 31, 2024 18:58
Slicing in python
a[start:stop] # items start through stop-1
a[start:] # items start through the rest of the array
a[:stop] # items from the beginning through stop-1
a[:] # a copy of the whole array
@pointofpresence
pointofpresence / pyppeteer screenshot.py
Last active March 31, 2024 18:55
Скриншот страницы с помощью pyppeteer
import asyncio
from pyppeteer import launch
async def main():
browser = await launch()
page = await browser.newPage()
await page.goto('http://example.com')
await page.screenshot({'path': 'example.png', 'fullPage': 'true'})
await browser.close()
@pointofpresence
pointofpresence / text width.js
Last active March 31, 2024 18:48
Получение ширины строки текста
function getTextWidth() {  
text = document.createElement("span");
document.body.appendChild(text);
text.style.font = "times new roman";
text.style.fontSize = 16 + "px";
text.style.height = 'auto';
text.style.width = 'auto';
text.style.position = 'absolute';
text.style.whiteSpace = 'no-wrap';
@pointofpresence
pointofpresence / python_type_check.py
Last active March 31, 2024 18:45
Python: Проверка типа переменной
# Use the type() builtin function:
i = 123
type(i)
# <type 'int'>
type(i) is int
# True
i = 123.456
@pointofpresence
pointofpresence / select multiple.jsx
Last active March 31, 2024 18:42
HTML: Тег select с мультивыбором
// В атрибут value можно передать массив, что позволит выбрать несколько опций в теге select:
<select multiple={true} value={['Б', 'В']}
// Boolean attribute 'multiple' indicates that multiple options can be selected in the list.
// If it is not specified, then only one option can be selected at a time. When `multiple` is
// specified, most browsers will show a scrolling list box instead of a single line dropdown.
@pointofpresence
pointofpresence / ReactJS__userHooks.md
Last active March 31, 2024 18:25
Создание пользовательских хуков

Создание пользовательских хуков

Хуки создаются для того, чтобы можно было разделять одинаковое поведение между разными компонентами. Они работают гораздо очевиднее, чем компоненты высшего порядка или рендер-пропсы. Также, React позволяет создавать кастомные хуки.

// создаем хук для получения данных из API
function useAPI(endpoint) {
  const [value, setValue] = React.useState([]);

 React.useEffect(() =&gt; {