everycode 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
everycode/__init__.py ADDED
@@ -0,0 +1,886 @@
1
+ """Everycode: a friendly collection of everyday Python helpers.
2
+
3
+ Import with ``import everycode as ec``. The package is intentionally built
4
+ from the Python standard library and has no import-time side effects.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import calendar as _calendar
10
+ import base64 as _base64
11
+ import contextvars as _contextvars
12
+ import datetime as _dt
13
+ import functools as _functools
14
+ import json as _json
15
+ import math as _math
16
+ import os as _os
17
+ import platform as _platform
18
+ from pathlib import Path as _Path
19
+ import random as _random
20
+ import statistics as _statistics
21
+ import string as _string
22
+ import time as _time
23
+ import sys as _sys
24
+ import urllib.parse as _urlparse
25
+ import uuid as _uuid
26
+ from collections import Counter as _Counter
27
+ from typing import Any
28
+
29
+ __version__ = "1.0.0"
30
+ _LANGUAGE = "en"
31
+
32
+
33
+ def _localized(english: str, slovak: str) -> str:
34
+ return slovak if _LANGUAGE == "sk" else english
35
+
36
+
37
+ def sklang() -> None:
38
+ """Switch user-facing Everycode messages to Slovak."""
39
+ global _LANGUAGE
40
+ _LANGUAGE = "sk"
41
+
42
+
43
+ def enlang() -> None:
44
+ """Switch user-facing Everycode messages back to English."""
45
+ global _LANGUAGE
46
+ _LANGUAGE = "en"
47
+
48
+
49
+ def close() -> None:
50
+ """Exit the current Python program cleanly."""
51
+ raise SystemExit(0)
52
+
53
+
54
+ def exit_program(code: int = 0) -> None:
55
+ """Exit the current Python program with an optional status code."""
56
+ raise SystemExit(code)
57
+
58
+
59
+ def pause(prompt: str | None = None) -> str:
60
+ """Wait for Enter and return what the user typed."""
61
+ default = _localized("Press Enter to continue...", "Stlač Enter na pokračovanie...")
62
+ return input(prompt if prompt is not None else default)
63
+
64
+
65
+ def clear_screen() -> None:
66
+ """Clear the current terminal screen."""
67
+ _os.system("cls" if _os.name == "nt" else "clear")
68
+
69
+
70
+ def get_args() -> list[str]:
71
+ """Return command-line arguments passed to the current script."""
72
+ return _sys.argv[1:]
73
+
74
+
75
+ def current_directory() -> str:
76
+ """Return the current working directory."""
77
+ return _os.getcwd()
78
+
79
+
80
+ def script_path() -> str:
81
+ """Return the path used to start the current Python program."""
82
+ return _os.path.abspath(_sys.argv[0])
83
+
84
+
85
+ def python_version() -> str:
86
+ """Return the running Python version."""
87
+ return _platform.python_version()
88
+
89
+
90
+ def platform_name() -> str:
91
+ """Return the operating system platform name."""
92
+ return _sys.platform
93
+
94
+
95
+ def is_interactive() -> bool:
96
+ """Return whether standard input is connected to an interactive terminal."""
97
+ return _sys.stdin.isatty()
98
+
99
+
100
+ def wait(seconds: int | float) -> None:
101
+ """Pause the current program for whole or fractional seconds."""
102
+ if isinstance(seconds, bool) or not isinstance(seconds, (int, float)):
103
+ raise TypeError(_localized("seconds must be a number", "čas musí byť číslo"))
104
+ if seconds < 0:
105
+ raise ValueError(_localized("seconds must be non-negative", "počet sekúnd nesmie byť záporný"))
106
+ _time.sleep(seconds)
107
+
108
+
109
+ def json_dumps(value: Any, indent: int = 2, ensure_ascii: bool = False) -> str:
110
+ """Convert a Python value to readable JSON text."""
111
+ return _json.dumps(value, indent=indent, ensure_ascii=ensure_ascii)
112
+
113
+
114
+ def json_loads(text: str) -> Any:
115
+ """Parse JSON text into Python values."""
116
+ return _json.loads(text)
117
+
118
+
119
+ def is_json(text: str) -> bool:
120
+ """Return whether text contains valid JSON."""
121
+ try:
122
+ _json.loads(text)
123
+ return True
124
+ except (TypeError, ValueError):
125
+ return False
126
+
127
+
128
+ def url_encode(text: str) -> str:
129
+ """Percent-encode text for use in a URL query value."""
130
+ return _urlparse.quote(text, safe="")
131
+
132
+
133
+ def url_decode(text: str) -> str:
134
+ """Decode percent-encoded URL text."""
135
+ return _urlparse.unquote(text)
136
+
137
+
138
+ def base64_encode(text: str) -> str:
139
+ """Encode UTF-8 text as Base64."""
140
+ return _base64.b64encode(text.encode("utf-8")).decode("ascii")
141
+
142
+
143
+ def base64_decode(text: str) -> str:
144
+ """Decode Base64 text as UTF-8."""
145
+ return _base64.b64decode(text.encode("ascii"), validate=True).decode("utf-8")
146
+
147
+
148
+ def new_id() -> str:
149
+ """Create a random UUID string."""
150
+ return str(_uuid.uuid4())
151
+
152
+
153
+ def path_exists(path: str) -> bool:
154
+ """Return whether a file-system path exists."""
155
+ return _Path(path).exists()
156
+
157
+
158
+ def path_name(path: str) -> str:
159
+ """Return the final file or folder name from a path."""
160
+ return _Path(path).name
161
+
162
+
163
+ def file_extension(path: str) -> str:
164
+ """Return a file extension, including its leading dot."""
165
+ return _Path(path).suffix
166
+
167
+
168
+ def file_size(path: str) -> int:
169
+ """Return a file's size in bytes."""
170
+ return _Path(path).stat().st_size
171
+
172
+
173
+ def read_text(path: str, encoding: str = "utf-8") -> str:
174
+ """Read and return a text file using the selected encoding."""
175
+ return _Path(path).read_text(encoding=encoding)
176
+
177
+
178
+ def get_env(name: str, default: str | None = None) -> str | None:
179
+ """Get an environment variable, or return a fallback value."""
180
+ return _os.environ.get(name, default)
181
+
182
+
183
+ # Time and date
184
+ def now() -> _dt.datetime:
185
+ """Return the current local date and time."""
186
+ return _dt.datetime.now().astimezone()
187
+
188
+
189
+ def time() -> str:
190
+ """Return the current local time as HH:MM:SS."""
191
+ return _dt.datetime.now().astimezone().strftime("%H:%M:%S")
192
+
193
+
194
+ def year() -> int:
195
+ """Return the current local year."""
196
+ return _dt.datetime.now().astimezone().year
197
+
198
+
199
+ def date() -> str:
200
+ """Return today's local date in ISO format (YYYY-MM-DD)."""
201
+ return _dt.datetime.now().astimezone().date().isoformat()
202
+
203
+
204
+ def datetime() -> str:
205
+ """Return the current local date and time in ISO format."""
206
+ return _dt.datetime.now().astimezone().isoformat(timespec="seconds")
207
+
208
+
209
+ def today() -> _dt.date:
210
+ return _dt.datetime.now().astimezone().date()
211
+
212
+
213
+ def timestamp() -> float:
214
+ return _time.time()
215
+
216
+
217
+ def weekday(day: _dt.date | None = None) -> str:
218
+ value = day or _dt.date.today()
219
+ sk = ("pondelok", "utorok", "streda", "štvrtok", "piatok", "sobota", "nedeľa")[value.weekday()]
220
+ return _localized(value.strftime("%A"), sk)
221
+
222
+
223
+ def weekday_number(day: _dt.date | None = None) -> int:
224
+ return (day or today()).weekday()
225
+
226
+
227
+ def month_name(month: int | None = None) -> str:
228
+ value = month or _dt.date.today().month
229
+ if not 1 <= value <= 12: raise ValueError("month must be between 1 and 12")
230
+ sk = ("január", "február", "marec", "apríl", "máj", "jún", "júl", "august", "september", "október", "november", "december")[value-1]
231
+ return _localized(_calendar.month_name[value], sk)
232
+
233
+
234
+ def month_days(year: int | None = None, month: int | None = None) -> int:
235
+ d = today()
236
+ return _calendar.monthrange(year or d.year, month or d.month)[1]
237
+
238
+
239
+ def calendar_month(year: int | None = None, month: int | None = None) -> str:
240
+ d = today()
241
+ value = _calendar.month(year or d.year, month or d.month)
242
+ if _LANGUAGE == "sk":
243
+ for en, sk in zip(_calendar.month_name[1:], ("január", "február", "marec", "apríl", "máj", "jún", "júl", "august", "september", "október", "november", "december")):
244
+ value = value.replace(en, sk)
245
+ for en, sk in zip(("Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"), ("Po", "Ut", "St", "Št", "Pi", "So", "Ne")):
246
+ value = value.replace(en, sk)
247
+ return value
248
+
249
+
250
+ def is_leap_year(year: int | None = None) -> bool:
251
+ return _calendar.isleap(year or today().year)
252
+
253
+
254
+ def add_days(days: int, start: _dt.date | None = None) -> _dt.date:
255
+ return (start or today()) + _dt.timedelta(days=days)
256
+
257
+
258
+ def days_between(first: _dt.date, second: _dt.date) -> int:
259
+ return (second - first).days
260
+
261
+
262
+ def parse_date(value: str, fmt: str = "%Y-%m-%d") -> _dt.date:
263
+ return _dt.datetime.strptime(value, fmt).date()
264
+
265
+
266
+ def format_date(value: _dt.date | _dt.datetime, fmt: str = "%Y-%m-%d") -> str:
267
+ return value.strftime(fmt)
268
+
269
+
270
+ def countdown(target: _dt.datetime) -> _dt.timedelta:
271
+ if target.tzinfo is None:
272
+ target = target.astimezone()
273
+ return target - _dt.datetime.now().astimezone()
274
+
275
+
276
+ # Arithmetic and numeric helpers
277
+ def add(a: float, b: float) -> float: return a + b
278
+ def subtract(a: float, b: float) -> float: return a - b
279
+ def multiply(a: float, b: float) -> float: return a * b
280
+ def divide(a: float, b: float) -> float:
281
+ if b == 0: raise ZeroDivisionError("cannot divide by zero")
282
+ return a / b
283
+ def floor_divide(a: int, b: int) -> int: return a // b
284
+ def modulo(a: int, b: int) -> int: return a % b
285
+ def power(a: float, b: float) -> float: return a ** b
286
+ def square(n: float) -> float: return n * n
287
+ def cube(n: float) -> float: return n ** 3
288
+ def sqrt(n: float) -> float: return _math.sqrt(n)
289
+ def cbrt(n: float) -> float: return _math.cbrt(n)
290
+ def absolute(n: float) -> float: return abs(n)
291
+ def negate(n: float) -> float: return -n
292
+ def sign(n: float) -> int: return (n > 0) - (n < 0)
293
+ def clamp(n: float, low: float, high: float) -> float:
294
+ if low > high: raise ValueError("low must be <= high")
295
+ return max(low, min(high, n))
296
+ def lerp(a: float, b: float, amount: float) -> float: return a + (b - a) * amount
297
+ def map_range(value: float, in_min: float, in_max: float, out_min: float, out_max: float) -> float:
298
+ if in_min == in_max: raise ValueError("input range must not be zero")
299
+ return out_min + (value - in_min) * (out_max - out_min) / (in_max - in_min)
300
+ def round_to(n: float, digits: int = 0) -> float: return round(n, digits)
301
+ def floor(n: float) -> int: return _math.floor(n)
302
+ def ceil(n: float) -> int: return _math.ceil(n)
303
+ def trunc(n: float) -> int: return _math.trunc(n)
304
+ def is_even(n: int) -> bool: return n % 2 == 0
305
+ def is_odd(n: int) -> bool: return n % 2 != 0
306
+ def is_prime(n: int) -> bool:
307
+ if n < 2: return False
308
+ if n % 2 == 0: return n == 2
309
+ return all(n % d for d in range(3, _math.isqrt(n) + 1, 2))
310
+ def factorial(n: int) -> int: return _math.factorial(n)
311
+ def gcd(a: int, b: int) -> int: return _math.gcd(a, b)
312
+ def lcm(a: int, b: int) -> int: return _math.lcm(a, b)
313
+ def percent(value: float, total: float) -> float:
314
+ if total == 0: raise ZeroDivisionError("total must not be zero")
315
+ return value / total * 100
316
+ def percentage_of(percent_value: float, total: float) -> float: return percent_value * total / 100
317
+ def percent_change(old: float, new: float) -> float:
318
+ if old == 0: raise ZeroDivisionError("old value must not be zero")
319
+ return (new - old) / abs(old) * 100
320
+ def average(values: Any) -> float: return _statistics.mean(values)
321
+ def median(values: Any) -> float: return _statistics.median(values)
322
+ def mode(values: Any) -> Any: return _statistics.mode(values)
323
+ def sum_values(values: Any) -> Any: return sum(values)
324
+ def product(values: Any) -> Any: return _math.prod(values)
325
+ def minimum(values: Any) -> Any: return min(values)
326
+ def maximum(values: Any) -> Any: return max(values)
327
+ def variance(values: Any) -> float: return _statistics.variance(values)
328
+ def population_variance(values: Any) -> float: return _statistics.pvariance(values)
329
+ def standard_deviation(values: Any) -> float: return _statistics.stdev(values)
330
+ def population_stdev(values: Any) -> float: return _statistics.pstdev(values)
331
+ def distance_2d(x1: float, y1: float, x2: float, y2: float) -> float: return _math.hypot(x2-x1, y2-y1)
332
+ def distance_3d(x1: float, y1: float, z1: float, x2: float, y2: float, z2: float) -> float: return _math.dist((x1,y1,z1),(x2,y2,z2))
333
+ def hypotenuse(a: float, b: float) -> float: return _math.hypot(a, b)
334
+ def degrees(radians: float) -> float: return _math.degrees(radians)
335
+ def radians(degrees_value: float) -> float: return _math.radians(degrees_value)
336
+ def sin(angle: float) -> float: return _math.sin(angle)
337
+ def cos(angle: float) -> float: return _math.cos(angle)
338
+ def tan(angle: float) -> float: return _math.tan(angle)
339
+ def log(n: float, base: float = _math.e) -> float: return _math.log(n, base)
340
+ def log10(n: float) -> float: return _math.log10(n)
341
+ def exp(n: float) -> float: return _math.exp(n)
342
+ def is_close(a: float, b: float, tolerance: float = 1e-9) -> bool: return _math.isclose(a, b, abs_tol=tolerance)
343
+ def is_number(value: Any) -> bool:
344
+ try: float(value); return True
345
+ except (TypeError, ValueError): return False
346
+ def to_number(value: Any) -> float: return float(value)
347
+ def to_int(value: Any) -> int: return int(value)
348
+ def fibonacci(n: int) -> list[int]:
349
+ if n < 0: raise ValueError("n must be non-negative")
350
+ out=[]; a,b=0,1
351
+ for _ in range(n): out.append(a); a,b=b,a+b
352
+ return out
353
+
354
+
355
+ # Geometry, conversions and everyday calculations
356
+ def area_rectangle(width: float, height: float) -> float: return width * height
357
+ def area_square(side: float) -> float: return side * side
358
+ def area_circle(radius: float) -> float: return _math.pi * radius**2
359
+ def area_triangle(base: float, height: float) -> float: return base * height / 2
360
+ def area_trapezoid(a: float, b: float, height: float) -> float: return (a+b)*height/2
361
+ def perimeter_rectangle(width: float, height: float) -> float: return 2*(width+height)
362
+ def perimeter_square(side: float) -> float: return side * 4
363
+ def circumference(radius: float) -> float: return 2 * _math.pi * radius
364
+ def volume_cube(side: float) -> float: return side**3
365
+ def volume_box(width: float, height: float, depth: float) -> float: return width*height*depth
366
+ def volume_sphere(radius: float) -> float: return 4*_math.pi*radius**3/3
367
+ def celsius_to_fahrenheit(c: float) -> float: return c*9/5+32
368
+ def fahrenheit_to_celsius(f: float) -> float: return (f-32)*5/9
369
+ def celsius_to_kelvin(c: float) -> float: return c+273.15
370
+ def kelvin_to_celsius(k: float) -> float: return k-273.15
371
+ def km_to_miles(km: float) -> float: return km*0.621371
372
+ def miles_to_km(miles: float) -> float: return miles/0.621371
373
+ def meters_to_feet(meters: float) -> float: return meters*3.28084
374
+ def feet_to_meters(feet: float) -> float: return feet/3.28084
375
+ def kg_to_pounds(kg: float) -> float: return kg*2.2046226218
376
+ def pounds_to_kg(pounds: float) -> float: return pounds/2.2046226218
377
+ def cm_to_inches(cm: float) -> float: return cm/2.54
378
+ def inches_to_cm(inches: float) -> float: return inches*2.54
379
+ def liters_to_gallons(liters: float) -> float: return liters*0.264172
380
+ def gallons_to_liters(gallons: float) -> float: return gallons/0.264172
381
+ def minutes_to_seconds(minutes: float) -> float: return minutes*60
382
+ def hours_to_minutes(hours: float) -> float: return hours*60
383
+ def days_to_hours(days: float) -> float: return days*24
384
+ def bytes_to_kb(n: float) -> float: return n/1024
385
+ def kb_to_mb(n: float) -> float: return n/1024
386
+ def mb_to_gb(n: float) -> float: return n/1024
387
+ def bmr_mifflin(weight_kg: float, height_cm: float, age: int, sex: str = "female") -> float:
388
+ base=10*weight_kg+6.25*height_cm-5*age
389
+ if sex.lower() in {"male","m"}: return base+5
390
+ if sex.lower() in {"female","f"}: return base-161
391
+ raise ValueError("sex must be 'female' or 'male'")
392
+
393
+
394
+ # Text helpers
395
+ def reverse_text(text: str) -> str: return text[::-1]
396
+ def word_count(text: str) -> int: return len(text.split())
397
+ def char_count(text: str) -> int: return len(text)
398
+ def count_char(text: str, char: str) -> int: return text.count(char)
399
+ def title_case(text: str) -> str: return text.title()
400
+ def sentence_case(text: str) -> str: return text.capitalize()
401
+ def uppercase(text: str) -> str: return text.upper()
402
+ def lowercase(text: str) -> str: return text.lower()
403
+ def swap_case(text: str) -> str: return text.swapcase()
404
+ def slugify(text: str) -> str:
405
+ return "-".join("".join(c.lower() if c.isalnum() else " " for c in text).split())
406
+ def remove_spaces(text: str) -> str: return "".join(text.split())
407
+ def normalize_spaces(text: str) -> str: return " ".join(text.split())
408
+ def is_palindrome(text: str) -> bool:
409
+ cleaned="".join(c.casefold() for c in text if c.isalnum()); return cleaned == cleaned[::-1]
410
+ def initials(name: str) -> str: return "".join(part[0].upper() for part in name.split() if part)
411
+ def truncate(text: str, length: int, suffix: str = "…") -> str:
412
+ if length < 0: raise ValueError("length must be non-negative")
413
+ return text if len(text)<=length else text[:max(0,length-len(suffix))]+suffix
414
+ def repeat_text(text: str, times: int) -> str: return text * times
415
+ def pad_left(text: str, length: int, fill: str = " ") -> str: return text.rjust(length, fill)
416
+ def pad_right(text: str, length: int, fill: str = " ") -> str: return text.ljust(length, fill)
417
+ def count_vowels(text: str) -> int: return sum(c.casefold() in "aeiouáäéíóôúý" for c in text)
418
+ def remove_vowels(text: str) -> str: return "".join(c for c in text if c.casefold() not in "aeiouáäéíóôúý")
419
+ def unique_chars(text: str) -> str: return "".join(dict.fromkeys(text))
420
+ def sort_words(text: str) -> list[str]: return sorted(text.split(), key=str.casefold)
421
+ def longest_word(text: str) -> str: return max(text.split(), key=len, default="")
422
+ def most_common_word(text: str) -> str:
423
+ words=[w.strip(_string.punctuation).casefold() for w in text.split()]; words=[w for w in words if w]
424
+ return _Counter(words).most_common(1)[0][0] if words else ""
425
+ def contains(text: str, part: str) -> bool: return part in text
426
+ def is_blank(text: str) -> bool: return not text.strip()
427
+ def center_text(text: str, width: int, fill: str = " ") -> str: return text.center(width, fill)
428
+ def wrap_text(text: str, width: int = 70) -> str:
429
+ import textwrap
430
+ return textwrap.fill(text, width=width)
431
+ def mask_text(text: str, keep_last: int = 4, mask: str = "*") -> str:
432
+ if keep_last < 0: raise ValueError("keep_last must be non-negative")
433
+ return mask*max(0,len(text)-keep_last)+text[-keep_last:] if keep_last else mask*len(text)
434
+
435
+
436
+ # Lists and collections
437
+ def unique(items: Any) -> list[Any]: return list(dict.fromkeys(items))
438
+ def flatten(items: Any) -> list[Any]: return [x for group in items for x in group]
439
+ def chunk(items: Any, size: int) -> list[list[Any]]:
440
+ if size <= 0: raise ValueError("size must be positive")
441
+ return [list(items[i:i+size]) for i in range(0,len(items),size)]
442
+ def rotate(items: Any, steps: int = 1) -> list[Any]:
443
+ values=list(items)
444
+ if not values: return values
445
+ n=steps%len(values); return values[-n:]+values[:-n] if n else values
446
+ def second_largest(items: Any) -> Any:
447
+ vals=sorted(set(items));
448
+ if len(vals)<2: raise ValueError("need at least two distinct values")
449
+ return vals[-2]
450
+ def median_value(items: Any) -> float: return _statistics.median(items)
451
+ def frequency(items: Any) -> dict[Any,int]: return dict(_Counter(items))
452
+ def most_common(items: Any, count: int = 1) -> list[tuple[Any,int]]: return _Counter(items).most_common(count)
453
+ def shuffle_copy(items: Any) -> list[Any]:
454
+ result=list(items); _random.shuffle(result); return result
455
+ def pick(items: Any) -> Any:
456
+ if not items: raise IndexError("cannot pick from an empty collection")
457
+ return _random.choice(items)
458
+ def pick_many(items: Any, count: int) -> list[Any]: return _random.sample(list(items), count)
459
+ def pairwise(items: Any) -> list[tuple[Any,Any]]: return list(zip(items,items[1:]))
460
+ def difference(first: Any, second: Any) -> list[Any]: return [x for x in first if x not in second]
461
+ def intersection(first: Any, second: Any) -> list[Any]: return list(dict.fromkeys(x for x in first if x in second))
462
+ def union(first: Any, second: Any) -> list[Any]: return unique(list(first)+list(second))
463
+ def sorted_copy(items: Any, reverse: bool = False) -> list[Any]: return sorted(items, reverse=reverse)
464
+ def reverse_list(items: Any) -> list[Any]: return list(reversed(items))
465
+ def sum_squares(items: Any) -> float: return sum(x*x for x in items)
466
+ def all_true(items: Any) -> bool: return all(items)
467
+ def any_true(items: Any) -> bool: return any(items)
468
+ def enumerate_items(items: Any, start: int = 0) -> list[tuple[int,Any]]: return list(enumerate(items,start))
469
+ def zip_lists(*items: Any) -> list[tuple[Any,...]]: return list(zip(*items))
470
+
471
+
472
+ # Randomness, identifiers and light-hearted pranks (all opt-in and harmless)
473
+ def random_int(low: int, high: int) -> int: return _random.randint(low,high)
474
+ def randnum(from_: int | None = None, to: int | None = None) -> int:
475
+ """Print and return a random integer from the inclusive from_ to to range."""
476
+ from_label, to_label = ("od", "do") if _LANGUAGE == "sk" else ("from", "to")
477
+ missing = [label for value, label in ((from_, from_label), (to, to_label)) if value is None]
478
+ if missing:
479
+ if len(missing) == 2:
480
+ raise TypeError(f"randnum() requires both '{from_label}' and '{to_label}' arguments.")
481
+ raise TypeError(f"randnum() is missing required argument: '{missing[0]}'.")
482
+ if isinstance(from_, bool) or not isinstance(from_, int) or isinstance(to, bool) or not isinstance(to, int):
483
+ raise TypeError(f"randnum() '{from_label}' and '{to_label}' must be integers.")
484
+ if from_ > to:
485
+ raise ValueError(f"randnum() '{from_label}' must be less than or equal to '{to_label}'.")
486
+ return random_int(from_, to)
487
+ def random_float(low: float = 0.0, high: float = 1.0) -> float: return _random.uniform(low,high)
488
+ def random_bool() -> bool: return bool(_random.getrandbits(1))
489
+ def random_color() -> str: return "#"+"".join(f"{_random.randrange(256):02x}" for _ in range(3))
490
+ def random_password(length: int = 16) -> str:
491
+ if length < 1: raise ValueError("length must be positive")
492
+ import secrets
493
+ alphabet=_string.ascii_letters+_string.digits+"!@#$%^&*"
494
+ return "".join(secrets.choice(alphabet) for _ in range(length))
495
+ def coin_flip() -> str: return _random.choice(["heads","tails"])
496
+ def dice(sides: int = 6) -> int:
497
+ if sides < 2: raise ValueError("a die needs at least two sides")
498
+ return _random.randint(1,sides)
499
+ def choose(items: Any) -> Any: return pick(items)
500
+ def random_emoji() -> str: return _random.choice([":-)","<3",":D","^_^","*_*",";)"])
501
+ def _pick_translation(choices: list[tuple[str, str]]) -> str:
502
+ english, slovak = _random.choice(choices)
503
+ return _localized(english, slovak)
504
+ def magic_8_ball() -> str:
505
+ return _pick_translation([("Yes.","Áno."),("Probably.","Skôr áno."),("Maybe.","Možno."),("Ask again later.","Skús sa opýtať neskôr."),("The outlook is not great today.","Dnes to nevyzerá.")])
506
+ def silly_compliment(name: str = "friend") -> str: return _localized(f"{name}, your brain is in turbo mode today!",f"{name}, tvoj mozog dnes beží na turbo!")
507
+ def silly_excuse() -> str: return _pick_translation([("My cactus needed emotional support.","Môj kaktus potreboval podporu."),("I got tangled up in my own plan.","Zamotal som sa do vlastného plánu."),("The universe took a short break.","Vesmír si dal krátku prestávku."),("My sock had an urgent meeting.","Moja ponožka mala naliehavú poradu.")])
508
+ def silly_riddle() -> str: return _pick_translation([("What has teeth but cannot bite? A comb.","Čo má zuby, ale nehryzie? Hrebeň."),("What goes up and never comes down? Your age.","Čo ide hore a nikdy nejde dolu? Vek."),("What has a neck but no head? A bottle.","Čo má krk, ale nemá hlavu? Fľaša.")])
509
+ def silly_fact() -> str: return _pick_translation([("Octopuses have three hearts.","Chobotnice majú tri srdcia."),("A banana is botanically a berry.","Banán je z botanického pohľadu bobuľa."),("Honey keeps well when stored properly.","Med sa pri správnom skladovaní nekazí ľahko.")])
510
+ def prank_pun() -> str: return _pick_translation([("Why did the math book visit the doctor? It had too many problems.","Prečo išla matematická kniha k lekárovi? Mala veľa problémov."),("What did zero say to eight? Nice belt!","Čo povie nula osmičke? Pekný opasok!"),("Why did the computer visit the doctor? It had a virus.","Prečo počítač išiel k lekárovi? Mal vírus.")])
511
+ def prank_fake_loading(seconds: int = 3) -> str:
512
+ """Return a pretend loading animation as text; it does not wait or alter anything."""
513
+ if seconds < 0: raise ValueError("seconds must be non-negative")
514
+ return _localized("Loading"+"."*(seconds%4)+" Done! (just a joke)","Načítavam"+"."*(seconds%4)+" Hotovo! (len žart)")
515
+ def prank_reversed(text: str) -> str: return _localized(f"Oops, your text got reversed: {text[::-1]}",f"Ups, text sa obrátil: {text[::-1]}")
516
+ def prank_computer_says() -> str: return _localized("The computer says it needs a break for virtual tea.","Počítač tvrdí, že potrebuje prestávku na virtuálny čaj.")
517
+ def fortune_cookie() -> str: return _pick_translation([("You will learn something new today.","Dnes sa naučíš niečo nové."),("A small step can take you far.","Malý krok ťa posunie ďaleko."),("A good idea may be hiding in a question.","Dobrý nápad sa môže skrývať v otázke."),("Remember to drink some water.","Nezabudni sa napiť vody.")])
518
+ def random_name() -> str: return _random.choice(["Milo","Nina","Tobi","Luna","Alex","Samo","Ema","Riko"])
519
+ def random_quote() -> str: return _pick_translation([("Every expert was once a beginner.","Každý expert bol kedysi začiatočník."),("Try it first, then improve it.","Najprv to skús, potom to vylepši."),("Small progress is still progress.","Aj malý pokrok je pokrok.")])
520
+ def random_color_name() -> str: return _pick_translation([("red","červená"),("blue","modrá"),("green","zelená"),("purple","fialová"),("orange","oranžová"),("turquoise","tyrkysová")])
521
+ def random_choice_message(items: Any) -> str:
522
+ value=pick(items); return _localized(f"Random choice: {value}",f"Náhodná voľba: {value}")
523
+
524
+
525
+ # Helpful formatting and validation
526
+ def format_number(n: float, decimals: int = 2) -> str: return f"{n:,.{decimals}f}"
527
+ def ordinal(n: int) -> str:
528
+ return f"{n}{'th' if 10 <= n%100 <= 20 else {1:'st',2:'nd',3:'rd'}.get(n%10,'th')}"
529
+ def bytes_human(n: int) -> str:
530
+ if n < 0: raise ValueError("n must be non-negative")
531
+ value=float(n)
532
+ for unit in ("B","KB","MB","GB","TB","PB"):
533
+ if value < 1024 or unit == "PB": return f"{value:.2f} {unit}"
534
+ value/=1024
535
+ def is_email(value: str) -> bool: return "@" in value and "." in value.rsplit("@",1)[-1] and not any(c.isspace() for c in value)
536
+ def is_url(value: str) -> bool: return value.startswith(("https://","http://")) and "." in value.split("://",1)[-1]
537
+ def is_hex_color(value: str) -> bool: return len(value)==7 and value.startswith("#") and all(c in _string.hexdigits for c in value[1:])
538
+ def is_integer(value: Any) -> bool:
539
+ try: int(value); return str(value).strip() not in {"", "+", "-"}
540
+ except (TypeError, ValueError): return False
541
+ def is_alpha(text: str) -> bool: return text.isalpha()
542
+ def is_alphanumeric(text: str) -> bool: return text.isalnum()
543
+ def is_digit(text: str) -> bool: return text.isdigit()
544
+ def is_lower(text: str) -> bool: return text.islower()
545
+ def is_upper(text: str) -> bool: return text.isupper()
546
+ def reverse_number(n: int) -> int: return int(str(abs(n))[::-1]) * (-1 if n<0 else 1)
547
+ def digit_sum(n: int) -> int: return sum(int(c) for c in str(abs(n)))
548
+ def roman_numeral(n: int) -> str:
549
+ if not 1 <= n <= 3999: raise ValueError("n must be between 1 and 3999")
550
+ result=""
551
+ for value, symbol in ((1000,"M"),(900,"CM"),(500,"D"),(400,"CD"),(100,"C"),(90,"XC"),(50,"L"),(40,"XL"),(10,"X"),(9,"IX"),(5,"V"),(4,"IV"),(1,"I")):
552
+ while n>=value: result+=symbol; n-=value
553
+ return result
554
+ def to_binary(n: int) -> str: return format(n,"b")
555
+ def to_hex(n: int) -> str: return format(n,"x")
556
+ def to_octal(n: int) -> str: return format(n,"o")
557
+
558
+
559
+ # Extra everyday helpers
560
+ def add_many(*values: float) -> float: return sum(values)
561
+ def subtract_many(first: float, *values: float) -> float:
562
+ for value in values: first -= value
563
+ return first
564
+ def multiply_many(*values: float) -> float: return _math.prod(values)
565
+ def average_or_zero(values: Any) -> float: return _statistics.mean(values) if values else 0
566
+ def median_low(values: Any) -> Any: return _statistics.median_low(values)
567
+ def median_high(values: Any) -> Any: return _statistics.median_high(values)
568
+ def is_positive(n: float) -> bool: return n > 0
569
+ def is_negative(n: float) -> bool: return n < 0
570
+ def is_zero(n: float) -> bool: return n == 0
571
+ def is_in_range(n: float, low: float, high: float) -> bool: return low <= n <= high
572
+ def nearest_multiple(n: float, multiple: float) -> float:
573
+ if multiple == 0: raise ZeroDivisionError("multiple must not be zero")
574
+ return round(n/multiple)*multiple
575
+ def percent_off(price: float, discount: float) -> float: return price*(1-discount/100)
576
+ def tip_amount(bill: float, tip_percent: float = 15) -> float: return bill*tip_percent/100
577
+ def split_bill(bill: float, people: int) -> float:
578
+ if people <= 0: raise ValueError("people must be positive")
579
+ return bill/people
580
+ def compound_interest(principal: float, rate_percent: float, periods: int) -> float: return principal*(1+rate_percent/100)**periods
581
+ def simple_interest(principal: float, rate_percent: float, years: float) -> float: return principal*rate_percent/100*years
582
+ def bmi(weight_kg: float, height_m: float) -> float:
583
+ if height_m <= 0: raise ValueError("height must be positive")
584
+ return weight_kg/(height_m**2)
585
+ def pace_minutes_per_km(minutes: float, kilometers: float) -> float:
586
+ if kilometers <= 0: raise ValueError("kilometers must be positive")
587
+ return minutes/kilometers
588
+ def speed(distance: float, hours: float) -> float:
589
+ if hours == 0: raise ZeroDivisionError("hours must not be zero")
590
+ return distance/hours
591
+ def midpoint(a: float, b: float) -> float: return (a+b)/2
592
+ def is_between(n: float, a: float, b: float) -> bool: return min(a,b) <= n <= max(a,b)
593
+ def triangle_hypotenuse(a: float, b: float) -> float: return _math.hypot(a,b)
594
+ def triangle_area_sides(a: float, b: float, c: float) -> float:
595
+ s=(a+b+c)/2
596
+ if min(a,b,c) <= 0 or max(a,b,c) >= a+b+c-max(a,b,c): raise ValueError("side lengths must form a triangle")
597
+ return _math.sqrt(s*(s-a)*(s-b)*(s-c))
598
+ def area_ellipse(a: float, b: float) -> float: return _math.pi*a*b
599
+ def surface_area_box(w: float, h: float, d: float) -> float: return 2*(w*h+w*d+h*d)
600
+ def surface_area_sphere(r: float) -> float: return 4*_math.pi*r*r
601
+ def volume_cylinder(r: float, h: float) -> float: return _math.pi*r*r*h
602
+ def volume_cone(r: float, h: float) -> float: return _math.pi*r*r*h/3
603
+ def celsius_to_rankine(c: float) -> float: return (c+273.15)*9/5
604
+ def fahrenheit_to_kelvin(f: float) -> float: return (f-32)*5/9+273.15
605
+ def kmh_to_mph(speed_kmh: float) -> float: return speed_kmh*0.621371
606
+ def mph_to_kmh(speed_mph: float) -> float: return speed_mph/0.621371
607
+ def grams_to_ounces(g: float) -> float: return g/28.349523125
608
+ def ounces_to_grams(oz: float) -> float: return oz*28.349523125
609
+ def ml_to_liters(ml: float) -> float: return ml/1000
610
+ def liters_to_ml(liters: float) -> float: return liters*1000
611
+ def seconds_to_minutes(seconds: float) -> float: return seconds/60
612
+ def seconds_to_hours(seconds: float) -> float: return seconds/3600
613
+ def hours_to_seconds(hours: float) -> float: return hours*3600
614
+ def weeks_to_days(weeks: float) -> float: return weeks*7
615
+ def days_to_minutes(days: float) -> float: return days*1440
616
+ def gb_to_mb(gb: float) -> float: return gb*1024
617
+ def mb_to_kb(mb: float) -> float: return mb*1024
618
+ def kb_to_bytes(kb: float) -> float: return kb*1024
619
+ def bytes_to_mb(n: float) -> float: return n/(1024**2)
620
+ def bytes_to_gb(n: float) -> float: return n/(1024**3)
621
+ def title_words(text: str) -> list[str]: return text.title().split()
622
+ def split_lines(text: str) -> list[str]: return text.splitlines()
623
+ def join_words(words: Any, separator: str = " ") -> str: return separator.join(map(str,words))
624
+ def remove_punctuation(text: str) -> str: return "".join(c for c in text if c not in _string.punctuation)
625
+ def keep_letters(text: str) -> str: return "".join(c for c in text if c.isalpha() or c.isspace())
626
+ def keep_digits(text: str) -> str: return "".join(c for c in text if c.isdigit())
627
+ def count_lines(text: str) -> int: return len(text.splitlines())
628
+ def count_sentences(text: str) -> int: return sum(text.count(mark) for mark in ".!?")
629
+ def common_prefix(first: str, second: str) -> str:
630
+ i=0
631
+ while i<min(len(first),len(second)) and first[i]==second[i]: i+=1
632
+ return first[:i]
633
+ def common_suffix(first: str, second: str) -> str:
634
+ i=0
635
+ while i<min(len(first),len(second)) and first[-i-1]==second[-i-1]: i+=1
636
+ return first[len(first)-i:] if i else ""
637
+ def nth_item(items: Any, index: int, default: Any = None) -> Any:
638
+ try: return items[index]
639
+ except IndexError: return default
640
+ def first(items: Any, default: Any = None) -> Any: return nth_item(items,0,default)
641
+ def last(items: Any, default: Any = None) -> Any: return nth_item(items,-1,default)
642
+ def take(items: Any, count: int) -> list[Any]: return list(items[:count])
643
+ def drop(items: Any, count: int) -> list[Any]: return list(items[count:])
644
+ def count_items(items: Any) -> int: return len(items)
645
+ def has_duplicates(items: Any) -> bool:
646
+ values=list(items); return len(set(values))<len(values)
647
+ def partition(items: Any, predicate: Any) -> tuple[list[Any],list[Any]]:
648
+ yes=[]; no=[]
649
+ for item in items: (yes if predicate(item) else no).append(item)
650
+ return yes,no
651
+ def random_letter() -> str: return _random.choice(_string.ascii_lowercase)
652
+ def random_number_string(length: int = 6) -> str:
653
+ if length < 1: raise ValueError("length must be positive")
654
+ return "".join(_random.choice(_string.digits) for _ in range(length))
655
+ def random_sentence() -> str: return _pick_translation([("A cat is learning to code.","Mačka sa učí programovať."),("Today is a great day for a new idea.","Dnes je skvelý deň na nový nápad."),("A little robot is looking for its sock.","Malý robot hľadá svoju ponožku.")])
656
+ def rock_paper_scissors(choice: str) -> str:
657
+ user=choice.casefold()
658
+ if user not in {"rock","paper","scissors","kameň","papier","nožnice"}: raise ValueError("choose rock/paper/scissors or kameň/papier/nožnice")
659
+ mapping={"rock":"kameň","paper":"papier","scissors":"nožnice","kameň":"kameň","papier":"papier","nožnice":"nožnice"}
660
+ mine=_random.choice(["kameň","papier","nožnice"]); theirs=mapping[user]
661
+ result="remíza" if mine==theirs else "vyhral si" if (theirs,mine) in {("kameň","nožnice"),("papier","kameň"),("nožnice","papier")} else "vyhral počítač"
662
+ en_result = {"remíza":"draw", "vyhral si":"you win", "vyhral počítač":"the computer wins"}[result]
663
+ return _localized(f"You: {theirs}; computer: {mine}; {en_result}.",f"Ty: {theirs}; počítač: {mine}; {result}.")
664
+ def choose_for_me(*options: Any) -> Any:
665
+ if not options: raise ValueError("provide at least one option")
666
+ return _random.choice(options)
667
+ def random_boolean_message() -> str: return _pick_translation([("Yes!","Áno!"),("No.","Nie.")])
668
+ def silly_name() -> str: return _pick_translation([("Captain Spaghetti","Kapitán Špageta"),("Professor Pancake","Profesor Palacinka"),("Agent Cucumber","Agent Uhorka"),("Doctor Sock","Doktor Ponožka")])
669
+ def silly_weather() -> str: return _pick_translation([("Cloudy with a chance of cookies.","Dnes očakávame oblačno s možnosťou sušienok."),("Sunny skies and one cheerful thought ahead.","Na obzore sa črtá slnečno a veselá myšlienka."),("Forecast: 100 percent chance of a smile.","Predpoveď: 100 percent šanca na úsmev.")])
670
+ def ascii_smile() -> str: return ":-)"
671
+ def ascii_table(rows: Any) -> str:
672
+ values=[list(map(str,row)) for row in rows]
673
+ if not values: return ""
674
+ widths=[max(len(row[i]) if i<len(row) else 0 for row in values) for i in range(max(map(len,values)))]
675
+ return "\n".join(" | ".join(value.ljust(widths[i]) for i,value in enumerate(row)) for row in values)
676
+ def format_duration(seconds: float) -> str:
677
+ seconds=int(seconds); sign="-" if seconds<0 else ""; seconds=abs(seconds)
678
+ h,rem=divmod(seconds,3600); m,s=divmod(rem,60)
679
+ return f"{sign}{h:02d}:{m:02d}:{s:02d}"
680
+ def format_money(amount: float, currency: str = "EUR") -> str: return f"{amount:,.2f} {currency}"
681
+ def zero_pad(n: int, width: int = 2) -> str: return str(n).zfill(width)
682
+ def percentage_bar(value: float, width: int = 20) -> str:
683
+ if width < 1: raise ValueError("width must be positive")
684
+ value=max(0,min(100,value)); filled=round(width*value/100)
685
+ return "["+"#"*filled+"-"*(width-filled)+f"] {value:g}%"
686
+ def check_password_length(password: str, minimum: int = 8) -> bool: return len(password)>=minimum
687
+ def sanitize_filename(name: str) -> str: return "".join(c for c in name if c.isalnum() or c in "._- ").strip()
688
+ def strip_edges(text: str) -> str: return text.strip()
689
+ def remove_prefix(text: str, prefix: str) -> str: return text[len(prefix):] if text.startswith(prefix) else text
690
+ def remove_suffix(text: str, suffix: str) -> str: return text[:-len(suffix)] if suffix and text.endswith(suffix) else text
691
+ def replace_text(text: str, old: str, new: str) -> str: return text.replace(old,new)
692
+ def starts_with(text: str, prefix: str) -> bool: return text.startswith(prefix)
693
+ def ends_with(text: str, suffix: str) -> bool: return text.endswith(suffix)
694
+ def count_substring(text: str, part: str) -> int: return text.count(part)
695
+ def binary_to_int(value: str) -> int: return int(value,2)
696
+ def hex_to_int(value: str) -> int: return int(value,16)
697
+ def octal_to_int(value: str) -> int: return int(value,8)
698
+ def fraction(numerator: int, denominator: int) -> tuple[int,int]:
699
+ if denominator == 0: raise ZeroDivisionError("denominator must not be zero")
700
+ divisor=_math.gcd(numerator,denominator); return numerator//divisor,denominator//divisor
701
+ def digit_count(n: int) -> int: return len(str(abs(n)))
702
+ def sum_digits(n: int) -> int: return digit_sum(n)
703
+ def is_perfect_square(n: int) -> bool: return n>=0 and _math.isqrt(n)**2==n
704
+ def is_power_of_two(n: int) -> bool: return n>0 and n&(n-1)==0
705
+ def next_prime(n: int) -> int:
706
+ candidate=max(2,n+1)
707
+ while not is_prime(candidate): candidate+=1
708
+ return candidate
709
+ def percent_fraction(value: float, total: float) -> str: return f"{percent(value,total):.1f}%"
710
+ def average_speed(distance: float, hours: float) -> float: return speed(distance,hours)
711
+ def growth_factor(rate_percent: float, periods: int) -> float: return (1+rate_percent/100)**periods
712
+ def tax_included(price: float, tax_percent: float) -> float: return price*(1+tax_percent/100)
713
+ def tax_amount(price: float, tax_percent: float) -> float: return price*tax_percent/100
714
+ def discount_amount(price: float, discount_percent: float) -> float: return price*discount_percent/100
715
+ def safe_divide(a: float, b: float, default: Any = None) -> Any: return a/b if b else default
716
+ def try_int(value: Any, default: Any = None) -> Any:
717
+ try: return int(value)
718
+ except (TypeError,ValueError): return default
719
+ def try_float(value: Any, default: Any = None) -> Any:
720
+ try: return float(value)
721
+ except (TypeError,ValueError): return default
722
+
723
+
724
+ # Help catalog: each public callable has a concise description. Generated
725
+ # from docstrings / readable names so help remains complete as the API grows.
726
+ _DESCRIPTIONS = {
727
+ "time":"Print and return the current local time.", "year":"Print and return the current year.", "date":"Print and return today's date.",
728
+ "datetime":"Print and return the current date and time.", "now":"Print and return the current local date and time as an object.",
729
+ "prank_fake_loading":"Return a harmless pretend loading message.",
730
+ "prank_pun":"Choose a harmless pun.", "prank_reversed":"Return text reversed as a harmless joke.",
731
+ "prank_computer_says":"Return a harmless pretend computer message.",
732
+ "randnum":"Print and return a random integer between the inclusive limits.",
733
+ "close":"Exit the current Python program cleanly.",
734
+ "exit_program":"Exit the current Python program with an optional status code.",
735
+ "pause":"Wait for the user to press Enter.", "clear_screen":"Clear the current terminal screen.",
736
+ "get_args":"Return the script's command-line arguments.", "current_directory":"Return the working directory.",
737
+ "script_path":"Return the current script path.", "python_version":"Return the running Python version.",
738
+ "platform_name":"Return the operating system platform name.", "is_interactive":"Check whether input is an interactive terminal.",
739
+ "wait":"Pause the program for whole or fractional seconds.",
740
+ "json_dumps":"Convert a Python value to JSON text.", "json_loads":"Parse JSON text into Python values.",
741
+ "is_json":"Check whether text is valid JSON.", "url_encode":"Encode text for use in a URL.",
742
+ "url_decode":"Decode percent-encoded URL text.", "base64_encode":"Encode UTF-8 text as Base64.",
743
+ "base64_decode":"Decode Base64 text as UTF-8.", "new_id":"Create a random UUID.",
744
+ "path_exists":"Check whether a file-system path exists.", "path_name":"Get the final name from a path.",
745
+ "file_extension":"Get a file extension.", "file_size":"Get a file size in bytes.",
746
+ "read_text":"Read a text file.", "get_env":"Get an environment variable or a fallback.",
747
+ }
748
+
749
+ _SK_DESCRIPTIONS = {
750
+ "now":"Vypíše a vráti aktuálny miestny dátum a čas.", "time":"Vypíše a vráti aktuálny miestny čas.",
751
+ "year":"Vypíše a vráti aktuálny rok.", "date":"Vypíše a vráti dnešný dátum.",
752
+ "datetime":"Vypíše a vráti aktuálny dátum a čas.", "prank_fake_loading":"Vráti neškodnú falošnú správu o načítavaní.",
753
+ "prank_pun":"Vyberie neškodný vtip.", "prank_reversed":"Vráti text odzadu ako neškodný žart.",
754
+ "prank_computer_says":"Vráti neškodnú žartovnú hlášku počítača.",
755
+ "randnum":"Vypíše a vráti náhodné celé číslo vrátane zadaných hraníc.",
756
+ "close":"Bezpečne ukončí aktuálny Python program.",
757
+ "exit_program":"Ukončí Python program s voliteľným návratovým kódom.",
758
+ "pause":"Počká, kým používateľ stlačí Enter.", "clear_screen":"Vyčistí obrazovku terminálu.",
759
+ "get_args":"Vráti argumenty príkazového riadka odovzdané skriptu.", "current_directory":"Vráti aktuálny pracovný priečinok.",
760
+ "script_path":"Vráti cestu k spustenému skriptu.", "python_version":"Vráti verziu spusteného Pythonu.",
761
+ "platform_name":"Vráti názov platformy operačného systému.", "is_interactive":"Zistí, či je vstup pripojený k interaktívnemu terminálu.",
762
+ "wait":"Pozastaví program na zadaný počet sekúnd vrátane zlomkov sekundy.",
763
+ "json_dumps":"Prevedie hodnotu Pythonu na text vo formáte JSON.", "json_loads":"Načíta hodnoty z textu JSON.",
764
+ "is_json":"Zistí, či text obsahuje platný JSON.", "url_encode":"Zakóduje text na použitie v URL.",
765
+ "url_decode":"Dekóduje percentovo zakódovaný text URL.", "base64_encode":"Zakóduje UTF-8 text vo formáte Base64.",
766
+ "base64_decode":"Dekóduje Base64 text ako UTF-8.", "new_id":"Vytvorí náhodný identifikátor UUID.",
767
+ "path_exists":"Zistí, či cesta k súboru alebo priečinku existuje.", "path_name":"Vráti názov súboru alebo priečinka z cesty.",
768
+ "file_extension":"Vráti príponu súboru.", "file_size":"Vráti veľkosť súboru v bajtoch.",
769
+ "read_text":"Prečíta textový súbor.", "get_env":"Vráti premennú prostredia alebo náhradnú hodnotu.",
770
+ }
771
+ _SK_WORDS = {
772
+ "add":"sčítaj", "subtract":"odčítaj", "multiply":"vynásob", "divide":"vydeľ",
773
+ "average":"priemer", "median":"medián", "mode":"modus", "sum":"súčet",
774
+ "square":"druhá mocnina", "cube":"tretia mocnina", "sqrt":"odmocnina",
775
+ "is":"je", "even":"párne", "odd":"nepárne", "prime":"prvočíslo",
776
+ "positive":"kladné", "negative":"záporné", "zero":"nula", "number":"číslo",
777
+ "date":"dátum", "time":"čas", "year":"rok", "month":"mesiac", "day":"deň",
778
+ "weekday":"deň v týždni", "random":"náhodný", "color":"farba", "name":"názov",
779
+ "text":"text", "word":"slovo", "count":"počet", "reverse":"obráť",
780
+ "list":"zoznam", "unique":"jedinečné", "sort":"zoradiť", "filter":"filtrovať",
781
+ "format":"formátovať", "convert":"previesť", "to":"na", "from":"z",
782
+ "area":"obsah", "volume":"objem", "circle":"kruh", "square":"štvorec",
783
+ "rectangle":"obdĺžnik", "triangle":"trojuholník", "distance":"vzdialenosť",
784
+ "degrees":"stupne", "radians":"radiány", "password":"heslo", "email":"e-mail",
785
+ "url":"webová adresa", "true":"pravda", "false":"nepravda", "all":"všetky",
786
+ "any":"niektoré", "first":"prvý", "last":"posledný", "days":"dni",
787
+ "hours":"hodiny", "minutes":"minúty", "seconds":"sekundy", "bytes":"bajty",
788
+ "int":"celé číslo", "float":"desatinné číslo", "items":"položky", "values":"hodnoty",
789
+ "randomness":"náhodnosť", "factorial":"faktoriál", "fibonacci":"Fibonacciho postupnosť",
790
+ "percentage":"percento", "percent":"percento", "change":"zmena", "human":"čitateľný",
791
+ "check":"skontrolovať", "contains":"obsahuje", "contains":"obsahuje",
792
+ }
793
+
794
+
795
+ def _slovak_description(name: str) -> str:
796
+ return " ".join(_SK_WORDS.get(part, part) for part in name.split("_")) + "."
797
+
798
+
799
+ def commands() -> dict[str, str]:
800
+ """Return everycode's public command names with short descriptions."""
801
+ result = {}
802
+ for name, value in globals().copy().items():
803
+ if name.startswith("_") or name in {"commands", "help", "sklang", "enlang"} or not callable(value):
804
+ continue
805
+ if getattr(value, "__module__", None) != __name__:
806
+ continue
807
+ description = _DESCRIPTIONS.get(name, (getattr(value,"__doc__",None) or name.replace("_"," ").capitalize()+".").strip())
808
+ if _LANGUAGE == "sk":
809
+ description = _SK_DESCRIPTIONS.get(name, _slovak_description(name))
810
+ result[name] = description
811
+ return dict(sorted(result.items()))
812
+
813
+
814
+ def help(command: str | None = None) -> None:
815
+ """Print everycode command help, or details for one command."""
816
+ items = commands()
817
+ if command is not None:
818
+ fn = globals().get(command)
819
+ if command not in items:
820
+ print(_localized(f"Unknown command: {command}. Type ec.help().", f"Neznámy príkaz: {command}. Zadaj ec.help()."))
821
+ return
822
+ print(f"ec.{command}{__import__('inspect').signature(fn)} — {items[command]}")
823
+ doc = getattr(fn,"__doc__",None)
824
+ if doc: print(doc)
825
+ return
826
+ if _LANGUAGE == "sk":
827
+ count = len(items)
828
+ label = "príkaz" if count == 1 else "príkazy" if 2 <= count % 10 <= 4 and not 12 <= count % 100 <= 14 else "príkazov"
829
+ print(f"Everycode {__version__} — {count} {label}\nPoužitie: import everycode as ec; ec.help('add')\n")
830
+ else:
831
+ print(f"Everycode {__version__} — {len(items)} commands\nUsage: import everycode as ec; ec.help('add')\n")
832
+ groups = {
833
+ ("Date and time" if _LANGUAGE == "en" else "Dátum a čas"): [n for n in items if n in {"now","time","year","date","datetime","today","timestamp","weekday","weekday_number","month_name","month_days","calendar_month","is_leap_year","add_days","days_between","parse_date","format_date","countdown"}],
834
+ ("Math" if _LANGUAGE == "en" else "Matematika"): [n for n in items if n in {"add","add_many","subtract","subtract_many","multiply","multiply_many","divide","safe_divide","floor_divide","modulo","power","square","cube","sqrt","cbrt","absolute","negate","sign","is_positive","is_negative","is_zero","clamp","lerp","map_range","nearest_multiple","midpoint","is_between","is_in_range","round_to","floor","ceil","trunc","is_even","is_odd","is_prime","next_prime","is_perfect_square","is_power_of_two","factorial","gcd","lcm","fraction","percent","percentage_of","percent_change","percent_off","percent_fraction","discount_amount","tip_amount","tax_amount","tax_included","split_bill","simple_interest","compound_interest","growth_factor","average","average_or_zero","median","median_low","median_high","mode","sum_values","product","minimum","maximum","variance","population_variance","standard_deviation","population_stdev","distance_2d","distance_3d","hypotenuse","triangle_hypotenuse","triangle_area_sides","degrees","radians","sin","cos","tan","log","log10","exp","is_close","is_number","to_number","to_int","try_int","try_float","fibonacci","bmi","pace_minutes_per_km","speed","average_speed","digit_sum","sum_digits","digit_count","reverse_number","check_password_length"}],
835
+ ("Shapes and conversions" if _LANGUAGE == "en" else "Tvary a prevody"): [n for n in items if n.startswith(("area_","perimeter_","volume_","surface_area_")) or n in {"circumference","celsius_to_fahrenheit","fahrenheit_to_celsius","celsius_to_kelvin","kelvin_to_celsius","celsius_to_rankine","fahrenheit_to_kelvin","km_to_miles","miles_to_km","kmh_to_mph","mph_to_kmh","meters_to_feet","feet_to_meters","kg_to_pounds","pounds_to_kg","grams_to_ounces","ounces_to_grams","cm_to_inches","inches_to_cm","liters_to_gallons","gallons_to_liters","liters_to_ml","ml_to_liters","minutes_to_seconds","seconds_to_minutes","seconds_to_hours","hours_to_minutes","hours_to_seconds","days_to_hours","days_to_minutes","weeks_to_days","bytes_to_kb","kb_to_mb","mb_to_gb","kb_to_bytes","mb_to_kb","gb_to_mb","bytes_to_mb","bytes_to_gb","bmr_mifflin","binary_to_int","hex_to_int","octal_to_int","to_binary","to_hex","to_octal","bytes_human"}],
836
+ ("Text" if _LANGUAGE == "en" else "Text"): [n for n in items if n in {"reverse_text","word_count","char_count","count_char","count_lines","count_sentences","count_substring","title_case","sentence_case","title_words","uppercase","lowercase","swap_case","slugify","remove_spaces","normalize_spaces","strip_edges","remove_prefix","remove_suffix","replace_text","remove_punctuation","keep_letters","keep_digits","is_palindrome","initials","truncate","repeat_text","pad_left","pad_right","count_vowels","remove_vowels","unique_chars","sort_words","longest_word","most_common_word","contains","is_blank","center_text","wrap_text","mask_text","split_lines","join_words","common_prefix","common_suffix","starts_with","ends_with","sanitize_filename"}],
837
+ ("Lists" if _LANGUAGE == "en" else "Zoznamy"): [n for n in items if n in {"unique","flatten","chunk","rotate","second_largest","median_value","frequency","most_common","shuffle_copy","pick","pick_many","pairwise","difference","intersection","union","sorted_copy","reverse_list","sum_squares","all_true","any_true","enumerate_items","zip_lists","first","last","nth_item","take","drop","count_items","has_duplicates","partition"}],
838
+ ("Randomness and harmless pranks" if _LANGUAGE == "en" else "Náhoda a neškodné pranky"): [n for n in items if n.startswith(("random_","prank_","silly_")) or n in {"randnum","coin_flip","dice","choose","choose_for_me","magic_8_ball","fortune_cookie","rock_paper_scissors"}],
839
+ ("Formatting and validation" if _LANGUAGE == "en" else "Formátovanie a kontrola"): [n for n in items if n in {"format_number","format_money","format_duration","percentage_bar","zero_pad","ordinal","ascii_table","ascii_smile","is_email","is_url","is_hex_color","is_integer","is_alpha","is_alphanumeric","is_digit","is_lower","is_upper","roman_numeral"}],
840
+ ("Program control" if _LANGUAGE == "en" else "Ovládanie programu"): [n for n in items if n in {"close","exit_program","pause","clear_screen","get_args","current_directory","script_path","python_version","platform_name","is_interactive","wait"}],
841
+ ("Data, web and paths" if _LANGUAGE == "en" else "Dáta, web a cesty"): [n for n in items if n in {"json_dumps","json_loads","is_json","url_encode","url_decode","base64_encode","base64_decode","new_id","path_exists","path_name","file_extension","file_size","read_text","get_env"}],
842
+ }
843
+ used=set()
844
+ for group, names in groups.items():
845
+ names=[n for n in names if n in items]
846
+ used.update(names)
847
+ print(f"{group} ({len(names)}):")
848
+ for name in names: print(f" ec.{name} — {items[name]}")
849
+ print()
850
+ rest=[n for n in items if n not in used]
851
+ if rest:
852
+ print(f"{'Other' if _LANGUAGE == 'en' else 'Ďalšie'} ({len(rest)}):")
853
+ for name in rest: print(f" ec.{name} — {items[name]}")
854
+
855
+
856
+ # Print each top-level command result once while preserving its return value.
857
+ # The context variable suppresses output from helper commands called internally.
858
+ _PRINT_DEPTH = _contextvars.ContextVar("everycode_print_depth", default=0)
859
+
860
+
861
+ def _with_auto_print(function: Any) -> Any:
862
+ @_functools.wraps(function)
863
+ def wrapped(*args: Any, **kwargs: Any) -> Any:
864
+ parent_depth = _PRINT_DEPTH.get()
865
+ token = _PRINT_DEPTH.set(parent_depth + 1)
866
+ try:
867
+ result = function(*args, **kwargs)
868
+ finally:
869
+ _PRINT_DEPTH.reset(token)
870
+ if parent_depth == 0 and result is not None:
871
+ print(result)
872
+ return result
873
+ return wrapped
874
+
875
+
876
+ for _command_name, _command_value in tuple(globals().items()):
877
+ if (
878
+ not _command_name.startswith("_")
879
+ and _command_name not in {"commands", "help", "sklang", "enlang"}
880
+ and callable(_command_value)
881
+ and getattr(_command_value, "__module__", None) == __name__
882
+ ):
883
+ globals()[_command_name] = _with_auto_print(_command_value)
884
+
885
+
886
+ __all__ = [*commands().keys(), "commands", "help", "sklang", "enlang", "__version__"]
@@ -0,0 +1,59 @@
1
+ Metadata-Version: 2.4
2
+ Name: everycode
3
+ Version: 1.0.0
4
+ Summary: A friendly collection of everyday Python helper commands
5
+ Author: Everycode contributors
6
+ License-Expression: MIT
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+
10
+ # everycode
11
+
12
+ Everycode is a beginner-friendly Python helper library with date and time,
13
+ math, geometry, conversions, text tools, list helpers, validation, random
14
+ utilities, and opt-in harmless joke functions. It uses only Python's standard
15
+ library and does nothing when imported.
16
+
17
+ ## Install
18
+
19
+ From this folder:
20
+
21
+ ```bash
22
+ python -m pip install .
23
+ ```
24
+
25
+ ## Quick start
26
+
27
+ ```python
28
+ import everycode as ec
29
+
30
+ ec.time() # prints the time and also returns it
31
+ ec.year() # prints the current year
32
+ ec.date() # prints YYYY-MM-DD
33
+ ec.datetime() # prints local date and time
34
+ ec.add(4, 5) # prints 9 and returns 9
35
+ ec.celsius_to_fahrenheit(20)
36
+ ec.prank_pun() # prints a harmless joke and returns it
37
+
38
+ ec.help() # categorized list of every command
39
+ ec.help("add") # details about one command
40
+
41
+ ec.sklang() # switch subsequent messages/help to Slovak
42
+ ec.prank_reversed("Ahoj!")
43
+ ec.enlang() # switch back to English
44
+ ec.json_dumps({"name": "Everycode"})
45
+ ec.url_encode("hello world")
46
+ ec.new_id()
47
+ ```
48
+
49
+ English is the default language. `ec.sklang()` and `ec.enlang()` change the
50
+ language used by help and localized text helpers for the rest of the program.
51
+ These two language switches are intentionally omitted from `ec.help()`.
52
+
53
+ Commands shown by `ec.help()` print their result automatically and also return
54
+ it, so you can still save it in a variable, for example `answer = ec.add(4, 5)`.
55
+ The helper `ec.commands()` returns a mapping of command names to descriptions.
56
+ The language switches only change the language used by supported text outputs;
57
+ they do not print anything themselves.
58
+
59
+ See [PUBLISHING.md](PUBLISHING.md) for the step-by-step PyPI publishing guide.
@@ -0,0 +1,5 @@
1
+ everycode/__init__.py,sha256=VNetrR9YwDGc_EhrPSy08x-9ehuGzVVt_3puQvoIzHA,52730
2
+ everycode-1.0.0.dist-info/METADATA,sha256=AZyT2TWxplBsQmnr6M2YB6EFDs05Vpo5XzZcmtI_Nco,2047
3
+ everycode-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
4
+ everycode-1.0.0.dist-info/top_level.txt,sha256=V3PFWaqLXhloQlGIlcZ5QYamvlQBoxc_zwMQy36SH7A,10
5
+ everycode-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ everycode