dossenge 1.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.
Dossenge/Dossenge.py ADDED
@@ -0,0 +1,78 @@
1
+ import sys
2
+ import os
3
+ import toml
4
+
5
+ def get_module_installation_path(module_name):
6
+ try:
7
+ # 导入指定的模块
8
+ module = __import__(module_name)
9
+ # 获取模块的文件路径
10
+ module_path = module.__file__
11
+ # print(f"模块 {module_name} 的安装路径是: {module_path}")
12
+ return module_path
13
+ except ImportError:
14
+ # print(f"模块 {module_name} 未安装或无法导入。")
15
+ return None
16
+ except AttributeError:
17
+ # print(f"模块 {module_name} 没有 __file__ 属性,可能是一个内置模块。")
18
+ return None
19
+
20
+ current_file_path = os.path.abspath(get_module_installation_path("Dossenge"))
21
+ current_dir = os.path.dirname(current_file_path)
22
+ os.chdir(current_dir)
23
+ namer = {'posix':'/','nt':'\\'}
24
+ char = namer[os.name]
25
+
26
+
27
+
28
+ def equal(x, y, roundnum=3):
29
+ diff = abs(x - y)
30
+ return diff < 10**-roundnum
31
+
32
+ def chicken_rabbit(head,foot):
33
+ chicken = head
34
+ rabbit = 0
35
+ solutions = []
36
+ for i in range(1,head+2):
37
+ if chicken*2+rabbit*4 == foot:
38
+ solutions.append((chicken, rabbit))
39
+ chicken -= 1
40
+ rabbit += 1
41
+ return solutions
42
+
43
+ def dossenge():
44
+ # # # with open(file,'r') as f:
45
+ # # # equal = f.readline(0)
46
+ # # # cr = f.readline(1)
47
+ # more
48
+ # # # with open(current_dir+char+'config.toml','r') as f:
49
+ # # # data = toml.load(f)
50
+ # # # file = f'{data["path"]}/{data["lang"]}{data["ext"]}'
51
+ equal = '判断两数是否相等'
52
+ cr = '解决鸡兔同笼问题'
53
+ try:
54
+ if sys.argv[1]=='equal':
55
+ print(equal(eval(sys.argv[2]),eval(sys.argv[3]),roundnum=eval(sys.argv[4])))
56
+ elif sys.argv[1]=='cr':
57
+ print(chicken_rabbit(eval(sys.argv[2]),eval(sys.argv[3])))
58
+ else:
59
+ print('Usage:')
60
+ print(f'equal : {equal}')
61
+ print(f'cr : {cr}')
62
+ except:
63
+ print('Usage:')
64
+ print(f'equal : {equal}')
65
+ print(f'cr : {cr}')
66
+
67
+ def fibonacci(number):
68
+ if number < 0:
69
+ raise ValueError('number cannot be < 0')
70
+ elif number == 0:
71
+ return 0
72
+ elif number == 1:
73
+ return 1
74
+ else:
75
+ return fibonacci(number-1)+fibonacci(number-2)
76
+
77
+ if __name__ == '__main__':
78
+ pass
Dossenge/__init__.py ADDED
@@ -0,0 +1 @@
1
+ from .Dossenge import *
@@ -0,0 +1,91 @@
1
+ # from abc import ABC, abstractmethod
2
+ undefined = type('undefined', (object, ), {})()
3
+
4
+ class array(object):
5
+ def __init__(self, size, typ, *, default_factory=None):
6
+ if not isinstance(size, int) or size < 0:
7
+ raise ValueError("size must be a non-negative integer")
8
+ self.size = size
9
+ self.typ = typ
10
+ self._data = [None] * size if default_factory is None else [default_factory() for _ in range(size)]
11
+
12
+ # ---------- 读 ----------
13
+ def __getitem__(self, index):
14
+ if isinstance(index, slice):
15
+ return [self._data[i] for i in self._slice_indices(index)]
16
+ # 普通下标
17
+ idx = self._norm_index(index)
18
+ return self._data[idx]
19
+
20
+ # ---------- 写 ----------
21
+ def __setitem__(self, index, value):
22
+ if isinstance(index, slice):
23
+ indices = self._slice_indices(index)
24
+ if len(indices) != len(value):
25
+ raise ValueError("attempt to assign sequence of size "
26
+ f"{len(value)} to slice of size {len(indices)}")
27
+ for i, v in zip(indices, value):
28
+ self._validate_and_set(i, v)
29
+ else:
30
+ idx = self._norm_index(index)
31
+ self._validate_and_set(idx, value)
32
+
33
+ # ---------- 内部工具 ----------
34
+ def _norm_index(self, idx):
35
+ """把任意整数下标转成 0<=idx<size"""
36
+ if idx < 0:
37
+ idx += self.size
38
+ if not 0 <= idx < self.size:
39
+ raise IndexError("array index out of range")
40
+ return idx
41
+
42
+ def _slice_indices(self, s):
43
+ """返回 slice 对应的真实下标列表,支持负步长"""
44
+ if s.step is None or s.step > 0:
45
+ base = range(self.size)
46
+ else: # 负步长
47
+ base = range(self.size - 1, -1, -1)
48
+ return list(base)[s]
49
+
50
+ def _validate_and_set(self, idx, val):
51
+ if not isinstance(val, self.typ):
52
+ raise TypeError(f"Expected {self.typ.__name__}, got {type(val).__name__}")
53
+ self._data[idx] = val
54
+
55
+ # ---------- 其余保持原样 ---------
56
+
57
+ def __len__(self):
58
+ return self.size
59
+
60
+ def __iter__(self):
61
+ return iter(self._data)
62
+
63
+ def __repr__(self):
64
+ return f"array(size={self.size}, typ={self.typ.__name__})"
65
+
66
+ def __str__(self):
67
+ return f"{self.typ.__name__}[{self.size}]: {self._data}"
68
+
69
+ def printchar(self):
70
+ if self.typ is char:
71
+ for i in self._data:
72
+ print(i, end="")
73
+ else:
74
+ raise TypeError("printchar(): self.typ must be char")
75
+
76
+
77
+ class arrayable_class_meta(type):
78
+ def __getitem__(cls, size):
79
+ factory = getattr(cls, "__array_default_factory__", None)
80
+ return array(size=size, typ=cls, default_factory=factory)
81
+
82
+ class arrayable_class(metaclass=arrayable_class_meta):
83
+ pass
84
+
85
+ def arrayable(cls):
86
+ """装饰器:把 cls 的元类换成 arrayable_class_meta"""
87
+ # 动态创建一个新元类,复用已有逻辑
88
+ new_meta = type('arrayable_meta_for_' + cls.__name__,
89
+ (arrayable_class_meta,), {})
90
+ # 用新元类重新生成类
91
+ return new_meta(cls.__name__, cls.__bases__, dict(cls.__dict__))
Dossenge/http.py ADDED
@@ -0,0 +1,10 @@
1
+ import requests
2
+
3
+ def header_request(url,**headers):
4
+ try:
5
+ response = requests.get(url,headers=headers)
6
+ response.raise_for_status()
7
+ return response
8
+ except requests.RequestException as e:
9
+ raise Exception('Connection Error')
10
+
Dossenge/package.py ADDED
@@ -0,0 +1,4 @@
1
+ import subprocess
2
+ import sys
3
+ def install(package):
4
+ subprocess.check_call([sys.executable, '-m', 'pip', 'install', package])
Dossenge/stdio.py ADDED
@@ -0,0 +1,57 @@
1
+ from . import arrayable_class
2
+
3
+ def printf(text, *formatter):
4
+ print(str(text) % formatter)
5
+
6
+ @arrayable_class.arrayable
7
+ class char(object):
8
+ def __init__(self, value):
9
+ try:
10
+ self.value = chr(value)
11
+ except Exception:
12
+ if len(str(value)) != 1:
13
+ raise ValueError("Invalid byte. ")
14
+ self.value = str(value)
15
+ def __str__(self):
16
+ return self.value
17
+ def __repr__(self):
18
+ return f"{self.__class__}({self.value})"
19
+ def __eq__(self,o):
20
+ return self.value == o.value
21
+ def __lt__(self,o):
22
+ return ord(self.value) < ord(o.value)
23
+ def __gt__(self,o):
24
+ return ord(self.value) > ord(o.value)
25
+ def __le__(self,o):
26
+ return ord(self.value) <= ord(o.value)
27
+ def __ge__(self,o):
28
+ return ord(self.value) >= ord(o.value)
29
+ def __int__(self):
30
+ return ord(self.value)
31
+ # 可选:支持 ord(c) 直接返回 int
32
+ def __index__(self):
33
+ return self.__int__()
34
+ def __setattr__(self, key, value):
35
+ if hasattr(self, 'value'):
36
+ raise TypeError("'char' object does not support item assignment")
37
+ super().__setattr__(key, value)
38
+
39
+ class struct(object):
40
+ def __init__(self, **kwargs):
41
+ # 定义允许的属性及其类型
42
+ self._allowed_attributes = {key: type(value) for key, value in kwargs.items()}
43
+ # 设置初始属性值
44
+ for key, value in kwargs.items():
45
+ setattr(self, key, value)
46
+
47
+ def __setattr__(self, key, value):
48
+ # 检查是否是私有属性或已定义的属性
49
+ if key.startswith("_") or key in self._allowed_attributes:
50
+ # 检查类型是否匹配
51
+ if key in self._allowed_attributes and not isinstance(value, self._allowed_attributes[key]):
52
+ raise TypeError(f"Attribute '{key}' must be of type {self._allowed_attributes[key].__name__}")
53
+ super().__setattr__(key, value)
54
+ else:
55
+ # 防止动态添加新属性
56
+ raise AttributeError(f"Cannot add new attribute '{key}' dynamically")
57
+
Dossenge/string.py ADDED
@@ -0,0 +1,52 @@
1
+ import toml
2
+ import os
3
+ import sys
4
+ def get_module_installation_path(module_name):
5
+ try:
6
+ # 导入指定的模块
7
+ module = __import__(module_name)
8
+ # 获取模块的文件路径
9
+ module_path = module.__file__
10
+ # print(f"模块 {module_name} 的安装路径是: {module_path}")
11
+ return module_path
12
+ except ImportError:
13
+ # print(f"模块 {module_name} 未安装或无法导入。")
14
+ return None
15
+ except AttributeError:
16
+ # print(f"模块 {module_name} 没有 __file__ 属性,可能是一个内置模块。")
17
+ return None
18
+
19
+ current_file_path = os.path.abspath(get_module_installation_path("Dossenge"))
20
+ current_dir = os.path.dirname(current_file_path)
21
+ os.chdir(current_dir)
22
+ namer = {'posix':'/','nt':'\\'}
23
+ char = namer[os.name]
24
+ # with open(current_dir+char+'config.toml','r') as f:
25
+ # data = toml.load(f)
26
+
27
+ class String():
28
+ def __init__(self,value=None,file=None):
29
+ if not file == None:
30
+ self.file = file
31
+ with open(file,'r') as f:
32
+ self.value = f.readlines()
33
+ elif not value == None:
34
+ self.value = value
35
+ else:
36
+ raise SyntaxError('invalid syntax')
37
+
38
+ def countstr(st):
39
+ output = {}
40
+ for i in st:
41
+ if i in output:
42
+ output[i] += 1
43
+ else:
44
+ output[i] = 1
45
+ return output
46
+
47
+ def save_add(filepath,string):
48
+ with open(filepath,'a') as f:
49
+ f.write(string)
50
+ with open(filepath,'r') as f:
51
+ content = f.readlines()
52
+ return content
@@ -0,0 +1,108 @@
1
+ Metadata-Version: 2.1
2
+ Name: dossenge
3
+ Version: 1.0
4
+ Summary: Dossenge 1.0
5
+ Home-page: http://github.com/Dossenge/Dossenge.git
6
+ Author: Dossenge
7
+ Requires-Python: >=3.5
8
+ Description-Content-Type: text/markdown
9
+ Requires-Dist: toml
10
+ Requires-Dist: requests
11
+
12
+ # Dossenge - 一个包含很常用功能的Python库
13
+
14
+
15
+ ## 项目介绍
16
+ Dossenge 是一个为 Python 开发者设计的实用工具库,旨在提供一些常用的功能,帮助开发者快速解决问题。这个库特别适合初学者和需要快速实现某些功能的开发者。
17
+
18
+ ## 主模块
19
+
20
+ ### 方法列表
21
+
22
+ **引入方法:**
23
+ `from Dossenge import Dossenge`或`from Dossenge.Dossenge import *`或`import Dossenge`
24
+
25
+ **方法列表:**
26
+ ```python
27
+ Dossenge.equal(x, y, roundnum=3) # 判断x与y的差是否小于10**-roundnum(精度影响,可自行设置精度)
28
+ Dossenge.chicken_rabbit(head, foot) # 计算鸡兔同笼问题,head个头,foot条腿 返回[(chicken,rabbit)]
29
+ Dossenge.fibonacci(number) #计算斐波那契数列的第number项
30
+ ```
31
+
32
+ ## 字符串处理
33
+
34
+ **引入Dossenge.string方法:**
35
+ `from Dossenge import string`或`from Dossenge.string import *`
36
+
37
+ **方法列表:**
38
+ ```python
39
+ Dossenge.string.String # 类: 目前没有用处,敬请期待
40
+ Dossenge.string.countstr(string) # 以字典形式返回字符串中字符的个数
41
+ Dossenge.string.save_add(filepath,string) # 往filepath文件中增加写入string然后返回新的内容
42
+ ```
43
+
44
+ ## HTTP 请求
45
+
46
+ **引入方法:** `from Dossenge.http import *`
47
+
48
+ **方法列表:**
49
+ ```python
50
+ Dossenge.http.header_request(url, **headers) # 发送带有自定义请求头的 HTTP 请求
51
+ ```
52
+
53
+ **示例:**
54
+
55
+ ```python
56
+ from Dossenge.http import header_request
57
+
58
+ # 自定义请求头
59
+ headers = {
60
+ "User-Agent": "MyApp/1.0",
61
+ "Authorization": "Bearer mytoken",
62
+ "Accept": "application/json"
63
+ }
64
+
65
+ # 发送请求
66
+ response = header_request("https://api.example.com/data", **headers)
67
+
68
+ # 打印响应内容
69
+ if response:
70
+ print(response.json())
71
+
72
+ ```
73
+
74
+ ## 可数组类
75
+
76
+ **引入方法:** `from Dossenge.arrayable_class import *`
77
+
78
+ **方法列表:**
79
+ ```python
80
+ Dossenge.arrayable_class.arrayable(func) # 类装饰器,用于类可数组,使用MyClass[size]
81
+ Dossenge.arrayable_class.Array(size, typ) # 数组类
82
+ Dossenge.arrayable_class.arrayable_class_meta() # 可数组类元类
83
+ Dossenge.arrayable_class.arrayable_class() # 空基类,可继承
84
+ ```
85
+
86
+ **示例:**
87
+
88
+ ```python
89
+ from Dossenge.arrayable_class import arrayable_class
90
+
91
+ class MyClass(arrayable_class):
92
+ pass
93
+
94
+ arr = MyClass[5]
95
+
96
+
97
+ ```
98
+
99
+ ## 可执行文件
100
+ ```bash
101
+ dossenge equal 0.1+0.2 0.3 5
102
+ ```
103
+ 判断x与y的差是否小于10\*\*-5
104
+
105
+ ```bash
106
+ dossenge cr head foot
107
+ ```
108
+ 解决鸡兔同笼问题
@@ -0,0 +1,12 @@
1
+ Dossenge/Dossenge.py,sha256=isAj4R7eim7eb1N3rdup1s3APufpscVes4E2u6JC5Zs,2319
2
+ Dossenge/__init__.py,sha256=DyW73w74ukBjqvkEORgfuKfAHy36GJo5yqNB0Fo3icg,23
3
+ Dossenge/arrayable_class.py,sha256=fec3PTTpXi3mkPGM9fN_MCSZjdWmhYAtnEzOQROC-qI,3310
4
+ Dossenge/http.py,sha256=YZI4um3sOD3BGNS7Rw9-jkSJOCF5lTCJYWziZr84Dis,272
5
+ Dossenge/package.py,sha256=E2JiTjLpN3qHmuyvcU97p-q2UAYqTn_UjKU6rY1pW8I,132
6
+ Dossenge/stdio.py,sha256=uGDaNURClQNGkwzBShJtNmwCC8uaPWHY9ZJ9eHdrfrY,2145
7
+ Dossenge/string.py,sha256=dHWROVlup23A0CAaBB39yQG-OH1O1dWrG7yvMJGydzI,1593
8
+ dossenge-1.0.dist-info/METADATA,sha256=YM3UANozsWNCRmdH2d7RsiLYV2qjRI1h0o_hOGN6XqY,2795
9
+ dossenge-1.0.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
10
+ dossenge-1.0.dist-info/entry_points.txt,sha256=5wgNL4jhbOBvZsxAAp2juAgtuKyqud6MdsMpDduQNS4,56
11
+ dossenge-1.0.dist-info/top_level.txt,sha256=YBnDGrwVBirWpxi35Oex-cuwGFUuIjU371In7N3oEPQ,9
12
+ dossenge-1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.6.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ dossenge = Dossenge.Dossenge:dossenge
@@ -0,0 +1 @@
1
+ Dossenge