bool-hybrid-array 9.5.0__py3-none-any.whl → 9.10.19__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.
- bool_hybrid_array/__init__.py +35 -4
- bool_hybrid_array/__main__.py +284 -0
- bool_hybrid_array/core.py +325 -63
- bool_hybrid_array/int_array/__init__.py +203 -0
- bool_hybrid_array//321/207/320/267/320/250/321/205/320/277/320/226.md +2 -0
- bool_hybrid_array-9.10.19.dist-info/METADATA +596 -0
- bool_hybrid_array-9.10.19.dist-info/RECORD +10 -0
- bool_hybrid_array-9.5.0.dist-info/METADATA +0 -393
- bool_hybrid_array-9.5.0.dist-info/RECORD +0 -7
- {bool_hybrid_array-9.5.0.dist-info → bool_hybrid_array-9.10.19.dist-info}/WHEEL +0 -0
- {bool_hybrid_array-9.5.0.dist-info → bool_hybrid_array-9.10.19.dist-info}/licenses/LICENSE +0 -0
- {bool_hybrid_array-9.5.0.dist-info → bool_hybrid_array-9.10.19.dist-info}/top_level.txt +0 -0
bool_hybrid_array/core.py
CHANGED
|
@@ -2,27 +2,104 @@ from __future__ import annotations
|
|
|
2
2
|
import builtins
|
|
3
3
|
import array,bisect,numpy as np
|
|
4
4
|
from collections.abc import MutableSequence,Iterable,Generator,Iterator,Sequence
|
|
5
|
-
import itertools,copy,sys,math,weakref
|
|
5
|
+
import itertools,copy,sys,math,weakref,random,mmap,os
|
|
6
6
|
from functools import reduce
|
|
7
|
-
import operator,ctypes,gc,abc
|
|
7
|
+
import operator,ctypes,gc,abc,types
|
|
8
|
+
from functools import lru_cache
|
|
9
|
+
from typing import Union,_GenericAlias
|
|
8
10
|
hybrid_array_cache = []
|
|
9
|
-
|
|
10
|
-
class
|
|
11
|
+
if 'UnionType' in types.__dict__:
|
|
12
|
+
class Union:
|
|
13
|
+
def __getitem__(self,*args):
|
|
14
|
+
return reduce(operator.or_, args)
|
|
15
|
+
Union = Union()
|
|
16
|
+
if 'GenericAlias' in types.__dict__:
|
|
17
|
+
_GenericAlias = types.GenericAlias
|
|
18
|
+
class ResurrectMeta(abc.ABCMeta,metaclass=abc.ABCMeta):
|
|
19
|
+
__module__ = 'bool_hybrid_array'
|
|
20
|
+
name = 'ResurrectMeta'
|
|
11
21
|
def __new__(cls, name, bases, namespace):
|
|
12
22
|
meta_bases = tuple(type(base) for base in bases)
|
|
13
23
|
if cls not in meta_bases:
|
|
14
24
|
meta_bases = (cls,) + meta_bases
|
|
15
|
-
|
|
16
|
-
|
|
25
|
+
obj = super().__new__(cls, name, bases, namespace)
|
|
26
|
+
super_cls = super(ResurrectMeta, obj)
|
|
27
|
+
super_cls.__setattr__('x',None)
|
|
28
|
+
super_cls.__setattr__('name', name)
|
|
29
|
+
super_cls.__setattr__('bases', bases)
|
|
30
|
+
super_cls.__setattr__('namespace', namespace)
|
|
31
|
+
super_cls.__setattr__('original_dict', dict(obj.__dict__))
|
|
32
|
+
del obj.original_dict["__abstractmethods__"]
|
|
33
|
+
del obj.original_dict["_abc_impl"]
|
|
34
|
+
return obj
|
|
35
|
+
@lru_cache
|
|
17
36
|
def __str__(cls):
|
|
18
|
-
return super().
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
37
|
+
return super().__repr__()[8:][:-2]
|
|
38
|
+
@lru_cache
|
|
39
|
+
def __repr__(cls,detailed = False):
|
|
40
|
+
if detailed:
|
|
41
|
+
name, bases, namespace = cls.name,cls.bases,cls.namespace
|
|
42
|
+
return f'ResurrectMeta(cls = {cls},{name = },{bases = },{namespace = })'
|
|
43
|
+
return str(cls)
|
|
22
44
|
def __del__(cls):
|
|
23
45
|
exec(f"builtins.{cls.__name__} = cls")
|
|
24
46
|
if not sys.is_finalizing():
|
|
47
|
+
print(f'警告:禁止删除常变量:{cls}!')
|
|
25
48
|
raise TypeError(f'禁止删除常变量:{cls}')
|
|
49
|
+
def __hash__(cls):
|
|
50
|
+
return hash(cls.name+cls.__module__)
|
|
51
|
+
def __setattr__(cls,name,value):
|
|
52
|
+
if not hasattr(cls, 'x'):
|
|
53
|
+
super().__setattr__(name,value)
|
|
54
|
+
return
|
|
55
|
+
if hasattr(cls, 'name') and cls.name == 'BHA_Bool' and repr(value) in {'T','F'} and name in {'T','F'}:
|
|
56
|
+
super().__setattr__(name,value)
|
|
57
|
+
return
|
|
58
|
+
if hasattr(cls, 'original_dict') and name in cls.original_dict:
|
|
59
|
+
raise AttributeError(f'禁止修改属性:{name}')
|
|
60
|
+
else:
|
|
61
|
+
super().__setattr__(name,value)
|
|
62
|
+
def __delattr__(cls,name):
|
|
63
|
+
if name in cls.original_dict:
|
|
64
|
+
raise AttributeError(f'禁止删除属性:{name}')
|
|
65
|
+
else:
|
|
66
|
+
super().__delattr__(name)
|
|
67
|
+
if 'UnionType' not in types.__dict__:
|
|
68
|
+
def __or__(self,other):
|
|
69
|
+
return Union[self,other]
|
|
70
|
+
__ror__ = __or__
|
|
71
|
+
def __getitem__(self,*args):
|
|
72
|
+
return _GenericAlias(self,args)
|
|
73
|
+
x = None
|
|
74
|
+
original_dict = {"__delattr__":__delattr__,"__getitem__":__getitem__,"__setattr__":__setattr__,"__hash__":__hash__,
|
|
75
|
+
"__new__":__new__,"__del__":__del__,"__str__":__str__,"__repr__":__repr__,"__class__":abc.ABCMeta,"original_dict":None}
|
|
76
|
+
try:
|
|
77
|
+
original_dict["original_dict"] = original_dict
|
|
78
|
+
original_dict["__ror__"] = __ror__
|
|
79
|
+
original_dict["__or__"] = __or__
|
|
80
|
+
except:
|
|
81
|
+
pass
|
|
82
|
+
ResurrectMeta.__class__ = ResurrectMeta
|
|
83
|
+
class BHA_Function(metaclass=ResurrectMeta):
|
|
84
|
+
def __init__(self,v):
|
|
85
|
+
self.data,self.module = v,__name__
|
|
86
|
+
def __call__(self,*a,**b):
|
|
87
|
+
return self.data(*a,**b)
|
|
88
|
+
def __getattr__(self,name):
|
|
89
|
+
return getattr(self.data,name)
|
|
90
|
+
@classmethod
|
|
91
|
+
def string_define(cls, name, text, positional, default):
|
|
92
|
+
param_strs = list(positional)
|
|
93
|
+
param_strs.extend([f"{k}={v!r}" for k, v in default.items()])
|
|
94
|
+
params = ", ".join(param_strs)
|
|
95
|
+
func_code = f"""
|
|
96
|
+
def {name}({params}):
|
|
97
|
+
{text}
|
|
98
|
+
"""
|
|
99
|
+
local_namespace = {}
|
|
100
|
+
exec(func_code, globals(), local_namespace)
|
|
101
|
+
dynamic_func = local_namespace[name]
|
|
102
|
+
return cls(dynamic_func)
|
|
26
103
|
class BoolHybridArray(MutableSequence,Exception,metaclass=ResurrectMeta):
|
|
27
104
|
__module__ = 'bool_hybrid_array'
|
|
28
105
|
class _CompactBoolArray(Sequence,Exception):
|
|
@@ -44,11 +121,13 @@ class BoolHybridArray(MutableSequence,Exception,metaclass=ResurrectMeta):
|
|
|
44
121
|
val_bool = bool(value)
|
|
45
122
|
for i in indices:
|
|
46
123
|
self._set_single(i, val_bool, ctypes_arr)
|
|
124
|
+
self.data = np.ctypeslib.as_array(ctypes_arr, shape=(self.n_uint8,))
|
|
47
125
|
return
|
|
48
126
|
if not (0 <= index < self.size):
|
|
49
127
|
raise IndexError(f"密集区索引 {index} 超出范围 [0, {self.size})")
|
|
50
128
|
self._set_single(index, bool(value), ctypes_arr)
|
|
51
|
-
|
|
129
|
+
self.data = np.ctypeslib.as_array(ctypes_arr, shape=(self.n_uint8,))
|
|
130
|
+
self.data = self.data.view()
|
|
52
131
|
def _set_single(self, index: int, value: bool, ctypes_arr):
|
|
53
132
|
uint8_pos = index >> 3
|
|
54
133
|
bit_offset = index & 7
|
|
@@ -76,6 +155,10 @@ class BoolHybridArray(MutableSequence,Exception,metaclass=ResurrectMeta):
|
|
|
76
155
|
length = len(self.data)
|
|
77
156
|
if value:ctypes.memset(ctypes_arr, 0xff, length)
|
|
78
157
|
else:ctypes.memset(ctypes_arr, 0, length)
|
|
158
|
+
def copy(self):
|
|
159
|
+
new_instance = self.__class__(size=self.size)
|
|
160
|
+
new_instance.data = self.data.copy()
|
|
161
|
+
return new_instance
|
|
79
162
|
def __init__(self, split_index: int, size=None, is_sparse=False ,Type:Callable = None,hash_ = True) -> None:
|
|
80
163
|
self.Type = Type if Type is not None else builtins.BHA_Bool
|
|
81
164
|
self.split_index = int(split_index)
|
|
@@ -105,6 +188,12 @@ class BoolHybridArray(MutableSequence,Exception,metaclass=ResurrectMeta):
|
|
|
105
188
|
new_hash = id(self)
|
|
106
189
|
self._cached_hash = new_hash
|
|
107
190
|
hybrid_array_cache.append((weakref.ref(self), new_hash))
|
|
191
|
+
def __call__(self, func):
|
|
192
|
+
func.self = self
|
|
193
|
+
def wrapper(*args, **kwargs):
|
|
194
|
+
return func(self, *args, **kwargs)
|
|
195
|
+
setattr(self, func.__name__, wrapper)
|
|
196
|
+
return func
|
|
108
197
|
def __hash__(self):
|
|
109
198
|
return self._cached_hash
|
|
110
199
|
def accessor(self, i: int, value: bool|None = None) -> bool|None:
|
|
@@ -183,7 +272,7 @@ class BoolHybridArray(MutableSequence,Exception,metaclass=ResurrectMeta):
|
|
|
183
272
|
raise IndexError(f"小索引 {key} 超出small数组范围(长度{len(self.small)})")
|
|
184
273
|
self.small = np.delete(self.small, key)
|
|
185
274
|
self.small = np.append(self.small, not self.is_sparse)
|
|
186
|
-
self.split_index
|
|
275
|
+
self.split_index -= min(self.split_index, len(self.small) - 1)
|
|
187
276
|
else:
|
|
188
277
|
pos = bisect.bisect_left(self.large, key)
|
|
189
278
|
if pos < len(self.large) and self.large[pos] == key:
|
|
@@ -217,22 +306,26 @@ class BoolHybridArray(MutableSequence,Exception,metaclass=ResurrectMeta):
|
|
|
217
306
|
def __len__(self) -> int:
|
|
218
307
|
return self.size
|
|
219
308
|
def __iter__(self):
|
|
220
|
-
return BHA_Iterator(self
|
|
309
|
+
return BHA_Iterator(map(self.__getitem__,range(self.size)))
|
|
221
310
|
def __next__(self):
|
|
222
311
|
return next(self.generator)
|
|
223
312
|
def __contains__(self, value) -> bool:
|
|
224
313
|
if not isinstance(value, (bool,np.bool_,self.Type,BHA_bool)):return False
|
|
225
|
-
|
|
314
|
+
if not self.size:return False
|
|
315
|
+
for i in range(10):
|
|
316
|
+
if self[random.randint(0,self.size-1)] == value:
|
|
317
|
+
return True
|
|
318
|
+
b = any(1 for i in range(self.small.size+1>>1) if value==self.small[i] or value==self.small[self.small.size-i-1])
|
|
226
319
|
if value == self.is_sparse:
|
|
227
320
|
return self.large or b
|
|
228
321
|
else:
|
|
229
322
|
return len(self.large) == self.size-self.split_index-1 or b
|
|
230
323
|
def __bool__(self) -> bool:
|
|
231
|
-
return self.size
|
|
324
|
+
return self.size
|
|
232
325
|
def __any__(self):
|
|
233
|
-
return self
|
|
326
|
+
return T in self
|
|
234
327
|
def __all__(self):
|
|
235
|
-
return self
|
|
328
|
+
return F not in self
|
|
236
329
|
def __eq__(self, other) -> bool:
|
|
237
330
|
if not isinstance(other, (BoolHybridArray, list, tuple, np.ndarray, array.array)):
|
|
238
331
|
return False
|
|
@@ -249,9 +342,9 @@ class BoolHybridArray(MutableSequence,Exception,metaclass=ResurrectMeta):
|
|
|
249
342
|
raise ValueError(f"与运算要求数组长度相同({len(self)} vs {len(other)})")
|
|
250
343
|
return BoolHybridArr(map(operator.and_, self, other),hash_ = self.hash_)
|
|
251
344
|
def __int__(self):
|
|
252
|
-
if self.size
|
|
345
|
+
if not self.size:
|
|
253
346
|
return 0
|
|
254
|
-
return reduce(lambda acc, val: operator.or_(operator.lshift(acc, 1), val),self,0)
|
|
347
|
+
return reduce(lambda acc, val: operator.or_(operator.lshift(acc, 1), int(val)),self,0)
|
|
255
348
|
def __or__(self, other) -> BoolHybridArray:
|
|
256
349
|
if type(other) == int:
|
|
257
350
|
other = bin(other)[2:]
|
|
@@ -310,14 +403,15 @@ class BoolHybridArray(MutableSequence,Exception,metaclass=ResurrectMeta):
|
|
|
310
403
|
def __invert__(self) -> BoolHybridArray:
|
|
311
404
|
return BoolHybridArr(not a for a in self)
|
|
312
405
|
def copy(self) -> BoolHybridArray:
|
|
313
|
-
arr =
|
|
314
|
-
arr.large,arr.small,arr.split_index,arr.is_sparse,arr.Type = (self.large,self.small,
|
|
315
|
-
self.split_index,self.is_sparse,self.Type)
|
|
406
|
+
arr = BoolHybridArray(split_index = self.split_index,size = self.size)
|
|
407
|
+
arr.large,arr.small,arr.split_index,arr.is_sparse,arr.Type,arr.size = (array.array(self.large.typecode, self.large),self.small.copy(),
|
|
408
|
+
self.split_index,BHA_Bool(self.is_sparse),self.Type,self.size)
|
|
316
409
|
return arr
|
|
317
410
|
def __copy__(self) -> BoolHybridArray:
|
|
318
411
|
return self.copy()
|
|
319
412
|
def find(self,value):
|
|
320
|
-
|
|
413
|
+
from .int_array import IntHybridArray
|
|
414
|
+
return IntHybridArray([i for i in range(len(self)) if self[i]==value])
|
|
321
415
|
def extend(self, iterable:Iterable) -> None:
|
|
322
416
|
if isinstance(iterable, (Iterator, Generator, map)):
|
|
323
417
|
iterable,copy = itertools.tee(iterable, 2)
|
|
@@ -331,13 +425,30 @@ class BoolHybridArray(MutableSequence,Exception,metaclass=ResurrectMeta):
|
|
|
331
425
|
self.size += 1
|
|
332
426
|
self[-1] = v
|
|
333
427
|
def index(self, value) -> int:
|
|
428
|
+
if self.size == 0:
|
|
429
|
+
raise ValueError('无法在空的 BoolHybridArray 中查找元素!')
|
|
334
430
|
value = bool(value)
|
|
335
431
|
x = 'not find'
|
|
336
432
|
for i in range(self.size):
|
|
337
433
|
if self[i] == value:
|
|
338
434
|
return i
|
|
339
|
-
|
|
340
|
-
x =
|
|
435
|
+
if self[-i] == value:
|
|
436
|
+
x = self.size-i
|
|
437
|
+
if len(self)-i == i:
|
|
438
|
+
break
|
|
439
|
+
if x != 'not find':
|
|
440
|
+
return x
|
|
441
|
+
raise ValueError(f"{value} not in BoolHybridArray")
|
|
442
|
+
def rindex(self, value) -> int:
|
|
443
|
+
if self.size == 0:
|
|
444
|
+
raise ValueError('无法在空的 BoolHybridArray 中查找元素!')
|
|
445
|
+
value = bool(value)
|
|
446
|
+
x = 'not find'
|
|
447
|
+
for i in range(self.size):
|
|
448
|
+
if self[-i] == value:
|
|
449
|
+
return -i
|
|
450
|
+
if self[i] == value:
|
|
451
|
+
x = -(self.size-i)
|
|
341
452
|
if len(self)-i == i:
|
|
342
453
|
break
|
|
343
454
|
if x != 'not find':
|
|
@@ -383,6 +494,15 @@ class BoolHybridArray(MutableSequence,Exception,metaclass=ResurrectMeta):
|
|
|
383
494
|
}
|
|
384
495
|
def get_shape(self):
|
|
385
496
|
return (self.size,)
|
|
497
|
+
def __array__(self,dtype = np.bool_,copy = None):
|
|
498
|
+
arr = np.fromiter(map(np.bool_,self), dtype=dtype)
|
|
499
|
+
return arr.copy() if copy else arr.view()
|
|
500
|
+
def view(self):
|
|
501
|
+
arr = TruesArray(0)
|
|
502
|
+
arr.__dict__ = self.__dict__
|
|
503
|
+
return arr
|
|
504
|
+
def __reduce__(self):
|
|
505
|
+
return BoolHybridArr,(np.asarray(self),self.is_sparse,self.Type,self.hash_,),
|
|
386
506
|
class BoolHybridArr(BoolHybridArray,metaclass=ResurrectMeta):
|
|
387
507
|
__module__ = 'bool_hybrid_array'
|
|
388
508
|
def __new__(cls, lst: Iterable, is_sparse=None, Type = None, hash_ = True) -> BoolHybridArray:
|
|
@@ -401,7 +521,7 @@ class BoolHybridArr(BoolHybridArray,metaclass=ResurrectMeta):
|
|
|
401
521
|
split_index = int(min(size * 0.8, math.sqrt(size) * 100))
|
|
402
522
|
split_index = math.isqrt(size) if true_count>size/3*2 or true_count<size/3 else max(split_index, 1)
|
|
403
523
|
split_index = int(split_index) if split_index < 150e+7*2 else int(145e+7*2)
|
|
404
|
-
arr = BoolHybridArray(split_index, size, is_sparse, Type, hash_ = F)
|
|
524
|
+
arr = BoolHybridArray(split_index = split_index, size = size, is_sparse = is_sparse, Type = Type, hash_ = F)
|
|
405
525
|
small_max_idx = min(split_index, size - 1)
|
|
406
526
|
if a:
|
|
407
527
|
small_data = []
|
|
@@ -430,6 +550,7 @@ class BoolHybridArr(BoolHybridArray,metaclass=ResurrectMeta):
|
|
|
430
550
|
arr.large = array.array(type_, arr.large)
|
|
431
551
|
if hash_:
|
|
432
552
|
global hybrid_array_cache
|
|
553
|
+
del hybrid_array_cache[-1]
|
|
433
554
|
hybrid_array_cache = [
|
|
434
555
|
(ref, h) for ref, h in hybrid_array_cache
|
|
435
556
|
if ref() is not None
|
|
@@ -442,7 +563,7 @@ class BoolHybridArr(BoolHybridArray,metaclass=ResurrectMeta):
|
|
|
442
563
|
elif arr == existing_array:
|
|
443
564
|
arr._cached_hash = existing_hash
|
|
444
565
|
return arr
|
|
445
|
-
except
|
|
566
|
+
except:
|
|
446
567
|
continue
|
|
447
568
|
return arr
|
|
448
569
|
def TruesArray(size, Type = None, hash_ = True):
|
|
@@ -464,35 +585,39 @@ class BHA_bool(int,metaclass=ResurrectMeta):
|
|
|
464
585
|
instance.data = Bool_Array[1] if core_value else Bool_Array[0]
|
|
465
586
|
instance.value = core_value
|
|
466
587
|
return instance
|
|
588
|
+
@lru_cache
|
|
467
589
|
def __str__(self):
|
|
468
590
|
return 'True' if self else 'False'
|
|
591
|
+
@lru_cache
|
|
469
592
|
def __repr__(self):
|
|
470
593
|
return 'T' if self else 'F'
|
|
594
|
+
@lru_cache
|
|
471
595
|
def __bool__(self):
|
|
472
596
|
return self.value
|
|
597
|
+
@lru_cache
|
|
473
598
|
def __int__(self):
|
|
474
599
|
return int(self.data)
|
|
475
|
-
|
|
476
|
-
return self.value is bool(other)
|
|
600
|
+
@lru_cache
|
|
477
601
|
def __or__(self,other):
|
|
478
602
|
return BHA_Bool(self.value|other)
|
|
603
|
+
@lru_cache
|
|
479
604
|
def __and__(self,other):
|
|
480
605
|
return BHA_Bool(self.value&other)
|
|
606
|
+
@lru_cache
|
|
481
607
|
def __xor__(self,other):
|
|
482
608
|
return BHA_Bool(self.value^other)
|
|
483
|
-
def
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
if not sys.is_finalizing():
|
|
488
|
-
raise TypeError(f'禁止删除常变量{repr(self)}')
|
|
609
|
+
def __hash__(self):
|
|
610
|
+
return hash(self.data)
|
|
611
|
+
def __len__(self):
|
|
612
|
+
raise TypeError("'BHA_bool' object has no attribute '__len__'")
|
|
489
613
|
__rand__,__ror__,__rxor__ = __and__,__or__,__xor__
|
|
490
614
|
class BHA_Bool(BHA_bool,metaclass=ResurrectMeta):
|
|
491
615
|
__module__ = 'bool_hybrid_array'
|
|
616
|
+
@lru_cache
|
|
492
617
|
def __new__(cls,v):
|
|
493
|
-
|
|
494
|
-
return T if v else F
|
|
495
|
-
|
|
618
|
+
if(builtins.T == True)and(builtins.F == False):
|
|
619
|
+
return builtins.T if v else builtins.F
|
|
620
|
+
else:
|
|
496
621
|
builtins.T,builtins.F = BHA_Bool.T,BHA_Bool.F
|
|
497
622
|
return BHA_Bool.T if v else BHA_Bool.F
|
|
498
623
|
class BHA_List(list,metaclass=ResurrectMeta):
|
|
@@ -510,6 +635,16 @@ class BHA_List(list,metaclass=ResurrectMeta):
|
|
|
510
635
|
else:
|
|
511
636
|
return v
|
|
512
637
|
super().__init__(map(Temp,arr))
|
|
638
|
+
try:self.hash_value = sum(map(hash,self))
|
|
639
|
+
except Exception as e:return hash(e)
|
|
640
|
+
def __hash__(self):
|
|
641
|
+
return self.hash_value
|
|
642
|
+
def __call__(self, func):
|
|
643
|
+
func.self = self
|
|
644
|
+
def wrapper(*args, **kwargs):
|
|
645
|
+
return func(self, *args, **kwargs)
|
|
646
|
+
setattr(self, func.__name__, wrapper)
|
|
647
|
+
return func
|
|
513
648
|
def __str__(self):
|
|
514
649
|
def Temp(v):
|
|
515
650
|
if isinstance(v,(BoolHybridArray,np.ndarray,BHA_List,array.array)):
|
|
@@ -563,30 +698,137 @@ class BHA_Iterator(Iterator,metaclass=ResurrectMeta):
|
|
|
563
698
|
return BHA_Iterator(map(operator.and_, self, other))
|
|
564
699
|
def __xor__(self,other):
|
|
565
700
|
return BHA_Iterator(map(operator.xor, self, other))
|
|
701
|
+
def __array__(self,dtype = None,copy = None):
|
|
702
|
+
arr = np.fromiter(self, dtype=dtype)
|
|
703
|
+
return arr.copy() if copy else arr.view()
|
|
566
704
|
__rand__,__ror__,__rxor__ = __and__,__or__,__xor__
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
705
|
+
class ProtectedBuiltinsDict(dict,metaclass=ResurrectMeta):
|
|
706
|
+
def __init__(self, *args, protected_names = ["T", "F", "BHA_Bool", "BHA_List", "BoolHybridArray", "BoolHybridArr",
|
|
707
|
+
"TruesArray", "FalsesArray", "ProtectedBuiltinsDict", "builtins",
|
|
708
|
+
"__builtins__", "__dict__","ResurrectMeta","math",
|
|
709
|
+
"np","protected_names","BHA_Function",
|
|
710
|
+
"__class__","Ask_BHA","Create_BHA","Ask_arr","numba_opt"],
|
|
711
|
+
name = 'builtins', **kwargs):
|
|
712
|
+
super().__init__(*args, **kwargs)
|
|
713
|
+
if name == 'builtins':
|
|
714
|
+
super().__setattr__('__dict__',self)
|
|
715
|
+
super().__setattr__('builtins',self)
|
|
716
|
+
super().__setattr__('__builtins__',self)
|
|
717
|
+
self.name = name
|
|
718
|
+
self.protected_names = protected_names
|
|
719
|
+
def __setitem__(self, name, value):
|
|
720
|
+
if name in ["T", "F"]:
|
|
721
|
+
current_T = self.get("T")
|
|
722
|
+
current_F = self.get("F")
|
|
723
|
+
if isinstance(current_T, BHA_bool) and isinstance(current_F, BHA_bool):
|
|
724
|
+
is_swap = (name == "T" and isinstance(value, BHA_bool) and value.value == current_F.value)or(name == "F" and isinstance(value, BHA_bool) and value.value == current_T.value)
|
|
725
|
+
if is_swap:
|
|
726
|
+
print(f"""警告:禁止交换内置常量 __{self.name}__["{name}"] 和 __builtins__["{'F' if name == 'T' else 'T'}"]!""")
|
|
727
|
+
raise AttributeError(f"""禁止交换内置常量 __{self.name}__["{name}"] 和 __{self.name}__["{'F' if name == 'T' else 'T'}"]""")
|
|
728
|
+
if name in self.protected_names and name not in ["T", "F"]:
|
|
729
|
+
print(f"警告:禁止修改内置常量 __{self.name}__['{name}']!")
|
|
730
|
+
raise AttributeError(f"禁止修改内置常量 __{self.name}__['{name}']")
|
|
731
|
+
super().__setitem__(name, value)
|
|
732
|
+
def __delitem__(self, name):
|
|
733
|
+
if name in self.protected_names:
|
|
734
|
+
print(f"警告:禁止删除内置常量 __builtins__['{name}']!")
|
|
735
|
+
raise AttributeError(f"禁止删除内置常量 __builtins__['{name}']")
|
|
736
|
+
if name in self:
|
|
737
|
+
super().__delitem__(name)
|
|
738
|
+
def __delattr__(self, name):
|
|
739
|
+
if name in self.protected_names:
|
|
740
|
+
raise AttributeError(f'禁止删除内置常量:{self.name}.{name}')
|
|
741
|
+
else:
|
|
742
|
+
del self[name]
|
|
743
|
+
def __getattr__(self, name):
|
|
744
|
+
if name in self:
|
|
745
|
+
return self[name]
|
|
746
|
+
else:
|
|
747
|
+
raise AttributeError(f"module 'builtins' has no attribute '{name}'")
|
|
748
|
+
def __setattr__(self,name,value):
|
|
749
|
+
try:protected = self.protected_names
|
|
750
|
+
except Exception:protected = self
|
|
751
|
+
if(name in protected)and(not sys.is_finalizing())and(name != '_'):
|
|
752
|
+
raise AttributeError(f'禁止修改内置常量:{self.name}.{name}')
|
|
753
|
+
else:
|
|
754
|
+
super().__setattr__(name,value)
|
|
755
|
+
def __import__(self, name, globals=None, locals=None, fromlist=(), level=0):
|
|
756
|
+
if fromlist:
|
|
757
|
+
result = []
|
|
758
|
+
for key in fromlist:
|
|
759
|
+
if key not in self:
|
|
760
|
+
raise AttributeError(f"'ImportableDict' object has no attribute '{key}'")
|
|
761
|
+
result.append(self[key])
|
|
762
|
+
return result[0] if len(result) == 1 else tuple(result)
|
|
763
|
+
return self
|
|
764
|
+
def Ask_arr(arr):
|
|
765
|
+
if isinstance(arr,BHA_List):
|
|
766
|
+
return '\n'.join(map(Ask_arr,arr))
|
|
767
|
+
elif isinstance(arr,BoolHybridArray):
|
|
768
|
+
h = hex(int(arr))[2:]
|
|
769
|
+
h = '0'*(arr.size - len(bin(int(arr)))+2)+h
|
|
770
|
+
return h
|
|
771
|
+
else:
|
|
772
|
+
return str(arr)
|
|
773
|
+
def Ask_BHA(path):
|
|
774
|
+
if '.bha' not in path.lower():
|
|
775
|
+
path += '.bha'
|
|
776
|
+
with open(path, 'a+b') as f:
|
|
777
|
+
f.seek(0)
|
|
778
|
+
file_size = os.fstat(f.fileno()).st_size
|
|
779
|
+
if not file_size:
|
|
780
|
+
return TruesArray(0)
|
|
781
|
+
if os.name == 'nt':
|
|
782
|
+
mm = mmap.mmap(f.fileno(), file_size, access=mmap.ACCESS_READ)
|
|
783
|
+
else:
|
|
784
|
+
mm = mmap.mmap(f.fileno(), file_size, flags=mmap.MAP_PRIVATE, prot=mmap.PROT_READ)
|
|
785
|
+
with mm:
|
|
786
|
+
temp = mm.read().decode('utf-8').strip()
|
|
787
|
+
temp = temp.split()
|
|
788
|
+
temp2 = lambda x:BoolHybridArr(map(int,'0'*(len(x) - len(x.lstrip('0')))+bin(int(x,base = 16))[2:]),hash_ = F)
|
|
789
|
+
temp = BHA_List(map(temp2,temp))
|
|
790
|
+
if len(temp) == 1:
|
|
791
|
+
return temp[0]
|
|
792
|
+
return temp
|
|
793
|
+
def Create_BHA(path,arr):
|
|
794
|
+
if '.bha' not in path.lower():
|
|
795
|
+
path += '.bha'
|
|
796
|
+
temp = Ask_arr(arr).strip().encode('utf-8')
|
|
797
|
+
with open(path, "w+b") as f:
|
|
798
|
+
f.truncate(len(temp))
|
|
799
|
+
if not len(temp):
|
|
800
|
+
return
|
|
801
|
+
with mmap.mmap(
|
|
802
|
+
f.fileno(),
|
|
803
|
+
length=len(temp),
|
|
804
|
+
access=mmap.ACCESS_WRITE
|
|
805
|
+
) as mm:
|
|
806
|
+
mm[:] = temp
|
|
807
|
+
mm.flush()
|
|
808
|
+
def numba_opt():
|
|
809
|
+
import numba
|
|
810
|
+
sig = numba.types.Union([
|
|
811
|
+
numba.types.intp(
|
|
812
|
+
numba.types.Array(numba.types.uint32, 1, 'C'),
|
|
813
|
+
numba.types.uint32,
|
|
814
|
+
numba.types.uint32,
|
|
815
|
+
numba.types.Optional(numba.types.uint32)
|
|
816
|
+
),
|
|
817
|
+
numba.types.intp(
|
|
818
|
+
numba.types.Array(numba.types.uint64, 1, 'C'),
|
|
819
|
+
numba.types.uint64,
|
|
820
|
+
numba.types.uint64,
|
|
821
|
+
numba.types.Optional(numba.types.uint64)
|
|
822
|
+
),
|
|
823
|
+
numba.types.intp(
|
|
824
|
+
numba.types.Any,
|
|
825
|
+
numba.types.Any,
|
|
826
|
+
numba.types.Any,
|
|
827
|
+
numba.types.Optional(numba.types.Any)
|
|
828
|
+
)
|
|
829
|
+
])
|
|
830
|
+
bisect.bisect_left = numba.njit(sig, cache=True)(bisect.bisect_left)
|
|
831
|
+
bisect.bisect_right = numba.njit(sig, cache=True)(bisect.bisect_right)
|
|
590
832
|
builtins.np = np
|
|
591
833
|
builtins.T = BHA_bool(1)
|
|
592
834
|
builtins.F = BHA_bool(0)
|
|
@@ -595,7 +837,27 @@ builtins.BHA_List = BHA_List
|
|
|
595
837
|
builtins.FalsesArray = FalsesArray
|
|
596
838
|
builtins.TruesArray = TruesArray
|
|
597
839
|
builtins.BoolHybridArr = BoolHybridArr
|
|
840
|
+
builtins.BHA_Iterator = BHA_Iterator
|
|
598
841
|
builtins.BoolHybridArray = BoolHybridArray
|
|
599
|
-
builtins.builtins = builtins
|
|
600
842
|
builtins.BHA_Bool.T,builtins.BHA_Bool.F = BHA_bool(1),BHA_bool(0)
|
|
601
|
-
builtins.ResurrectMeta = ResurrectMeta
|
|
843
|
+
builtins.ResurrectMeta = ResurrectMeta
|
|
844
|
+
builtins.ProtectedBuiltinsDict = ProtectedBuiltinsDict
|
|
845
|
+
builtins.BHA_Function = BHA_Function
|
|
846
|
+
builtins.Ask_BHA = Ask_BHA
|
|
847
|
+
builtins.Create_BHA = Create_BHA
|
|
848
|
+
builtins.numba_opt = numba_opt
|
|
849
|
+
Tid,Fid = id(T),id(F)
|
|
850
|
+
original_id = builtins.id
|
|
851
|
+
def fake_id(obj):
|
|
852
|
+
if isinstance(obj, BHA_bool):return Tid if obj else Fid
|
|
853
|
+
else:return original_id(obj)
|
|
854
|
+
builtins.id = fake_id
|
|
855
|
+
original_builtins_dict = builtins.__dict__.copy()
|
|
856
|
+
__builtins__ = ProtectedBuiltinsDict(original_builtins_dict)
|
|
857
|
+
builtins = __builtins__
|
|
858
|
+
sys.modules['builtins'] = builtins
|
|
859
|
+
builtins.name = 'builtins'
|
|
860
|
+
try:
|
|
861
|
+
sys.flags.optimize = 2
|
|
862
|
+
except:
|
|
863
|
+
pass
|