-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.py
96 lines (71 loc) · 2.4 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
from __future__ import annotations
import itertools
import random
from datetime import datetime
from datetime import time
from datetime import timedelta
from decimal import Decimal
from typing import Any
import pendulum
from models import Markov2
from models import Markov3
def time_difference(time1: time, time2: time) -> timedelta:
t1 = datetime(1990, 1, 1, time1.hour, time1.minute)
t2 = datetime(1990, 1, 1, time2.hour, time2.minute)
if t2 > t1:
return t2 - t1
else:
return t2 + timedelta(days=1) - t1
def window(seq, n=2):
"""
Returns a sliding window (of width n) over data from the iterable
s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...
"""
it = iter(seq)
result = tuple(itertools.islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result
def shuffle_str(s: str) -> str:
stringlist = list(s)
random.shuffle(stringlist)
return ''.join(stringlist)
def get_markov_weights(markovs: list[Markov2 | Markov3]) -> list[float]:
total = sum(markov.counter for markov in markovs)
return [markov.counter / total for markov in markovs]
class Buf:
def __init__(self, size: int = 2) -> None:
self._buf = [None] * size
self.size = size
def push(self, value) -> None:
self._buf = (self._buf + [value])[-self.size:]
def get(self) -> list:
return self._buf
@property
def last(self) -> Any:
return self._buf[-1]
def remove_prefix(text: str, prefix: str) -> str:
if text.startswith(prefix):
return text[len(prefix):]
return text
def triggered_chance(percentage_chance: float) -> bool:
return random.random() < percentage_chance
def next_call_timestamp(
now: pendulum.DateTime,
scheduled_at: time,
scheduled_every: pendulum.Duration,
) -> pendulum.DateTime:
candidate = now.replace(hour=scheduled_at.hour, minute=scheduled_at.minute)
while candidate < now:
candidate += scheduled_every
return candidate
def format_fraction(numerator: int, denominator: int) -> str:
result = Decimal(numerator) / Decimal(denominator)
if result == 0:
return '0'
decimal_part = str(result).split('.')[1]
first_nonzero_pos = next((i for i, digit in enumerate(decimal_part) if digit != '0'), None)
precision = first_nonzero_pos + 1
return f'{result:.{precision}f}'