本文整理汇总了Python中bitstring.BitArray.copy方法的典型用法代码示例。如果您正苦于以下问题:Python BitArray.copy方法的具体用法?Python BitArray.copy怎么用?Python BitArray.copy使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bitstring.BitArray
的用法示例。
在下文中一共展示了BitArray.copy方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MasterKey
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import copy [as 别名]
class MasterKey(object):
def __init__(self, master_key_hex_string="0x3cc849279ba298b587a34cabaeffc5ecb3a044bbf97c516fab7ede9d1af77cfa"):
self.key = BitArray(master_key_hex_string)
self.session_keys_amount = 8
self.current_cycle_index = 0
self.master_key_round_shift_bits = 24
def get_round_keys(self):
"""
:return: list of round keys
:rtype: list[RoundKey]
"""
if self.current_cycle_index:
round_master_key = self.key.copy()
round_master_key.ror(self.master_key_round_shift_bits * self.current_cycle_index)
else:
round_master_key = self.key.copy()
round_keys = []
round_key_size = round_master_key.length / self.session_keys_amount
for key_index in range(0, self.session_keys_amount):
round_key = round_master_key[key_index * round_key_size:key_index * round_key_size + round_key_size]
round_keys.append(RoundKey(round_key))
if self.current_cycle_index < 8:
self.current_cycle_index += 1
else:
self.current_cycle_index = 0
return round_keys
示例2: stop_packet
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import copy [as 别名]
def stop_packet(direction=1,
soft_stop=False,
ignore_direction=True):
"""
Build a stop packet for all decoders.
param direction sets the direction bit in the packet.
param soft_stop indicates if the decoder bring the locomotive to stop
or stop delivering energy to the engine (guess in
the first case it may gradually decelerate it)
param ignore_direction allows optionally ignoring the direction bit
for all direction sensitive functions
"""
byte_one = BitArray('0b00000000')
byte_two = BitArray('0b01')
if direction:
byte_two.append('0b1')
else:
byte_two.append('0b0')
if ignore_direction:
byte_two.append('0b1')
else:
byte_two.append('0b0')
byte_two.append('0b000')
if soft_stop:
byte_two.append('0b0')
else:
byte_two.append('0b1')
byte_three = byte_two.copy()
return DCCGeneralPacket(byte_one, [byte_two, byte_three])
示例3: testCopyMethod
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import copy [as 别名]
def testCopyMethod(self):
s = BitArray(9)
t = s.copy()
self.assertEqual(s, t)
t[0] = True
self.assertEqual(t.bin, '100000000')
self.assertEqual(s.bin, '000000000')
示例4: hamming_search
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import copy [as 别名]
def hamming_search(b, bit, radius, current_radius, H):
if current_radius == 0:
H[current_radius].append(b.copy())
if current_radius == radius:
return
for i in range(bit+1, b.length):
b2 = BitArray(b.copy())
b2.invert(i)
H[current_radius+1].append(b2.copy())
hamming_search(b2, i, radius, current_radius+1, H)
示例5: split
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import copy [as 别名]
def split(self, A):
IG_list = []
A_count = float(A.count(True))
p_A = self.prob(A)
e_A = self.entropy(p_A)
# Get decision for node
if p_A >= 0.5:
d = 1
else:
d = 0
# Check entropy of node
if e_A < 0.3:
print "Node entropy is low enough:", e_A
return None,None,d,None,None
# Check # elements
if A_count < self.count_thresh:
print "Node has few elements:", A_count
return None,None,d,None,None
F = self.X.T
for f in range(len(F)):
# Sort the relevant column and keep indices
indices = F[f].argsort()
pairs = zip(indices, F[f][indices])
s = len(pairs)*'0'
B = BitArray(bin=s)
C = A.copy()
i = 0
IG_prev = 0.0
# Threshold emulator loop
while i < len(pairs)-1:
if A[pairs[i][0]]:
B[pairs[i][0]] = 1
C[pairs[i][0]] = 0
if pairs[i][1] < pairs[i+1][1]:
t = pairs[i+1][1]
# Calculate information gain for the split
IG_curr,s_B,s_C = self.info_gain(B,C,e_A,A_count)
#print IG_curr
if IG_curr < IG_prev:
break
else:
IG_prev = IG_curr
# Check if entropy for any branches is below thresh
IG_list.append((IG_curr,f,t,d,B.copy(),C.copy(),s_B,s_C))
i += 1
if IG_list == []:
#print "Boring decision..."
return None,None,d,None,None
else:
max_val = max(IG[0] for IG in IG_list)
IG,f,t,d,B,C,s_B,s_C = [IG for IG in IG_list if IG[0] == max_val][0]
return f,t,d,B,C
示例6: build_bitmaps_1
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import copy [as 别名]
def build_bitmaps_1(given, implied, nrAttributes):
m = BitArray('0b'+'0'*2**nrAttributes)
n = m.copy()
n.invert()
for j in range(nrAttributes):
b = m.copy()
step = 2**(j)
a1=0
a2=a1+step
for i in range(0,32,step):
b[a1:a2] = n[a1:a2]
a1=a2+step
a2=a1+step
given.append(b[:])
for j in range(nrAttributes):
implied.append(given[j].copy())
for j in range(nrAttributes):
implied[j].invert()
示例7: split
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import copy [as 别名]
def split(self, A):
gain_list = []
A_count = float(A.count(True))
d = self.mean(A)
if A_count <= self.count_thresh:
print "Node has few elements:", A_count
return None,None,d,None,None
mse_A = self.mse([A])
#print "Curr mse:",mse_A
F = self.X.T
for f in range(len(F)):
#print f
# Sort the relevant column and keep indices
indices = F[f].argsort()
pairs = zip(indices, F[f][indices])
s = len(pairs)*'0'
B = BitArray(bin=s)
C = A.copy()
i = 0
# Threshold emulator loop
while i < len(pairs)-1:
if A[pairs[i][0]]:
B[pairs[i][0]] = 1
C[pairs[i][0]] = 0
if pairs[i][1] < pairs[i+1][1]:
t = pairs[i+1][1]
# Calculate MSE for the split
mse_curr = self.mse([B,C])
gain_curr = mse_A - mse_curr
# Check if entropy for any branches is below thresh
gain_list.append((gain_curr,f,t,d,B.copy(),C.copy(),mse_A,mse_curr))
i += 1
if gain_list == []:
print "mse_list empty"
# return None,None,d,None,None
else:
max_val = max(mse[0] for mse in gain_list)
gain,f,t,d,B,C,mse_A,mse_curr = [mse for mse in gain_list if mse[0] == max_val][0]
if mse_curr <= 1.0:
return None,None,d,None,None
else:
print "Gain:",mse_A,mse_curr
return f,t,d,B,C
示例8: FileMgr
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import copy [as 别名]
class FileMgr(object):
def __init__(self, metainfo):
self._metainfo = metainfo
self._have = BitArray(self._metainfo.num_pieces)
directory = metainfo.directory
if directory != "":
try:
if not os.path.exists(directory):
os.makedirs(directory)
except OSError as err:
if err.errno != errno.EEXIST:
raise
files = metainfo.files
# _files is a list of files in the torrent. Each entry is a
# tuple containing the file descriptor, length of the file and
# offset of the file within the torrent
self._files = []
offset = 0
subdirs = []
for path, length in files:
dirname = directory + "/".join(path[0:-1])
if dirname != "" and dirname not in subdirs:
subdirs.append(dirname)
try:
if not os.path.exists(dirname):
os.makedirs(dirname)
except OSError as err:
if err.errno != errno.EEXIST:
raise
if dirname == "":
filename = path[-1]
else:
filename = dirname + "/" + path[-1]
try:
open(filename, "a").close()
fd = open(filename, "rb+")
except IOError:
logger.critical("Unable to open file {}".format(filename))
raise
self._files.append((fd, length, offset))
offset += length
def _file_index(self, offset):
for i, (fd, length, begin) in enumerate(self._files):
if offset >= begin and offset < begin + length:
return i
def have(self):
return self._have.copy()
def write_block(self, piece_index, offset_in_piece, buf, file_index=None):
offset_in_torrent = piece_index * self._metainfo.piece_length + offset_in_piece
if file_index is None:
file_index = self._file_index(offset_in_torrent)
fd, file_length, file_offset_in_torrent = self._files[file_index]
offset_in_file = offset_in_torrent - file_offset_in_torrent
fd.seek(offset_in_file)
if len(buf) <= file_length - offset_in_file:
fd.write(buf)
fd.flush()
else:
to_write = file_length - offset_in_file
fd.write(buf[:to_write])
fd.flush()
self.write_block(piece_index, offset_in_piece + to_write, buf[to_write:], file_index + 1)
示例9: Message
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import copy [as 别名]
class Message(object):
def __init__(self, message_bit_array=BitArray(length=256)):
"""
:param message_bit_array: message BitArray
:type message_bit_array: BitArray
"""
self.message_block_amount = 8
self.normal_message_bits_amount = 256
self.message_bit_array = message_bit_array
self.message = self.message_bit_array.tobytes()
self._normalize_message()
@classmethod
def get_message_from_message_blocks(cls, message_blocks):
message_bit_array = BitArray()
for message_block in message_blocks:
message_bit_array.append(message_block.message_block)
return Message(message_bit_array)
def set_message_as_string(self, message_string):
self.message = message_string
self.message_bit_array = BitArray(self.message_to_hex(message_string))
def message_to_hex(self, message_string):
return '0x' + ''.join(x.encode('hex') for x in message_string)
def _normalize_message(self):
if self.message_bit_array.length > self.normal_message_bits_amount:
self._trim_message()
def _trim_message(self):
self.message_bit_array = self.message_bit_array[0:self.normal_message_bits_amount]
def get_message_blocks(self):
message_bit_array = self.message_bit_array.copy()
message_blocks = []
message_block_size = self.normal_message_bits_amount / self.message_block_amount
padding_blocks_amount = (
self.normal_message_bits_amount - message_bit_array.length) / message_block_size
padding_bits_amount = (self.normal_message_bits_amount - message_bit_array.length) % message_block_size
if padding_bits_amount != 0:
padding_block = BitArray('0b' + ''.join('0' for x in range(0, padding_bits_amount)))
message_bit_array.prepend(padding_block)
for padding_block_index in range(0, padding_blocks_amount):
message_block = BitArray('0b00000000000000000000000000000000')
message_blocks.append(MessageBlock(message_block))
for message_block_index in range(0, self.message_block_amount - padding_blocks_amount):
message_block = message_bit_array[
message_block_index * message_block_size:message_block_index * message_block_size + message_block_size]
message_blocks.append(MessageBlock(message_block))
return message_blocks
def __unicode__(self):
return self.message
def __str__(self):
return self.__unicode__()
示例10: print
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import copy [as 别名]
args = parser.parse_args()
if (len(args.command) != 12):
print('command is wrong length')
my_command = 'aXY1CT20F100'
else:
my_command =args.command
in_preamble = BitArray('0b00000')
in_device1 = BitArray('0xd70000c50027da11')
in_device2 = BitArray('0x641000420027da11')
in_params = BitArray('0xf40080c1002060060000b0002249000027da11')
in_list = [in_preamble,in_device1,in_device2,in_params]
#in_list[3].reverse()
in_first = in_params.copy()
print(in_list[0].bin)
print(in_list[1].hex)
print(in_list[2].hex)
print(in_list[3].hex)
#print(in_list[3].bin)
in_list[0].clear()
in_list[1].clear()
in_list[2].clear()
in_list[3].clear()
with open(args.input, 'r') as raw_file:
A_list1 = []
示例11: __init__
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import copy [as 别名]
class LDevice:
# Обертка над C API
def __init__(self, slot):
self._closed = True
err = ffi.new("unsigned int*")
device = _dll.CreateLDevice(slot, err)
err = err[0]
if device == ffi.NULL:
if err == 1:
raise LDeviceError("CreateLDevice return L_NOTSUPPORTED")
elif err == 2:
raise LDeviceError("CreateLDevice return L_ERROR")
elif err == 3:
raise LDeviceError("CreateLDevice return L_ERROR_NOBOARD")
elif err == 4:
raise LDeviceError("CreateLDevice return L_ERROR_INUSE")
else:
raise AssertionError("Unknown error number {}".format(err))
if _dll.OpenLDevice(device) == L_ERROR:
_dll.ReleaseLDevice(device)
raise LDeviceError("OpenLDevice error")
self._closed = False
self._impl = device
self._ttl = BitArray(uint=0, length=16)
def close(self):
assert not self._closed
self._closed = True
print("Close LDevice")
try:
if _dll.CloseLDevice(self._impl) == L_ERROR:
raise LDeviceError("CloseLDevice error")
finally:
_dll.ReleaseLDevice(self._impl)
def __del__(self):
if not self._closed:
self.close()
def plata_test(self):
return _dll.PlataTest(self._impl) == L_SUCCESS
def init_start(self):
if _dll.InitStartLDevice(self._impl) == L_ERROR:
raise LDeviceError("InitStartLDevice error")
def start(self):
if _dll.StartLDevice(self._impl) == L_ERROR:
raise LDeviceError("StartLDevice error")
def stop(self):
if _dll.StopLDevice(self._impl) == L_ERROR:
raise LDeviceError("StopLDevice error")
def load_bios(self, filename):
assert type(filename) == str
filename = filename.encode("ascii")
if _dll.LoadBios(self._impl, filename) == L_ERROR:
raise LDeviceError("LoadBios error")
def create_WASYNC_PAR(self):
return ffi.new("WASYNC_PAR*")
def io_async(self, WASYNC_PAR):
if _dll.IoAsync(self._impl, WASYNC_PAR) == L_ERROR:
raise LDeviceError("IoAsync error")
def get_slot_param(self):
sp = ffi.new("SLOT_PAR*")
if _dll.GetSlotParam(self._impl, sp) == L_ERROR:
raise LDeviceError("GetSlotParam error")
return sp
def enable_correction(self, val):
assert type(val) == bool
if _dll.EnableCorrection(self._impl, int(val)) == L_ERROR:
raise LDeviceError("EnableCorrection error")
# Пользовательские функции
@property
def ttl(self):
return self._ttl
def ttl_enable(self, enabled: bool):
sp = self.create_WASYNC_PAR()
sp.s_Type = L_ASYNC_TTL_CFG
sp.Mode = int(enabled)
self.io_async(sp)
def ttl_write(self):
sp = self.create_WASYNC_PAR()
sp.s_Type = L_ASYNC_TTL_OUT
ttl = self._ttl.copy()
ttl.reverse()
sp.Data[0] = ttl.uint
#.........这里部分代码省略.........
示例12: split
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import copy [as 别名]
def split(self, A):
gain_list = []
A_count = float(A.count(True))
d = self.mean(A)
if A_count <= self.count_thresh:
#print "Node has few elements:", A_count
return None,None,d,None,None
mse_A = self.mse([A])
#if mse_A <= 15:
# print "Node has small MSE:", mse_A
# return None,None,d,None,None
print "Elem, MSE:",A_count,mse_A
F = self.X.T
for f in range(len(F)):
#print f
# Sort the relevant column and keep indices
indices = F[f].argsort()
pairs = zip(indices, F[f][indices])
s = len(pairs)*'0'
B = BitArray(bin=s)
C = A.copy()
i = 0
gain_prev = 0.0
# Threshold emulator loop
while i < len(pairs)-1:
if A[pairs[i][0]]:
B[pairs[i][0]] = 1
C[pairs[i][0]] = 0
if pairs[i][1] < pairs[i+1][1]:
t = pairs[i+1][1]
# Calculate MSE for the split
mse_curr = self.mse([B,C])
gain_curr = mse_A - mse_curr
if gain_curr < 0:
print gain_curr
#print mse_curr
if gain_curr < gain_prev:
pass
#break
else:
gain_prev = gain_curr
# Check if entropy for any branches is below thresh
if B.count(True) == 0 or C.count(True) == 0:
pass
else:
gain_list.append((gain_curr,f,t,d,B.copy(),C.copy(),mse_A,mse_curr))
i += 1
if gain_list == []:
print "mse_list empty"
return None,None,d,None,None
else:
max_val = max(mse[0] for mse in gain_list)
gain,f,t,d,B,C,mse_A,mse_curr = [mse for mse in gain_list if mse[0] == max_val][0]
if B.count(True) == 0 or C.count(True) == 0:
print "Count of B or C = 0:",B.count(True), C.count(True)
for elem in gain_list:
print elem[4].count(True), elem[5].count(True)
print
return None,None,d,None,None
else:
return f,t,d,B,C