everycode 1.0.0__tar.gz → 1.0.2__tar.gz
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-1.0.2/PKG-INFO +89 -0
- everycode-1.0.2/README.md +77 -0
- {everycode-1.0.0/everycode → everycode-1.0.2}/__init__.py +130 -60
- {everycode-1.0.0 → everycode-1.0.2/everycode}/__init__.py +130 -60
- everycode-1.0.2/everycode.egg-info/PKG-INFO +89 -0
- everycode-1.0.2/pyproject.toml +23 -0
- everycode-1.0.0/PKG-INFO +0 -59
- everycode-1.0.0/README.md +0 -50
- everycode-1.0.0/everycode.egg-info/PKG-INFO +0 -59
- everycode-1.0.0/pyproject.toml +0 -15
- {everycode-1.0.0 → everycode-1.0.2}/everycode.egg-info/SOURCES.txt +0 -0
- {everycode-1.0.0 → everycode-1.0.2}/everycode.egg-info/dependency_links.txt +0 -0
- {everycode-1.0.0 → everycode-1.0.2}/everycode.egg-info/top_level.txt +0 -0
- {everycode-1.0.0 → everycode-1.0.2}/setup.cfg +0 -0
everycode-1.0.2/PKG-INFO
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: everycode
|
|
3
|
+
Version: 1.0.2
|
|
4
|
+
Summary: A standard-library Python toolkit for time, math, text, collections, conversions, encoding, paths, timers, and developer utilities
|
|
5
|
+
Author: Patrick Pustai
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: python,everycode,utilities,time,math,text,encoding,stopwatch,timer
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# Everycode
|
|
14
|
+
|
|
15
|
+
Everycode is a beginner-friendly Python utility library with hundreds of small, practical commands. It uses only Python's standard library and provides helpers for dates and time, arithmetic, statistics, geometry, unit conversion, text, lists, validation, JSON, URL and Base64 encoding, files and paths, random values, and program control.
|
|
16
|
+
|
|
17
|
+
Everycode works on Python 3.10 and later. Its commands return values, so use `print(...)` when you want to show a result. Importing the library does not print output or start timers.
|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pip install everycode
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Quick start
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
# Here are some commands for EveryCode
|
|
29
|
+
# Look to ec.help() for more commands
|
|
30
|
+
import everycode as ec
|
|
31
|
+
print("Welcome to EveryCode library!")
|
|
32
|
+
print(f"Current time: {ec.time()}")
|
|
33
|
+
print(ec.url_encode("Hello, World!"))
|
|
34
|
+
print(ec.platform_name())
|
|
35
|
+
print(ec.factorial(5))
|
|
36
|
+
print(ec.weekday())
|
|
37
|
+
ec.wait(1)
|
|
38
|
+
print(ec.date())
|
|
39
|
+
print(ec.base64_encode("EveryCode"))
|
|
40
|
+
print(ec.base64_decode("RXZlcnlDb2Rl"))
|
|
41
|
+
print(ec.roman_numeral(2026))
|
|
42
|
+
print(ec.is_email("everycode@example.com"))
|
|
43
|
+
print(ec.prank_computer_says())
|
|
44
|
+
print(ec.coin_flip())
|
|
45
|
+
print(ec.char_count("EveryCode is Python library"))
|
|
46
|
+
print(ec.is_negative(58))
|
|
47
|
+
ec.pause()
|
|
48
|
+
print(ec.ascii_smile())
|
|
49
|
+
ec.clear_screen()
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Timers and stopwatch
|
|
53
|
+
|
|
54
|
+
`timer` waits for the requested duration, then returns a completion message:
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
print(ec.timer(1.5))
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
`stopwatch` starts a stopwatch and returns an object that can measure laps,
|
|
61
|
+
stop, resume, and reset:
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
watch = ec.stopwatch()
|
|
65
|
+
# Do some work here.
|
|
66
|
+
print(watch.lap()) # seconds since start or previous lap
|
|
67
|
+
print(watch.stop()) # total elapsed seconds
|
|
68
|
+
watch.start() # resume
|
|
69
|
+
watch.reset() # reset and start again
|
|
70
|
+
print(watch.elapsed)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Discover commands
|
|
74
|
+
|
|
75
|
+
Use `ec.help()` to see all documented commands grouped by category. It includes
|
|
76
|
+
the total number of public commands. Use `ec.help("command_name")` for one
|
|
77
|
+
command's signature and description. `ec.commands()` returns the catalog as a
|
|
78
|
+
mapping of names to descriptions.
|
|
79
|
+
|
|
80
|
+
The help and supported text utilities can display English and Slovak text.
|
|
81
|
+
|
|
82
|
+
## More examples
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
print(ec.average([3, 5, 8]))
|
|
86
|
+
print(ec.slugify("A Useful Page Title"))
|
|
87
|
+
print(ec.new_id())
|
|
88
|
+
print(ec.path_exists("README.md"))
|
|
89
|
+
```
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# Everycode
|
|
2
|
+
|
|
3
|
+
Everycode is a beginner-friendly Python utility library with hundreds of small, practical commands. It uses only Python's standard library and provides helpers for dates and time, arithmetic, statistics, geometry, unit conversion, text, lists, validation, JSON, URL and Base64 encoding, files and paths, random values, and program control.
|
|
4
|
+
|
|
5
|
+
Everycode works on Python 3.10 and later. Its commands return values, so use `print(...)` when you want to show a result. Importing the library does not print output or start timers.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install everycode
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Quick start
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
# Here are some commands for EveryCode
|
|
17
|
+
# Look to ec.help() for more commands
|
|
18
|
+
import everycode as ec
|
|
19
|
+
print("Welcome to EveryCode library!")
|
|
20
|
+
print(f"Current time: {ec.time()}")
|
|
21
|
+
print(ec.url_encode("Hello, World!"))
|
|
22
|
+
print(ec.platform_name())
|
|
23
|
+
print(ec.factorial(5))
|
|
24
|
+
print(ec.weekday())
|
|
25
|
+
ec.wait(1)
|
|
26
|
+
print(ec.date())
|
|
27
|
+
print(ec.base64_encode("EveryCode"))
|
|
28
|
+
print(ec.base64_decode("RXZlcnlDb2Rl"))
|
|
29
|
+
print(ec.roman_numeral(2026))
|
|
30
|
+
print(ec.is_email("everycode@example.com"))
|
|
31
|
+
print(ec.prank_computer_says())
|
|
32
|
+
print(ec.coin_flip())
|
|
33
|
+
print(ec.char_count("EveryCode is Python library"))
|
|
34
|
+
print(ec.is_negative(58))
|
|
35
|
+
ec.pause()
|
|
36
|
+
print(ec.ascii_smile())
|
|
37
|
+
ec.clear_screen()
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Timers and stopwatch
|
|
41
|
+
|
|
42
|
+
`timer` waits for the requested duration, then returns a completion message:
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
print(ec.timer(1.5))
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
`stopwatch` starts a stopwatch and returns an object that can measure laps,
|
|
49
|
+
stop, resume, and reset:
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
watch = ec.stopwatch()
|
|
53
|
+
# Do some work here.
|
|
54
|
+
print(watch.lap()) # seconds since start or previous lap
|
|
55
|
+
print(watch.stop()) # total elapsed seconds
|
|
56
|
+
watch.start() # resume
|
|
57
|
+
watch.reset() # reset and start again
|
|
58
|
+
print(watch.elapsed)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Discover commands
|
|
62
|
+
|
|
63
|
+
Use `ec.help()` to see all documented commands grouped by category. It includes
|
|
64
|
+
the total number of public commands. Use `ec.help("command_name")` for one
|
|
65
|
+
command's signature and description. `ec.commands()` returns the catalog as a
|
|
66
|
+
mapping of names to descriptions.
|
|
67
|
+
|
|
68
|
+
The help and supported text utilities can display English and Slovak text.
|
|
69
|
+
|
|
70
|
+
## More examples
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
print(ec.average([3, 5, 8]))
|
|
74
|
+
print(ec.slugify("A Useful Page Title"))
|
|
75
|
+
print(ec.new_id())
|
|
76
|
+
print(ec.path_exists("README.md"))
|
|
77
|
+
```
|
|
@@ -8,9 +8,7 @@ from __future__ import annotations
|
|
|
8
8
|
|
|
9
9
|
import calendar as _calendar
|
|
10
10
|
import base64 as _base64
|
|
11
|
-
import contextvars as _contextvars
|
|
12
11
|
import datetime as _dt
|
|
13
|
-
import functools as _functools
|
|
14
12
|
import json as _json
|
|
15
13
|
import math as _math
|
|
16
14
|
import os as _os
|
|
@@ -26,7 +24,7 @@ import uuid as _uuid
|
|
|
26
24
|
from collections import Counter as _Counter
|
|
27
25
|
from typing import Any
|
|
28
26
|
|
|
29
|
-
__version__ = "1.0.
|
|
27
|
+
__version__ = "1.0.1"
|
|
30
28
|
_LANGUAGE = "en"
|
|
31
29
|
|
|
32
30
|
|
|
@@ -101,11 +99,75 @@ def wait(seconds: int | float) -> None:
|
|
|
101
99
|
"""Pause the current program for whole or fractional seconds."""
|
|
102
100
|
if isinstance(seconds, bool) or not isinstance(seconds, (int, float)):
|
|
103
101
|
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", "
|
|
102
|
+
if not _math.isfinite(seconds) or seconds < 0:
|
|
103
|
+
raise ValueError(_localized("seconds must be finite and non-negative", "čas musí byť konečné nezáporné číslo"))
|
|
106
104
|
_time.sleep(seconds)
|
|
107
105
|
|
|
108
106
|
|
|
107
|
+
def timer(seconds: int | float) -> str:
|
|
108
|
+
"""Wait for a duration, then return a completion message."""
|
|
109
|
+
if isinstance(seconds, bool) or not isinstance(seconds, (int, float)):
|
|
110
|
+
raise TypeError(_localized("seconds must be a number", "čas musí byť číslo"))
|
|
111
|
+
if not _math.isfinite(seconds) or seconds < 0:
|
|
112
|
+
raise ValueError(_localized("seconds must be finite and non-negative", "čas musí byť konečné nezáporné číslo"))
|
|
113
|
+
_time.sleep(seconds)
|
|
114
|
+
return _localized(f"Timer finished after {seconds:g} seconds.", f"Časovač skončil po {seconds:g} sekundách.")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class _Stopwatch:
|
|
118
|
+
"""A monotonic stopwatch returned by :func:`stopwatch`."""
|
|
119
|
+
def __init__(self) -> None:
|
|
120
|
+
self._started_at = _time.perf_counter()
|
|
121
|
+
self._elapsed_before = 0.0
|
|
122
|
+
self._lap_mark = 0.0
|
|
123
|
+
self._running = True
|
|
124
|
+
|
|
125
|
+
@property
|
|
126
|
+
def elapsed(self) -> float:
|
|
127
|
+
"""Elapsed seconds, including the current run if started."""
|
|
128
|
+
if self._running:
|
|
129
|
+
return self._elapsed_before + (_time.perf_counter() - self._started_at)
|
|
130
|
+
return self._elapsed_before
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def running(self) -> bool:
|
|
134
|
+
return self._running
|
|
135
|
+
|
|
136
|
+
def start(self) -> float:
|
|
137
|
+
"""Start or resume timing and return elapsed seconds."""
|
|
138
|
+
if not self._running:
|
|
139
|
+
self._started_at = _time.perf_counter()
|
|
140
|
+
self._running = True
|
|
141
|
+
return self.elapsed
|
|
142
|
+
|
|
143
|
+
def stop(self) -> float:
|
|
144
|
+
"""Stop timing and return total elapsed seconds."""
|
|
145
|
+
if self._running:
|
|
146
|
+
self._elapsed_before += _time.perf_counter() - self._started_at
|
|
147
|
+
self._running = False
|
|
148
|
+
return self._elapsed_before
|
|
149
|
+
|
|
150
|
+
def lap(self) -> float:
|
|
151
|
+
"""Return seconds since the previous lap (or start)."""
|
|
152
|
+
total = self.elapsed
|
|
153
|
+
result = total - self._lap_mark
|
|
154
|
+
self._lap_mark = total
|
|
155
|
+
return result
|
|
156
|
+
|
|
157
|
+
def reset(self) -> float:
|
|
158
|
+
"""Reset elapsed time and start timing again."""
|
|
159
|
+
self._elapsed_before = 0.0
|
|
160
|
+
self._lap_mark = 0.0
|
|
161
|
+
self._started_at = _time.perf_counter()
|
|
162
|
+
self._running = True
|
|
163
|
+
return 0.0
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def stopwatch() -> _Stopwatch:
|
|
167
|
+
"""Create and start a stopwatch; call its stop, lap, and reset methods."""
|
|
168
|
+
return _Stopwatch()
|
|
169
|
+
|
|
170
|
+
|
|
109
171
|
def json_dumps(value: Any, indent: int = 2, ensure_ascii: bool = False) -> str:
|
|
110
172
|
"""Convert a Python value to readable JSON text."""
|
|
111
173
|
return _json.dumps(value, indent=indent, ensure_ascii=ensure_ascii)
|
|
@@ -225,7 +287,7 @@ def weekday_number(day: _dt.date | None = None) -> int:
|
|
|
225
287
|
|
|
226
288
|
|
|
227
289
|
def month_name(month: int | None = None) -> str:
|
|
228
|
-
value =
|
|
290
|
+
value = _dt.date.today().month if month is None else month
|
|
229
291
|
if not 1 <= value <= 12: raise ValueError("month must be between 1 and 12")
|
|
230
292
|
sk = ("január", "február", "marec", "apríl", "máj", "jún", "júl", "august", "september", "október", "november", "december")[value-1]
|
|
231
293
|
return _localized(_calendar.month_name[value], sk)
|
|
@@ -233,12 +295,12 @@ def month_name(month: int | None = None) -> str:
|
|
|
233
295
|
|
|
234
296
|
def month_days(year: int | None = None, month: int | None = None) -> int:
|
|
235
297
|
d = today()
|
|
236
|
-
return _calendar.monthrange(year
|
|
298
|
+
return _calendar.monthrange(d.year if year is None else year, d.month if month is None else month)[1]
|
|
237
299
|
|
|
238
300
|
|
|
239
301
|
def calendar_month(year: int | None = None, month: int | None = None) -> str:
|
|
240
302
|
d = today()
|
|
241
|
-
value = _calendar.month(year
|
|
303
|
+
value = _calendar.month(d.year if year is None else year, d.month if month is None else month)
|
|
242
304
|
if _LANGUAGE == "sk":
|
|
243
305
|
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
306
|
value = value.replace(en, sk)
|
|
@@ -248,7 +310,7 @@ def calendar_month(year: int | None = None, month: int | None = None) -> str:
|
|
|
248
310
|
|
|
249
311
|
|
|
250
312
|
def is_leap_year(year: int | None = None) -> bool:
|
|
251
|
-
return _calendar.isleap(
|
|
313
|
+
return _calendar.isleap(today().year if year is None else year)
|
|
252
314
|
|
|
253
315
|
|
|
254
316
|
def add_days(days: int, start: _dt.date | None = None) -> _dt.date:
|
|
@@ -286,7 +348,10 @@ def power(a: float, b: float) -> float: return a ** b
|
|
|
286
348
|
def square(n: float) -> float: return n * n
|
|
287
349
|
def cube(n: float) -> float: return n ** 3
|
|
288
350
|
def sqrt(n: float) -> float: return _math.sqrt(n)
|
|
289
|
-
def cbrt(n: float) -> float:
|
|
351
|
+
def cbrt(n: float) -> float:
|
|
352
|
+
if hasattr(_math, "cbrt"):
|
|
353
|
+
return _math.cbrt(n)
|
|
354
|
+
return _math.copysign(abs(n) ** (1 / 3), n)
|
|
290
355
|
def absolute(n: float) -> float: return abs(n)
|
|
291
356
|
def negate(n: float) -> float: return -n
|
|
292
357
|
def sign(n: float) -> int: return (n > 0) - (n < 0)
|
|
@@ -472,7 +537,7 @@ def zip_lists(*items: Any) -> list[tuple[Any,...]]: return list(zip(*items))
|
|
|
472
537
|
# Randomness, identifiers and light-hearted pranks (all opt-in and harmless)
|
|
473
538
|
def random_int(low: int, high: int) -> int: return _random.randint(low,high)
|
|
474
539
|
def randnum(from_: int | None = None, to: int | None = None) -> int:
|
|
475
|
-
"""
|
|
540
|
+
"""Return a random integer from the inclusive lower to upper bound."""
|
|
476
541
|
from_label, to_label = ("od", "do") if _LANGUAGE == "sk" else ("from", "to")
|
|
477
542
|
missing = [label for value, label in ((from_, from_label), (to, to_label)) if value is None]
|
|
478
543
|
if missing:
|
|
@@ -492,7 +557,7 @@ def random_password(length: int = 16) -> str:
|
|
|
492
557
|
import secrets
|
|
493
558
|
alphabet=_string.ascii_letters+_string.digits+"!@#$%^&*"
|
|
494
559
|
return "".join(secrets.choice(alphabet) for _ in range(length))
|
|
495
|
-
def coin_flip() -> str: return _random.choice(["heads","tails"])
|
|
560
|
+
def coin_flip() -> str: return _localized(*_random.choice([("heads", "hlava"), ("tails", "orel")]))
|
|
496
561
|
def dice(sides: int = 6) -> int:
|
|
497
562
|
if sides < 2: raise ValueError("a die needs at least two sides")
|
|
498
563
|
return _random.randint(1,sides)
|
|
@@ -525,19 +590,45 @@ def random_choice_message(items: Any) -> str:
|
|
|
525
590
|
# Helpful formatting and validation
|
|
526
591
|
def format_number(n: float, decimals: int = 2) -> str: return f"{n:,.{decimals}f}"
|
|
527
592
|
def ordinal(n: int) -> str:
|
|
528
|
-
|
|
593
|
+
if _LANGUAGE == "sk":
|
|
594
|
+
return f"{n}."
|
|
595
|
+
value = abs(n)
|
|
596
|
+
suffix = "th" if 10 <= value % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(value % 10, "th")
|
|
597
|
+
return f"{n}{suffix}"
|
|
529
598
|
def bytes_human(n: int) -> str:
|
|
530
599
|
if n < 0: raise ValueError("n must be non-negative")
|
|
531
600
|
value=float(n)
|
|
532
601
|
for unit in ("B","KB","MB","GB","TB","PB"):
|
|
533
602
|
if value < 1024 or unit == "PB": return f"{value:.2f} {unit}"
|
|
534
603
|
value/=1024
|
|
535
|
-
def is_email(value: str) -> bool:
|
|
536
|
-
|
|
604
|
+
def is_email(value: str) -> bool:
|
|
605
|
+
if not isinstance(value, str) or any(c.isspace() for c in value) or value.count("@") != 1:
|
|
606
|
+
return False
|
|
607
|
+
local, domain = value.split("@")
|
|
608
|
+
return bool(local and domain and "." in domain and not domain.startswith(".") and not domain.endswith("."))
|
|
609
|
+
|
|
610
|
+
|
|
611
|
+
def is_url(value: str) -> bool:
|
|
612
|
+
if not isinstance(value, str) or any(c.isspace() for c in value):
|
|
613
|
+
return False
|
|
614
|
+
try:
|
|
615
|
+
parsed = _urlparse.urlsplit(value)
|
|
616
|
+
return parsed.scheme in {"http", "https"} and bool(parsed.hostname) and ("." in parsed.hostname or parsed.hostname == "localhost")
|
|
617
|
+
except ValueError:
|
|
618
|
+
return False
|
|
537
619
|
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
620
|
def is_integer(value: Any) -> bool:
|
|
539
|
-
|
|
540
|
-
|
|
621
|
+
if isinstance(value, bool):
|
|
622
|
+
return False
|
|
623
|
+
try:
|
|
624
|
+
converted = int(value)
|
|
625
|
+
if isinstance(value, str):
|
|
626
|
+
text = value.strip()
|
|
627
|
+
digits = text[1:] if text[:1] in {"+", "-"} else text
|
|
628
|
+
return bool(digits) and digits.isdecimal()
|
|
629
|
+
return value == converted
|
|
630
|
+
except (TypeError, ValueError, OverflowError):
|
|
631
|
+
return False
|
|
541
632
|
def is_alpha(text: str) -> bool: return text.isalpha()
|
|
542
633
|
def is_alphanumeric(text: str) -> bool: return text.isalnum()
|
|
543
634
|
def is_digit(text: str) -> bool: return text.isdigit()
|
|
@@ -562,7 +653,9 @@ def subtract_many(first: float, *values: float) -> float:
|
|
|
562
653
|
for value in values: first -= value
|
|
563
654
|
return first
|
|
564
655
|
def multiply_many(*values: float) -> float: return _math.prod(values)
|
|
565
|
-
def average_or_zero(values: Any) -> float:
|
|
656
|
+
def average_or_zero(values: Any) -> float:
|
|
657
|
+
values = list(values)
|
|
658
|
+
return _statistics.mean(values) if values else 0
|
|
566
659
|
def median_low(values: Any) -> Any: return _statistics.median_low(values)
|
|
567
660
|
def median_high(values: Any) -> Any: return _statistics.median_high(values)
|
|
568
661
|
def is_positive(n: float) -> bool: return n > 0
|
|
@@ -655,12 +748,13 @@ def random_number_string(length: int = 6) -> str:
|
|
|
655
748
|
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
749
|
def rock_paper_scissors(choice: str) -> str:
|
|
657
750
|
user=choice.casefold()
|
|
658
|
-
if user not in {"rock","paper","scissors","kameň","papier","nožnice"}: raise ValueError("choose rock
|
|
751
|
+
if user not in {"rock","paper","scissors","kameň","papier","nožnice"}: raise ValueError(_localized("choose rock, paper, or scissors", "vyber kameň, papier alebo nožnice"))
|
|
659
752
|
mapping={"rock":"kameň","paper":"papier","scissors":"nožnice","kameň":"kameň","papier":"papier","nožnice":"nožnice"}
|
|
660
753
|
mine=_random.choice(["kameň","papier","nožnice"]); theirs=mapping[user]
|
|
661
754
|
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
755
|
en_result = {"remíza":"draw", "vyhral si":"you win", "vyhral počítač":"the computer wins"}[result]
|
|
663
|
-
|
|
756
|
+
english_name={"kameň":"rock", "papier":"paper", "nožnice":"scissors"}
|
|
757
|
+
return _localized(f"You: {english_name[theirs]}; computer: {english_name[mine]}; {en_result}.",f"Ty: {theirs}; počítač: {mine}; {result}.")
|
|
664
758
|
def choose_for_me(*options: Any) -> Any:
|
|
665
759
|
if not options: raise ValueError("provide at least one option")
|
|
666
760
|
return _random.choice(options)
|
|
@@ -670,7 +764,7 @@ def silly_weather() -> str: return _pick_translation([("Cloudy with a chance of
|
|
|
670
764
|
def ascii_smile() -> str: return ":-)"
|
|
671
765
|
def ascii_table(rows: Any) -> str:
|
|
672
766
|
values=[list(map(str,row)) for row in rows]
|
|
673
|
-
if not values: return ""
|
|
767
|
+
if not values or not any(values): return ""
|
|
674
768
|
widths=[max(len(row[i]) if i<len(row) else 0 for row in values) for i in range(max(map(len,values)))]
|
|
675
769
|
return "\n".join(" | ".join(value.ljust(widths[i]) for i,value in enumerate(row)) for row in values)
|
|
676
770
|
def format_duration(seconds: float) -> str:
|
|
@@ -697,7 +791,9 @@ def hex_to_int(value: str) -> int: return int(value,16)
|
|
|
697
791
|
def octal_to_int(value: str) -> int: return int(value,8)
|
|
698
792
|
def fraction(numerator: int, denominator: int) -> tuple[int,int]:
|
|
699
793
|
if denominator == 0: raise ZeroDivisionError("denominator must not be zero")
|
|
700
|
-
divisor=_math.gcd(numerator,denominator)
|
|
794
|
+
divisor=_math.gcd(numerator,denominator)
|
|
795
|
+
numerator, denominator = numerator//divisor, denominator//divisor
|
|
796
|
+
return (-numerator, -denominator) if denominator < 0 else (numerator, denominator)
|
|
701
797
|
def digit_count(n: int) -> int: return len(str(abs(n)))
|
|
702
798
|
def sum_digits(n: int) -> int: return digit_sum(n)
|
|
703
799
|
def is_perfect_square(n: int) -> bool: return n>=0 and _math.isqrt(n)**2==n
|
|
@@ -724,12 +820,14 @@ def try_float(value: Any, default: Any = None) -> Any:
|
|
|
724
820
|
# Help catalog: each public callable has a concise description. Generated
|
|
725
821
|
# from docstrings / readable names so help remains complete as the API grows.
|
|
726
822
|
_DESCRIPTIONS = {
|
|
727
|
-
"time":"
|
|
728
|
-
"datetime":"
|
|
823
|
+
"time":"Return the current local time.", "year":"Return the current year.", "date":"Return today's date.",
|
|
824
|
+
"datetime":"Return the current date and time.", "now":"Return the current local date and time as an object.",
|
|
825
|
+
"timer":"Wait for a number of seconds and return a completion message.",
|
|
826
|
+
"stopwatch":"Start and return a stopwatch with lap, stop, resume, and reset methods.",
|
|
729
827
|
"prank_fake_loading":"Return a harmless pretend loading message.",
|
|
730
828
|
"prank_pun":"Choose a harmless pun.", "prank_reversed":"Return text reversed as a harmless joke.",
|
|
731
829
|
"prank_computer_says":"Return a harmless pretend computer message.",
|
|
732
|
-
"randnum":"
|
|
830
|
+
"randnum":"Return a random integer between the inclusive limits.",
|
|
733
831
|
"close":"Exit the current Python program cleanly.",
|
|
734
832
|
"exit_program":"Exit the current Python program with an optional status code.",
|
|
735
833
|
"pause":"Wait for the user to press Enter.", "clear_screen":"Clear the current terminal screen.",
|
|
@@ -747,12 +845,14 @@ _DESCRIPTIONS = {
|
|
|
747
845
|
}
|
|
748
846
|
|
|
749
847
|
_SK_DESCRIPTIONS = {
|
|
750
|
-
"now":"
|
|
751
|
-
"year":"
|
|
752
|
-
"datetime":"
|
|
848
|
+
"now":"Vráti aktuálny miestny dátum a čas ako objekt.", "time":"Vráti aktuálny miestny čas.",
|
|
849
|
+
"year":"Vráti aktuálny rok.", "date":"Vráti dnešný dátum.",
|
|
850
|
+
"datetime":"Vráti aktuálny dátum a čas.", "timer":"Počká zadaný počet sekúnd a vráti správu o skončení časovača.",
|
|
851
|
+
"stopwatch":"Spustí stopky s meraním kôl, zastavením, obnovením a vynulovaním.",
|
|
852
|
+
"prank_fake_loading":"Vráti neškodnú falošnú správu o načítavaní.",
|
|
753
853
|
"prank_pun":"Vyberie neškodný vtip.", "prank_reversed":"Vráti text odzadu ako neškodný žart.",
|
|
754
854
|
"prank_computer_says":"Vráti neškodnú žartovnú hlášku počítača.",
|
|
755
|
-
"randnum":"
|
|
855
|
+
"randnum":"Vráti náhodné celé číslo vrátane zadaných hraníc.",
|
|
756
856
|
"close":"Bezpečne ukončí aktuálny Python program.",
|
|
757
857
|
"exit_program":"Ukončí Python program s voliteľným návratovým kódom.",
|
|
758
858
|
"pause":"Počká, kým používateľ stlačí Enter.", "clear_screen":"Vyčistí obrazovku terminálu.",
|
|
@@ -830,7 +930,7 @@ def help(command: str | None = None) -> None:
|
|
|
830
930
|
else:
|
|
831
931
|
print(f"Everycode {__version__} — {len(items)} commands\nUsage: import everycode as ec; ec.help('add')\n")
|
|
832
932
|
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"}],
|
|
933
|
+
("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","timer","stopwatch"}],
|
|
834
934
|
("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
935
|
("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
936
|
("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"}],
|
|
@@ -853,34 +953,4 @@ def help(command: str | None = None) -> None:
|
|
|
853
953
|
for name in rest: print(f" ec.{name} — {items[name]}")
|
|
854
954
|
|
|
855
955
|
|
|
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
956
|
__all__ = [*commands().keys(), "commands", "help", "sklang", "enlang", "__version__"]
|
|
@@ -8,9 +8,7 @@ from __future__ import annotations
|
|
|
8
8
|
|
|
9
9
|
import calendar as _calendar
|
|
10
10
|
import base64 as _base64
|
|
11
|
-
import contextvars as _contextvars
|
|
12
11
|
import datetime as _dt
|
|
13
|
-
import functools as _functools
|
|
14
12
|
import json as _json
|
|
15
13
|
import math as _math
|
|
16
14
|
import os as _os
|
|
@@ -26,7 +24,7 @@ import uuid as _uuid
|
|
|
26
24
|
from collections import Counter as _Counter
|
|
27
25
|
from typing import Any
|
|
28
26
|
|
|
29
|
-
__version__ = "1.0.
|
|
27
|
+
__version__ = "1.0.1"
|
|
30
28
|
_LANGUAGE = "en"
|
|
31
29
|
|
|
32
30
|
|
|
@@ -101,11 +99,75 @@ def wait(seconds: int | float) -> None:
|
|
|
101
99
|
"""Pause the current program for whole or fractional seconds."""
|
|
102
100
|
if isinstance(seconds, bool) or not isinstance(seconds, (int, float)):
|
|
103
101
|
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", "
|
|
102
|
+
if not _math.isfinite(seconds) or seconds < 0:
|
|
103
|
+
raise ValueError(_localized("seconds must be finite and non-negative", "čas musí byť konečné nezáporné číslo"))
|
|
106
104
|
_time.sleep(seconds)
|
|
107
105
|
|
|
108
106
|
|
|
107
|
+
def timer(seconds: int | float) -> str:
|
|
108
|
+
"""Wait for a duration, then return a completion message."""
|
|
109
|
+
if isinstance(seconds, bool) or not isinstance(seconds, (int, float)):
|
|
110
|
+
raise TypeError(_localized("seconds must be a number", "čas musí byť číslo"))
|
|
111
|
+
if not _math.isfinite(seconds) or seconds < 0:
|
|
112
|
+
raise ValueError(_localized("seconds must be finite and non-negative", "čas musí byť konečné nezáporné číslo"))
|
|
113
|
+
_time.sleep(seconds)
|
|
114
|
+
return _localized(f"Timer finished after {seconds:g} seconds.", f"Časovač skončil po {seconds:g} sekundách.")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class _Stopwatch:
|
|
118
|
+
"""A monotonic stopwatch returned by :func:`stopwatch`."""
|
|
119
|
+
def __init__(self) -> None:
|
|
120
|
+
self._started_at = _time.perf_counter()
|
|
121
|
+
self._elapsed_before = 0.0
|
|
122
|
+
self._lap_mark = 0.0
|
|
123
|
+
self._running = True
|
|
124
|
+
|
|
125
|
+
@property
|
|
126
|
+
def elapsed(self) -> float:
|
|
127
|
+
"""Elapsed seconds, including the current run if started."""
|
|
128
|
+
if self._running:
|
|
129
|
+
return self._elapsed_before + (_time.perf_counter() - self._started_at)
|
|
130
|
+
return self._elapsed_before
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def running(self) -> bool:
|
|
134
|
+
return self._running
|
|
135
|
+
|
|
136
|
+
def start(self) -> float:
|
|
137
|
+
"""Start or resume timing and return elapsed seconds."""
|
|
138
|
+
if not self._running:
|
|
139
|
+
self._started_at = _time.perf_counter()
|
|
140
|
+
self._running = True
|
|
141
|
+
return self.elapsed
|
|
142
|
+
|
|
143
|
+
def stop(self) -> float:
|
|
144
|
+
"""Stop timing and return total elapsed seconds."""
|
|
145
|
+
if self._running:
|
|
146
|
+
self._elapsed_before += _time.perf_counter() - self._started_at
|
|
147
|
+
self._running = False
|
|
148
|
+
return self._elapsed_before
|
|
149
|
+
|
|
150
|
+
def lap(self) -> float:
|
|
151
|
+
"""Return seconds since the previous lap (or start)."""
|
|
152
|
+
total = self.elapsed
|
|
153
|
+
result = total - self._lap_mark
|
|
154
|
+
self._lap_mark = total
|
|
155
|
+
return result
|
|
156
|
+
|
|
157
|
+
def reset(self) -> float:
|
|
158
|
+
"""Reset elapsed time and start timing again."""
|
|
159
|
+
self._elapsed_before = 0.0
|
|
160
|
+
self._lap_mark = 0.0
|
|
161
|
+
self._started_at = _time.perf_counter()
|
|
162
|
+
self._running = True
|
|
163
|
+
return 0.0
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def stopwatch() -> _Stopwatch:
|
|
167
|
+
"""Create and start a stopwatch; call its stop, lap, and reset methods."""
|
|
168
|
+
return _Stopwatch()
|
|
169
|
+
|
|
170
|
+
|
|
109
171
|
def json_dumps(value: Any, indent: int = 2, ensure_ascii: bool = False) -> str:
|
|
110
172
|
"""Convert a Python value to readable JSON text."""
|
|
111
173
|
return _json.dumps(value, indent=indent, ensure_ascii=ensure_ascii)
|
|
@@ -225,7 +287,7 @@ def weekday_number(day: _dt.date | None = None) -> int:
|
|
|
225
287
|
|
|
226
288
|
|
|
227
289
|
def month_name(month: int | None = None) -> str:
|
|
228
|
-
value =
|
|
290
|
+
value = _dt.date.today().month if month is None else month
|
|
229
291
|
if not 1 <= value <= 12: raise ValueError("month must be between 1 and 12")
|
|
230
292
|
sk = ("január", "február", "marec", "apríl", "máj", "jún", "júl", "august", "september", "október", "november", "december")[value-1]
|
|
231
293
|
return _localized(_calendar.month_name[value], sk)
|
|
@@ -233,12 +295,12 @@ def month_name(month: int | None = None) -> str:
|
|
|
233
295
|
|
|
234
296
|
def month_days(year: int | None = None, month: int | None = None) -> int:
|
|
235
297
|
d = today()
|
|
236
|
-
return _calendar.monthrange(year
|
|
298
|
+
return _calendar.monthrange(d.year if year is None else year, d.month if month is None else month)[1]
|
|
237
299
|
|
|
238
300
|
|
|
239
301
|
def calendar_month(year: int | None = None, month: int | None = None) -> str:
|
|
240
302
|
d = today()
|
|
241
|
-
value = _calendar.month(year
|
|
303
|
+
value = _calendar.month(d.year if year is None else year, d.month if month is None else month)
|
|
242
304
|
if _LANGUAGE == "sk":
|
|
243
305
|
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
306
|
value = value.replace(en, sk)
|
|
@@ -248,7 +310,7 @@ def calendar_month(year: int | None = None, month: int | None = None) -> str:
|
|
|
248
310
|
|
|
249
311
|
|
|
250
312
|
def is_leap_year(year: int | None = None) -> bool:
|
|
251
|
-
return _calendar.isleap(
|
|
313
|
+
return _calendar.isleap(today().year if year is None else year)
|
|
252
314
|
|
|
253
315
|
|
|
254
316
|
def add_days(days: int, start: _dt.date | None = None) -> _dt.date:
|
|
@@ -286,7 +348,10 @@ def power(a: float, b: float) -> float: return a ** b
|
|
|
286
348
|
def square(n: float) -> float: return n * n
|
|
287
349
|
def cube(n: float) -> float: return n ** 3
|
|
288
350
|
def sqrt(n: float) -> float: return _math.sqrt(n)
|
|
289
|
-
def cbrt(n: float) -> float:
|
|
351
|
+
def cbrt(n: float) -> float:
|
|
352
|
+
if hasattr(_math, "cbrt"):
|
|
353
|
+
return _math.cbrt(n)
|
|
354
|
+
return _math.copysign(abs(n) ** (1 / 3), n)
|
|
290
355
|
def absolute(n: float) -> float: return abs(n)
|
|
291
356
|
def negate(n: float) -> float: return -n
|
|
292
357
|
def sign(n: float) -> int: return (n > 0) - (n < 0)
|
|
@@ -472,7 +537,7 @@ def zip_lists(*items: Any) -> list[tuple[Any,...]]: return list(zip(*items))
|
|
|
472
537
|
# Randomness, identifiers and light-hearted pranks (all opt-in and harmless)
|
|
473
538
|
def random_int(low: int, high: int) -> int: return _random.randint(low,high)
|
|
474
539
|
def randnum(from_: int | None = None, to: int | None = None) -> int:
|
|
475
|
-
"""
|
|
540
|
+
"""Return a random integer from the inclusive lower to upper bound."""
|
|
476
541
|
from_label, to_label = ("od", "do") if _LANGUAGE == "sk" else ("from", "to")
|
|
477
542
|
missing = [label for value, label in ((from_, from_label), (to, to_label)) if value is None]
|
|
478
543
|
if missing:
|
|
@@ -492,7 +557,7 @@ def random_password(length: int = 16) -> str:
|
|
|
492
557
|
import secrets
|
|
493
558
|
alphabet=_string.ascii_letters+_string.digits+"!@#$%^&*"
|
|
494
559
|
return "".join(secrets.choice(alphabet) for _ in range(length))
|
|
495
|
-
def coin_flip() -> str: return _random.choice(["heads","tails"])
|
|
560
|
+
def coin_flip() -> str: return _localized(*_random.choice([("heads", "hlava"), ("tails", "orel")]))
|
|
496
561
|
def dice(sides: int = 6) -> int:
|
|
497
562
|
if sides < 2: raise ValueError("a die needs at least two sides")
|
|
498
563
|
return _random.randint(1,sides)
|
|
@@ -525,19 +590,45 @@ def random_choice_message(items: Any) -> str:
|
|
|
525
590
|
# Helpful formatting and validation
|
|
526
591
|
def format_number(n: float, decimals: int = 2) -> str: return f"{n:,.{decimals}f}"
|
|
527
592
|
def ordinal(n: int) -> str:
|
|
528
|
-
|
|
593
|
+
if _LANGUAGE == "sk":
|
|
594
|
+
return f"{n}."
|
|
595
|
+
value = abs(n)
|
|
596
|
+
suffix = "th" if 10 <= value % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(value % 10, "th")
|
|
597
|
+
return f"{n}{suffix}"
|
|
529
598
|
def bytes_human(n: int) -> str:
|
|
530
599
|
if n < 0: raise ValueError("n must be non-negative")
|
|
531
600
|
value=float(n)
|
|
532
601
|
for unit in ("B","KB","MB","GB","TB","PB"):
|
|
533
602
|
if value < 1024 or unit == "PB": return f"{value:.2f} {unit}"
|
|
534
603
|
value/=1024
|
|
535
|
-
def is_email(value: str) -> bool:
|
|
536
|
-
|
|
604
|
+
def is_email(value: str) -> bool:
|
|
605
|
+
if not isinstance(value, str) or any(c.isspace() for c in value) or value.count("@") != 1:
|
|
606
|
+
return False
|
|
607
|
+
local, domain = value.split("@")
|
|
608
|
+
return bool(local and domain and "." in domain and not domain.startswith(".") and not domain.endswith("."))
|
|
609
|
+
|
|
610
|
+
|
|
611
|
+
def is_url(value: str) -> bool:
|
|
612
|
+
if not isinstance(value, str) or any(c.isspace() for c in value):
|
|
613
|
+
return False
|
|
614
|
+
try:
|
|
615
|
+
parsed = _urlparse.urlsplit(value)
|
|
616
|
+
return parsed.scheme in {"http", "https"} and bool(parsed.hostname) and ("." in parsed.hostname or parsed.hostname == "localhost")
|
|
617
|
+
except ValueError:
|
|
618
|
+
return False
|
|
537
619
|
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
620
|
def is_integer(value: Any) -> bool:
|
|
539
|
-
|
|
540
|
-
|
|
621
|
+
if isinstance(value, bool):
|
|
622
|
+
return False
|
|
623
|
+
try:
|
|
624
|
+
converted = int(value)
|
|
625
|
+
if isinstance(value, str):
|
|
626
|
+
text = value.strip()
|
|
627
|
+
digits = text[1:] if text[:1] in {"+", "-"} else text
|
|
628
|
+
return bool(digits) and digits.isdecimal()
|
|
629
|
+
return value == converted
|
|
630
|
+
except (TypeError, ValueError, OverflowError):
|
|
631
|
+
return False
|
|
541
632
|
def is_alpha(text: str) -> bool: return text.isalpha()
|
|
542
633
|
def is_alphanumeric(text: str) -> bool: return text.isalnum()
|
|
543
634
|
def is_digit(text: str) -> bool: return text.isdigit()
|
|
@@ -562,7 +653,9 @@ def subtract_many(first: float, *values: float) -> float:
|
|
|
562
653
|
for value in values: first -= value
|
|
563
654
|
return first
|
|
564
655
|
def multiply_many(*values: float) -> float: return _math.prod(values)
|
|
565
|
-
def average_or_zero(values: Any) -> float:
|
|
656
|
+
def average_or_zero(values: Any) -> float:
|
|
657
|
+
values = list(values)
|
|
658
|
+
return _statistics.mean(values) if values else 0
|
|
566
659
|
def median_low(values: Any) -> Any: return _statistics.median_low(values)
|
|
567
660
|
def median_high(values: Any) -> Any: return _statistics.median_high(values)
|
|
568
661
|
def is_positive(n: float) -> bool: return n > 0
|
|
@@ -655,12 +748,13 @@ def random_number_string(length: int = 6) -> str:
|
|
|
655
748
|
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
749
|
def rock_paper_scissors(choice: str) -> str:
|
|
657
750
|
user=choice.casefold()
|
|
658
|
-
if user not in {"rock","paper","scissors","kameň","papier","nožnice"}: raise ValueError("choose rock
|
|
751
|
+
if user not in {"rock","paper","scissors","kameň","papier","nožnice"}: raise ValueError(_localized("choose rock, paper, or scissors", "vyber kameň, papier alebo nožnice"))
|
|
659
752
|
mapping={"rock":"kameň","paper":"papier","scissors":"nožnice","kameň":"kameň","papier":"papier","nožnice":"nožnice"}
|
|
660
753
|
mine=_random.choice(["kameň","papier","nožnice"]); theirs=mapping[user]
|
|
661
754
|
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
755
|
en_result = {"remíza":"draw", "vyhral si":"you win", "vyhral počítač":"the computer wins"}[result]
|
|
663
|
-
|
|
756
|
+
english_name={"kameň":"rock", "papier":"paper", "nožnice":"scissors"}
|
|
757
|
+
return _localized(f"You: {english_name[theirs]}; computer: {english_name[mine]}; {en_result}.",f"Ty: {theirs}; počítač: {mine}; {result}.")
|
|
664
758
|
def choose_for_me(*options: Any) -> Any:
|
|
665
759
|
if not options: raise ValueError("provide at least one option")
|
|
666
760
|
return _random.choice(options)
|
|
@@ -670,7 +764,7 @@ def silly_weather() -> str: return _pick_translation([("Cloudy with a chance of
|
|
|
670
764
|
def ascii_smile() -> str: return ":-)"
|
|
671
765
|
def ascii_table(rows: Any) -> str:
|
|
672
766
|
values=[list(map(str,row)) for row in rows]
|
|
673
|
-
if not values: return ""
|
|
767
|
+
if not values or not any(values): return ""
|
|
674
768
|
widths=[max(len(row[i]) if i<len(row) else 0 for row in values) for i in range(max(map(len,values)))]
|
|
675
769
|
return "\n".join(" | ".join(value.ljust(widths[i]) for i,value in enumerate(row)) for row in values)
|
|
676
770
|
def format_duration(seconds: float) -> str:
|
|
@@ -697,7 +791,9 @@ def hex_to_int(value: str) -> int: return int(value,16)
|
|
|
697
791
|
def octal_to_int(value: str) -> int: return int(value,8)
|
|
698
792
|
def fraction(numerator: int, denominator: int) -> tuple[int,int]:
|
|
699
793
|
if denominator == 0: raise ZeroDivisionError("denominator must not be zero")
|
|
700
|
-
divisor=_math.gcd(numerator,denominator)
|
|
794
|
+
divisor=_math.gcd(numerator,denominator)
|
|
795
|
+
numerator, denominator = numerator//divisor, denominator//divisor
|
|
796
|
+
return (-numerator, -denominator) if denominator < 0 else (numerator, denominator)
|
|
701
797
|
def digit_count(n: int) -> int: return len(str(abs(n)))
|
|
702
798
|
def sum_digits(n: int) -> int: return digit_sum(n)
|
|
703
799
|
def is_perfect_square(n: int) -> bool: return n>=0 and _math.isqrt(n)**2==n
|
|
@@ -724,12 +820,14 @@ def try_float(value: Any, default: Any = None) -> Any:
|
|
|
724
820
|
# Help catalog: each public callable has a concise description. Generated
|
|
725
821
|
# from docstrings / readable names so help remains complete as the API grows.
|
|
726
822
|
_DESCRIPTIONS = {
|
|
727
|
-
"time":"
|
|
728
|
-
"datetime":"
|
|
823
|
+
"time":"Return the current local time.", "year":"Return the current year.", "date":"Return today's date.",
|
|
824
|
+
"datetime":"Return the current date and time.", "now":"Return the current local date and time as an object.",
|
|
825
|
+
"timer":"Wait for a number of seconds and return a completion message.",
|
|
826
|
+
"stopwatch":"Start and return a stopwatch with lap, stop, resume, and reset methods.",
|
|
729
827
|
"prank_fake_loading":"Return a harmless pretend loading message.",
|
|
730
828
|
"prank_pun":"Choose a harmless pun.", "prank_reversed":"Return text reversed as a harmless joke.",
|
|
731
829
|
"prank_computer_says":"Return a harmless pretend computer message.",
|
|
732
|
-
"randnum":"
|
|
830
|
+
"randnum":"Return a random integer between the inclusive limits.",
|
|
733
831
|
"close":"Exit the current Python program cleanly.",
|
|
734
832
|
"exit_program":"Exit the current Python program with an optional status code.",
|
|
735
833
|
"pause":"Wait for the user to press Enter.", "clear_screen":"Clear the current terminal screen.",
|
|
@@ -747,12 +845,14 @@ _DESCRIPTIONS = {
|
|
|
747
845
|
}
|
|
748
846
|
|
|
749
847
|
_SK_DESCRIPTIONS = {
|
|
750
|
-
"now":"
|
|
751
|
-
"year":"
|
|
752
|
-
"datetime":"
|
|
848
|
+
"now":"Vráti aktuálny miestny dátum a čas ako objekt.", "time":"Vráti aktuálny miestny čas.",
|
|
849
|
+
"year":"Vráti aktuálny rok.", "date":"Vráti dnešný dátum.",
|
|
850
|
+
"datetime":"Vráti aktuálny dátum a čas.", "timer":"Počká zadaný počet sekúnd a vráti správu o skončení časovača.",
|
|
851
|
+
"stopwatch":"Spustí stopky s meraním kôl, zastavením, obnovením a vynulovaním.",
|
|
852
|
+
"prank_fake_loading":"Vráti neškodnú falošnú správu o načítavaní.",
|
|
753
853
|
"prank_pun":"Vyberie neškodný vtip.", "prank_reversed":"Vráti text odzadu ako neškodný žart.",
|
|
754
854
|
"prank_computer_says":"Vráti neškodnú žartovnú hlášku počítača.",
|
|
755
|
-
"randnum":"
|
|
855
|
+
"randnum":"Vráti náhodné celé číslo vrátane zadaných hraníc.",
|
|
756
856
|
"close":"Bezpečne ukončí aktuálny Python program.",
|
|
757
857
|
"exit_program":"Ukončí Python program s voliteľným návratovým kódom.",
|
|
758
858
|
"pause":"Počká, kým používateľ stlačí Enter.", "clear_screen":"Vyčistí obrazovku terminálu.",
|
|
@@ -830,7 +930,7 @@ def help(command: str | None = None) -> None:
|
|
|
830
930
|
else:
|
|
831
931
|
print(f"Everycode {__version__} — {len(items)} commands\nUsage: import everycode as ec; ec.help('add')\n")
|
|
832
932
|
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"}],
|
|
933
|
+
("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","timer","stopwatch"}],
|
|
834
934
|
("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
935
|
("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
936
|
("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"}],
|
|
@@ -853,34 +953,4 @@ def help(command: str | None = None) -> None:
|
|
|
853
953
|
for name in rest: print(f" ec.{name} — {items[name]}")
|
|
854
954
|
|
|
855
955
|
|
|
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
956
|
__all__ = [*commands().keys(), "commands", "help", "sklang", "enlang", "__version__"]
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: everycode
|
|
3
|
+
Version: 1.0.2
|
|
4
|
+
Summary: A standard-library Python toolkit for time, math, text, collections, conversions, encoding, paths, timers, and developer utilities
|
|
5
|
+
Author: Patrick Pustai
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: python,everycode,utilities,time,math,text,encoding,stopwatch,timer
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# Everycode
|
|
14
|
+
|
|
15
|
+
Everycode is a beginner-friendly Python utility library with hundreds of small, practical commands. It uses only Python's standard library and provides helpers for dates and time, arithmetic, statistics, geometry, unit conversion, text, lists, validation, JSON, URL and Base64 encoding, files and paths, random values, and program control.
|
|
16
|
+
|
|
17
|
+
Everycode works on Python 3.10 and later. Its commands return values, so use `print(...)` when you want to show a result. Importing the library does not print output or start timers.
|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pip install everycode
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Quick start
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
# Here are some commands for EveryCode
|
|
29
|
+
# Look to ec.help() for more commands
|
|
30
|
+
import everycode as ec
|
|
31
|
+
print("Welcome to EveryCode library!")
|
|
32
|
+
print(f"Current time: {ec.time()}")
|
|
33
|
+
print(ec.url_encode("Hello, World!"))
|
|
34
|
+
print(ec.platform_name())
|
|
35
|
+
print(ec.factorial(5))
|
|
36
|
+
print(ec.weekday())
|
|
37
|
+
ec.wait(1)
|
|
38
|
+
print(ec.date())
|
|
39
|
+
print(ec.base64_encode("EveryCode"))
|
|
40
|
+
print(ec.base64_decode("RXZlcnlDb2Rl"))
|
|
41
|
+
print(ec.roman_numeral(2026))
|
|
42
|
+
print(ec.is_email("everycode@example.com"))
|
|
43
|
+
print(ec.prank_computer_says())
|
|
44
|
+
print(ec.coin_flip())
|
|
45
|
+
print(ec.char_count("EveryCode is Python library"))
|
|
46
|
+
print(ec.is_negative(58))
|
|
47
|
+
ec.pause()
|
|
48
|
+
print(ec.ascii_smile())
|
|
49
|
+
ec.clear_screen()
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Timers and stopwatch
|
|
53
|
+
|
|
54
|
+
`timer` waits for the requested duration, then returns a completion message:
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
print(ec.timer(1.5))
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
`stopwatch` starts a stopwatch and returns an object that can measure laps,
|
|
61
|
+
stop, resume, and reset:
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
watch = ec.stopwatch()
|
|
65
|
+
# Do some work here.
|
|
66
|
+
print(watch.lap()) # seconds since start or previous lap
|
|
67
|
+
print(watch.stop()) # total elapsed seconds
|
|
68
|
+
watch.start() # resume
|
|
69
|
+
watch.reset() # reset and start again
|
|
70
|
+
print(watch.elapsed)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Discover commands
|
|
74
|
+
|
|
75
|
+
Use `ec.help()` to see all documented commands grouped by category. It includes
|
|
76
|
+
the total number of public commands. Use `ec.help("command_name")` for one
|
|
77
|
+
command's signature and description. `ec.commands()` returns the catalog as a
|
|
78
|
+
mapping of names to descriptions.
|
|
79
|
+
|
|
80
|
+
The help and supported text utilities can display English and Slovak text.
|
|
81
|
+
|
|
82
|
+
## More examples
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
print(ec.average([3, 5, 8]))
|
|
86
|
+
print(ec.slugify("A Useful Page Title"))
|
|
87
|
+
print(ec.new_id())
|
|
88
|
+
print(ec.path_exists("README.md"))
|
|
89
|
+
```
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
|
|
2
|
+
[build-system]
|
|
3
|
+
requires = ["setuptools>=77.0.0", "wheel"]
|
|
4
|
+
build-backend = "setuptools.build_meta"
|
|
5
|
+
|
|
6
|
+
[project]
|
|
7
|
+
name = "everycode"
|
|
8
|
+
version = "1.0.2"
|
|
9
|
+
description = "A standard-library Python toolkit for time, math, text, collections, conversions, encoding, paths, timers, and developer utilities"
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
license = "MIT"
|
|
13
|
+
authors = [
|
|
14
|
+
{name = "Patrick Pustai"}
|
|
15
|
+
]
|
|
16
|
+
keywords = ["python", "everycode", "utilities", "time", "math", "text", "encoding", "stopwatch", "timer"]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Operating System :: OS Independent"
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
[tool.setuptools]
|
|
23
|
+
packages = ["everycode"]
|
everycode-1.0.0/PKG-INFO
DELETED
|
@@ -1,59 +0,0 @@
|
|
|
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.
|
everycode-1.0.0/README.md
DELETED
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
# everycode
|
|
2
|
-
|
|
3
|
-
Everycode is a beginner-friendly Python helper library with date and time,
|
|
4
|
-
math, geometry, conversions, text tools, list helpers, validation, random
|
|
5
|
-
utilities, and opt-in harmless joke functions. It uses only Python's standard
|
|
6
|
-
library and does nothing when imported.
|
|
7
|
-
|
|
8
|
-
## Install
|
|
9
|
-
|
|
10
|
-
From this folder:
|
|
11
|
-
|
|
12
|
-
```bash
|
|
13
|
-
python -m pip install .
|
|
14
|
-
```
|
|
15
|
-
|
|
16
|
-
## Quick start
|
|
17
|
-
|
|
18
|
-
```python
|
|
19
|
-
import everycode as ec
|
|
20
|
-
|
|
21
|
-
ec.time() # prints the time and also returns it
|
|
22
|
-
ec.year() # prints the current year
|
|
23
|
-
ec.date() # prints YYYY-MM-DD
|
|
24
|
-
ec.datetime() # prints local date and time
|
|
25
|
-
ec.add(4, 5) # prints 9 and returns 9
|
|
26
|
-
ec.celsius_to_fahrenheit(20)
|
|
27
|
-
ec.prank_pun() # prints a harmless joke and returns it
|
|
28
|
-
|
|
29
|
-
ec.help() # categorized list of every command
|
|
30
|
-
ec.help("add") # details about one command
|
|
31
|
-
|
|
32
|
-
ec.sklang() # switch subsequent messages/help to Slovak
|
|
33
|
-
ec.prank_reversed("Ahoj!")
|
|
34
|
-
ec.enlang() # switch back to English
|
|
35
|
-
ec.json_dumps({"name": "Everycode"})
|
|
36
|
-
ec.url_encode("hello world")
|
|
37
|
-
ec.new_id()
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
English is the default language. `ec.sklang()` and `ec.enlang()` change the
|
|
41
|
-
language used by help and localized text helpers for the rest of the program.
|
|
42
|
-
These two language switches are intentionally omitted from `ec.help()`.
|
|
43
|
-
|
|
44
|
-
Commands shown by `ec.help()` print their result automatically and also return
|
|
45
|
-
it, so you can still save it in a variable, for example `answer = ec.add(4, 5)`.
|
|
46
|
-
The helper `ec.commands()` returns a mapping of command names to descriptions.
|
|
47
|
-
The language switches only change the language used by supported text outputs;
|
|
48
|
-
they do not print anything themselves.
|
|
49
|
-
|
|
50
|
-
See [PUBLISHING.md](PUBLISHING.md) for the step-by-step PyPI publishing guide.
|
|
@@ -1,59 +0,0 @@
|
|
|
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.
|
everycode-1.0.0/pyproject.toml
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
[build-system]
|
|
2
|
-
requires = ["setuptools>=68"]
|
|
3
|
-
build-backend = "setuptools.build_meta"
|
|
4
|
-
|
|
5
|
-
[project]
|
|
6
|
-
name = "everycode"
|
|
7
|
-
version = "1.0.0"
|
|
8
|
-
description = "A friendly collection of everyday Python helper commands"
|
|
9
|
-
readme = "README.md"
|
|
10
|
-
requires-python = ">=3.10"
|
|
11
|
-
license = "MIT"
|
|
12
|
-
authors = [{name = "Everycode contributors"}]
|
|
13
|
-
|
|
14
|
-
[tool.setuptools]
|
|
15
|
-
packages = ["everycode"]
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|