content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
|---|---|
def giwaxs_S_edge_wenkai(t=1):
dets = [pil300KW]
names = [ 'A2', 'A3', 'A4', 'A5', 'A6']
x = [30000, 16000, 0, -15000, -36000]
energies = np.arange(2450, 2470, 5).tolist() + np.arange(2470, 2480, 0.25).tolist() + np.arange(2480, 2490, 1).tolist()+ np.arange(2490, 2501, 5).tolist()
waxs_arc = np.linspace(0, 26, 5)
ai0 = 0
for name, xs in zip(names, x):
yield from bps.mv(piezo.x, xs)
yield from bps.mv(piezo.th, ai0)
yield from bps.mv(GV7.open_cmd, 1 )
yield from bps.sleep(1)
yield from bps.mv(GV7.open_cmd, 1 )
yield from bps.sleep(1)
yield from alignement_gisaxs(angle = 0.4)
# yield from bps.mv(att2_9, 'Insert')
yield from bps.mv(GV7.close_cmd, 1 )
yield from bps.sleep(1)
# yield from bps.mv(att2_9, 'Insert')
yield from bps.mv(GV7.close_cmd, 1 )
yield from bps.sleep(1)
ai0 = piezo.th.position
yield from bps.mv(piezo.th, ai0 + 0.7)
xss = np.linspace(xs, xs - 8000, 57)
for wa in waxs_arc:
yield from bps.mv(waxs, wa)
det_exposure_time(t,t)
name_fmt = '{sample}_{energy}eV_wa{wax}_bpm{xbpm}'
for e, xsss in zip(energies, xss):
yield from bps.mv(energy, e)
yield from bps.sleep(2)
yield from bps.mv(piezo.x, xsss)
bpm = xbpm2.sumX.value
sample_name = name_fmt.format(sample=name, energy='%6.2f'%e, wax = wa, xbpm = '%4.3f'%bpm)
sample_id(user_name='GF', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
yield from bps.mv(energy, 2470)
yield from bps.mv(energy, 2450)
def nexafs_S_edge_wenkai(t=1):
dets = [pil300KW]
names = ['PFSA_LSC']
x = [41200]
y = [-8000]
z = [ 2700]
energies = np.linspace(2450, 2500, 51)
energies = np.arange(2450, 2470, 5).tolist() + np.arange(2470, 2480, 0.25).tolist() + np.arange(2480, 2490, 1).tolist()+ np.arange(2490, 2501, 5).tolist()
energies1 = 10 + np.asarray(np.arange(2445, 2470, 5).tolist() + np.arange(2470, 2480, 0.25).tolist() + np.arange(2480, 2490, 1).tolist()+ np.arange(2490, 2501, 5).tolist())
for name, xs in zip(names, x):
det_exposure_time(t,t)
name_fmt = 'nexafs_{sample}_{energy}eV_wa52.00_bpm{xbpm}'
for e in energies:
yield from bps.mv(energy, e)
yield from bps.sleep(1)
bpm = xbpm2.sumX.value
sample_name = name_fmt.format(sample=name, energy='%6.2f'%e, xbpm = '%4.3f'%bpm)
sample_id(user_name='GF', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
yield from bps.mv(energy, 2470)
yield from bps.mv(energy, 2450)
def hardxray_wenkai2020_1(t=1):
dets = [pil300KW, pil1M]
names = ['PFSA_LSC', 'PFSA_LSC', 'N2200_vert', 'N2200_hori', 'A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2', 'A3', 'B3', 'C3', 'D3']
x = [41000, 29000, -8000, -30000, 43800, 37500, 32500, 27500, 22500, 17100, 12100, 5900, -16900, -21900, -27300, -32500]
y = [-8000, -8000, -8000, -8000, 3800, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4200,]
z = [ 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700]
waxs_arc = np.linspace(0, 39, 7)
for wa in waxs_arc:
yield from bps.mv(waxs, wa)
for name, xs, ys, zs in zip(names, x, y, z):
yield from bps.mv(piezo.x, xs)
yield from bps.mv(piezo.y, ys)
yield from bps.mv(piezo.z, zs)
det_exposure_time(t,t)
name_fmt = '{sample}_16.1keVeV_8.3m_wa{wax}'
yield from bps.sleep(1)
sample_name = name_fmt.format(sample=name, wax = wa)
sample_id(user_name='WZ', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
def waxs_S_edge_wenkai_2021_1(t=1):
dets = [pil1M, pil300KW]
# names = ['PFSA_LSC', 'PFSA_SSC', 'A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2', 'A3', 'B3', 'C3', 'D3']
# x = [41000, 28000, 43300, 37600, 32700, 27500, 21700, 16600, 11300, 5900, -17600, -22600, -28100, -33100]
# y = [-8500, -8500, 3800, 4000, 3900, 4200, 4100, 4100, 3800, 3900, 3900, 4100, 4100, 4200]
# z = [ 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700]
energies = np.arange(2450, 2470, 5).tolist() + np.arange(2470, 2480, 0.25).tolist() + np.arange(2480, 2490, 1).tolist()+ np.arange(2490, 2501, 5).tolist()
# energies1 = 10 + np.asarray(np.arange(2445, 2470, 5).tolist() + np.arange(2470, 2480, 0.25).tolist() + np.arange(2480, 2490, 1).tolist()+ np.arange(2490, 2501, 5).tolist())
# waxs_arc = np.linspace(13, 19.5, 2)
# for k, wa in enumerate(waxs_arc):
# yield from bps.mv(waxs, wa)
# for name, xs, ys, zs in zip(names, x, y, z):
# yield from bps.mv(piezo.x, xs)
# yield from bps.mv(piezo.y, ys)
# yield from bps.mv(piezo.z, zs)
# yss = np.linspace(ys, ys + 700, 29)
# xss = np.array([xs, xs + 500])
# yss, xss = np.meshgrid(yss, xss)
# yss = yss.ravel()
# xss = xss.ravel()
# det_exposure_time(t,t)
# name_fmt = '{sample}_{energy}eV_wa{wax}_bpm{xbpm}'
# for e, xsss, ysss in zip(energies1, xss, yss):
# yield from bps.mv(energy, e)
# yield from bps.sleep(1)
# yield from bps.mv(piezo.y, ysss)
# yield from bps.mv(piezo.x, xsss)
# bpm = xbpm2.sumX.value
# sample_name = name_fmt.format(sample=name, energy='%6.2f'%e, wax = wa, xbpm = '%4.3f'%bpm)
# sample_id(user_name='WZ', sample_name=sample_name)
# print(f'\n\t=== Sample: {sample_name} ===\n')
# yield from bp.count(dets, num=1)
# yield from bps.mv(energy, 2470)
# yield from bps.mv(energy, 2450)
names = ['N2200_vert', 'N2200_hori']
x = [-8500, -30500]
y = [-8500, -8000]
z = [ 2700, 2700]
waxs_arc = np.linspace(0, 19.5, 4)
for wa in waxs_arc:
yield from bps.mv(waxs, wa)
for name, xs, ys, zs in zip(names, x, y, z):
yield from bps.mv(piezo.x, xs)
yield from bps.mv(piezo.y, ys)
yield from bps.mv(piezo.z, zs)
yss = np.linspace(ys, ys + 1000, 29)
xss = np.array([xs, xs + 500])
yss, xss = np.meshgrid(yss, xss)
yss = yss.ravel()
xss = xss.ravel()
det_exposure_time(t,t)
name_fmt = '{sample}_{energy}eV_wa{wax}_bpm{xbpm}'
for e, xsss, ysss in zip(energies, xss, yss):
yield from bps.mv(energy, e)
yield from bps.sleep(1)
yield from bps.mv(piezo.y, ysss)
yield from bps.mv(piezo.x, xsss)
bpm = xbpm2.sumX.value
sample_name = name_fmt.format(sample=name, energy='%6.2f'%e, wax = wa, xbpm = '%4.3f'%bpm)
sample_id(user_name='WZ', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
yield from bps.mv(energy, 2470)
yield from bps.mv(energy, 2450)
def wenkai_waxs_tensile_tender_2021_2(t=1):
#85s to do the loop
dets = [pil300KW, pil1M]
names = 'SSC_loop4_waxs'
t0 = time.time()
# yield from bps.mvr(stage.y, -0.4)
for i in range(60):
det_exposure_time(t,t)
yield from bps.mvr(stage.y, 0.03)
if waxs.arc.position > 5:
wa = [19.5, 13, 6.5, 0]
else:
wa = [0, 6.5, 13, 19.5]
t1 = time.time()
for wax in wa:
name_fmt = '{sample}_2455.0eV_sdd3m_{time}s_{i}_wa{wa}'
yield from bps.mv(waxs, wax)
sample_name = name_fmt.format(sample=names, time = '%1.1f'%(t1-t0), i = '%3.3d'%i, wa = '%1.1f'%wax)
sample_id(user_name='GF', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
yield from bps.sleep(5)
t2 = time.time()
print(t2-t0)
def wenkai_waxsonly_tensile_tender_2021_2(t=1):
#85s to do the loop
dets = [pil300KW]
names = 'LSC_loop5_waxs_kaclamp'
t0 = time.time()
# yield from bps.mvr(stage.y, -0.4)
for i in range(1000):
det_exposure_time(t,t)
yield from bps.mvr(stage.y, 0.01)
t1 = time.time()
name_fmt = '{sample}_2484.25eV_sdd3m_{time}s_{i}_wa{wa}'
sample_name = name_fmt.format(sample=names, time = '%1.1f'%(t1-t0), i = '%3.3d'%i, wa = '%1.1f'%0)
sample_id(user_name='GF', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
t2 = time.time()
print(t2-t0)
def wenkai_saxsonly_tensile_tender_2021_2(t=1):
#85s to do the loop
dets = [pil300KW, pil1M]
names = 'SSC_loop3_saxs'
t0 = time.time()
# yield from bps.mvr(stage.y, -0.4)
for i in range(1000):
det_exposure_time(t,t)
yield from bps.mvr(stage.y, 0.005)
t1 = time.time()
name_fmt = '{sample}_2484.24eV_sdd3m_{time}s_{i}_wa{wa}'
sample_name = name_fmt.format(sample=names, time = '%1.1f'%(t1-t0), i = '%3.3d'%i, wa = '%1.1f'%8)
sample_id(user_name='GF', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
yield from bps.sleep(0.5)
t2 = time.time()
print(t2-t0)
def wenkai_saxs_waxs_tensile_hard(t=1):
dets = [pil300KW, pil1M]
names = 'PF-T2PO1_loop1'
t0 = time.time()
for i in range(2000):
det_exposure_time(t,t)
if waxs.arc.position > 5:
wa = [13, 6.5, 0]
else:
wa = [0, 6.5, 13]
name_fmt = '{sample}_14000eV_{time}s_{i}_wa{wa}'
t1 = time.time()
for wax in wa:
yield from bps.mv(waxs, wax)
sample_name = name_fmt.format(sample=names, time = '%1.1f'%(t1-t0), i = '%3.3d'%i, wa = '%1.1f'%wax)
sample_id(user_name='GF', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
def wenkai_waxs_tensile_2021_3(t=0.5):
names = 'LSC_RT_loop1'
dets = [pil900KW, pil300KW]
wa = [0]
yield from bps.mv(stage.y, 0.1)
t0 = time.time()
for i in range(2000):
det_exposure_time(t,t)
name_fmt = '{sample}_14keV_{time}s_{i}_wa{wa}'
t1 = time.time()
for wax in wa:
yield from bps.mv(waxs, wax)
sample_name = name_fmt.format(sample=names, time = '%1.1f'%(t1-t0), i = '%3.3d'%i, wa = '%1.1f'%wax)
sample_id(user_name='GF', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
yield from bps.mvr(stage.y, 0.01)
# yield from bps.sleep(2)
def wenkai_saxs_tensile_2021_3(t=0.5):
names = 'LSC_RT_loop6_samesample'
dets = [pil1M]
wa = [20]
yield from bps.mv(stage.y, -0.3)
t0 = time.time()
for i in range(2000):
det_exposure_time(t,t)
name_fmt = '{sample}_2484.24keV_{time}s_{i}_wa{wa}'
t1 = time.time()
for wax in wa:
yield from bps.mv(waxs, wax)
sample_name = name_fmt.format(sample=names, time = '%1.1f'%(t1-t0), i = '%3.3d'%i, wa = '%1.1f'%wax)
sample_id(user_name='GF', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
yield from bps.mvr(stage.y, 0.01)
# yield from bps.sleep(2)
|
def giwaxs_s_edge_wenkai(t=1):
dets = [pil300KW]
names = ['A2', 'A3', 'A4', 'A5', 'A6']
x = [30000, 16000, 0, -15000, -36000]
energies = np.arange(2450, 2470, 5).tolist() + np.arange(2470, 2480, 0.25).tolist() + np.arange(2480, 2490, 1).tolist() + np.arange(2490, 2501, 5).tolist()
waxs_arc = np.linspace(0, 26, 5)
ai0 = 0
for (name, xs) in zip(names, x):
yield from bps.mv(piezo.x, xs)
yield from bps.mv(piezo.th, ai0)
yield from bps.mv(GV7.open_cmd, 1)
yield from bps.sleep(1)
yield from bps.mv(GV7.open_cmd, 1)
yield from bps.sleep(1)
yield from alignement_gisaxs(angle=0.4)
yield from bps.mv(GV7.close_cmd, 1)
yield from bps.sleep(1)
yield from bps.mv(GV7.close_cmd, 1)
yield from bps.sleep(1)
ai0 = piezo.th.position
yield from bps.mv(piezo.th, ai0 + 0.7)
xss = np.linspace(xs, xs - 8000, 57)
for wa in waxs_arc:
yield from bps.mv(waxs, wa)
det_exposure_time(t, t)
name_fmt = '{sample}_{energy}eV_wa{wax}_bpm{xbpm}'
for (e, xsss) in zip(energies, xss):
yield from bps.mv(energy, e)
yield from bps.sleep(2)
yield from bps.mv(piezo.x, xsss)
bpm = xbpm2.sumX.value
sample_name = name_fmt.format(sample=name, energy='%6.2f' % e, wax=wa, xbpm='%4.3f' % bpm)
sample_id(user_name='GF', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
yield from bps.mv(energy, 2470)
yield from bps.mv(energy, 2450)
def nexafs_s_edge_wenkai(t=1):
dets = [pil300KW]
names = ['PFSA_LSC']
x = [41200]
y = [-8000]
z = [2700]
energies = np.linspace(2450, 2500, 51)
energies = np.arange(2450, 2470, 5).tolist() + np.arange(2470, 2480, 0.25).tolist() + np.arange(2480, 2490, 1).tolist() + np.arange(2490, 2501, 5).tolist()
energies1 = 10 + np.asarray(np.arange(2445, 2470, 5).tolist() + np.arange(2470, 2480, 0.25).tolist() + np.arange(2480, 2490, 1).tolist() + np.arange(2490, 2501, 5).tolist())
for (name, xs) in zip(names, x):
det_exposure_time(t, t)
name_fmt = 'nexafs_{sample}_{energy}eV_wa52.00_bpm{xbpm}'
for e in energies:
yield from bps.mv(energy, e)
yield from bps.sleep(1)
bpm = xbpm2.sumX.value
sample_name = name_fmt.format(sample=name, energy='%6.2f' % e, xbpm='%4.3f' % bpm)
sample_id(user_name='GF', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
yield from bps.mv(energy, 2470)
yield from bps.mv(energy, 2450)
def hardxray_wenkai2020_1(t=1):
dets = [pil300KW, pil1M]
names = ['PFSA_LSC', 'PFSA_LSC', 'N2200_vert', 'N2200_hori', 'A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2', 'A3', 'B3', 'C3', 'D3']
x = [41000, 29000, -8000, -30000, 43800, 37500, 32500, 27500, 22500, 17100, 12100, 5900, -16900, -21900, -27300, -32500]
y = [-8000, -8000, -8000, -8000, 3800, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4200]
z = [2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700]
waxs_arc = np.linspace(0, 39, 7)
for wa in waxs_arc:
yield from bps.mv(waxs, wa)
for (name, xs, ys, zs) in zip(names, x, y, z):
yield from bps.mv(piezo.x, xs)
yield from bps.mv(piezo.y, ys)
yield from bps.mv(piezo.z, zs)
det_exposure_time(t, t)
name_fmt = '{sample}_16.1keVeV_8.3m_wa{wax}'
yield from bps.sleep(1)
sample_name = name_fmt.format(sample=name, wax=wa)
sample_id(user_name='WZ', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
def waxs_s_edge_wenkai_2021_1(t=1):
dets = [pil1M, pil300KW]
energies = np.arange(2450, 2470, 5).tolist() + np.arange(2470, 2480, 0.25).tolist() + np.arange(2480, 2490, 1).tolist() + np.arange(2490, 2501, 5).tolist()
names = ['N2200_vert', 'N2200_hori']
x = [-8500, -30500]
y = [-8500, -8000]
z = [2700, 2700]
waxs_arc = np.linspace(0, 19.5, 4)
for wa in waxs_arc:
yield from bps.mv(waxs, wa)
for (name, xs, ys, zs) in zip(names, x, y, z):
yield from bps.mv(piezo.x, xs)
yield from bps.mv(piezo.y, ys)
yield from bps.mv(piezo.z, zs)
yss = np.linspace(ys, ys + 1000, 29)
xss = np.array([xs, xs + 500])
(yss, xss) = np.meshgrid(yss, xss)
yss = yss.ravel()
xss = xss.ravel()
det_exposure_time(t, t)
name_fmt = '{sample}_{energy}eV_wa{wax}_bpm{xbpm}'
for (e, xsss, ysss) in zip(energies, xss, yss):
yield from bps.mv(energy, e)
yield from bps.sleep(1)
yield from bps.mv(piezo.y, ysss)
yield from bps.mv(piezo.x, xsss)
bpm = xbpm2.sumX.value
sample_name = name_fmt.format(sample=name, energy='%6.2f' % e, wax=wa, xbpm='%4.3f' % bpm)
sample_id(user_name='WZ', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
yield from bps.mv(energy, 2470)
yield from bps.mv(energy, 2450)
def wenkai_waxs_tensile_tender_2021_2(t=1):
dets = [pil300KW, pil1M]
names = 'SSC_loop4_waxs'
t0 = time.time()
for i in range(60):
det_exposure_time(t, t)
yield from bps.mvr(stage.y, 0.03)
if waxs.arc.position > 5:
wa = [19.5, 13, 6.5, 0]
else:
wa = [0, 6.5, 13, 19.5]
t1 = time.time()
for wax in wa:
name_fmt = '{sample}_2455.0eV_sdd3m_{time}s_{i}_wa{wa}'
yield from bps.mv(waxs, wax)
sample_name = name_fmt.format(sample=names, time='%1.1f' % (t1 - t0), i='%3.3d' % i, wa='%1.1f' % wax)
sample_id(user_name='GF', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
yield from bps.sleep(5)
t2 = time.time()
print(t2 - t0)
def wenkai_waxsonly_tensile_tender_2021_2(t=1):
dets = [pil300KW]
names = 'LSC_loop5_waxs_kaclamp'
t0 = time.time()
for i in range(1000):
det_exposure_time(t, t)
yield from bps.mvr(stage.y, 0.01)
t1 = time.time()
name_fmt = '{sample}_2484.25eV_sdd3m_{time}s_{i}_wa{wa}'
sample_name = name_fmt.format(sample=names, time='%1.1f' % (t1 - t0), i='%3.3d' % i, wa='%1.1f' % 0)
sample_id(user_name='GF', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
t2 = time.time()
print(t2 - t0)
def wenkai_saxsonly_tensile_tender_2021_2(t=1):
dets = [pil300KW, pil1M]
names = 'SSC_loop3_saxs'
t0 = time.time()
for i in range(1000):
det_exposure_time(t, t)
yield from bps.mvr(stage.y, 0.005)
t1 = time.time()
name_fmt = '{sample}_2484.24eV_sdd3m_{time}s_{i}_wa{wa}'
sample_name = name_fmt.format(sample=names, time='%1.1f' % (t1 - t0), i='%3.3d' % i, wa='%1.1f' % 8)
sample_id(user_name='GF', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
yield from bps.sleep(0.5)
t2 = time.time()
print(t2 - t0)
def wenkai_saxs_waxs_tensile_hard(t=1):
dets = [pil300KW, pil1M]
names = 'PF-T2PO1_loop1'
t0 = time.time()
for i in range(2000):
det_exposure_time(t, t)
if waxs.arc.position > 5:
wa = [13, 6.5, 0]
else:
wa = [0, 6.5, 13]
name_fmt = '{sample}_14000eV_{time}s_{i}_wa{wa}'
t1 = time.time()
for wax in wa:
yield from bps.mv(waxs, wax)
sample_name = name_fmt.format(sample=names, time='%1.1f' % (t1 - t0), i='%3.3d' % i, wa='%1.1f' % wax)
sample_id(user_name='GF', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
def wenkai_waxs_tensile_2021_3(t=0.5):
names = 'LSC_RT_loop1'
dets = [pil900KW, pil300KW]
wa = [0]
yield from bps.mv(stage.y, 0.1)
t0 = time.time()
for i in range(2000):
det_exposure_time(t, t)
name_fmt = '{sample}_14keV_{time}s_{i}_wa{wa}'
t1 = time.time()
for wax in wa:
yield from bps.mv(waxs, wax)
sample_name = name_fmt.format(sample=names, time='%1.1f' % (t1 - t0), i='%3.3d' % i, wa='%1.1f' % wax)
sample_id(user_name='GF', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
yield from bps.mvr(stage.y, 0.01)
def wenkai_saxs_tensile_2021_3(t=0.5):
names = 'LSC_RT_loop6_samesample'
dets = [pil1M]
wa = [20]
yield from bps.mv(stage.y, -0.3)
t0 = time.time()
for i in range(2000):
det_exposure_time(t, t)
name_fmt = '{sample}_2484.24keV_{time}s_{i}_wa{wa}'
t1 = time.time()
for wax in wa:
yield from bps.mv(waxs, wax)
sample_name = name_fmt.format(sample=names, time='%1.1f' % (t1 - t0), i='%3.3d' % i, wa='%1.1f' % wax)
sample_id(user_name='GF', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
yield from bps.mvr(stage.y, 0.01)
|
# -*- coding: utf-8 -*-
"""
This module recieves an ForecastIO object and holds the currently weather
conditions. It has one class for this purpose.
"""
class FIOCurrently(object):
"""
This class recieves an ForecastIO object and holds the currently weather
conditions.
"""
currently = None
def __init__(self, forecast_io):
"""
Construct a new 'FIOCurrently' object.
Recieves an ForecastIO object and gets the currently weather conditions
if they are available in the object.
Args:
forecast_io (ForecastIO): The ForecastIO object
"""
if forecast_io.has_currently():
self.currently = forecast_io.get_currently()
for item in self.currently.keys():
setattr(self, item, self.currently[item])
def get(self):
"""
Returns a dictionary with current weather conditions.
Returns None is none are available.
Returns:
Dictionary with current weather conditions.
None is none are available.
"""
return self.currently
|
"""
This module recieves an ForecastIO object and holds the currently weather
conditions. It has one class for this purpose.
"""
class Fiocurrently(object):
"""
This class recieves an ForecastIO object and holds the currently weather
conditions.
"""
currently = None
def __init__(self, forecast_io):
"""
Construct a new 'FIOCurrently' object.
Recieves an ForecastIO object and gets the currently weather conditions
if they are available in the object.
Args:
forecast_io (ForecastIO): The ForecastIO object
"""
if forecast_io.has_currently():
self.currently = forecast_io.get_currently()
for item in self.currently.keys():
setattr(self, item, self.currently[item])
def get(self):
"""
Returns a dictionary with current weather conditions.
Returns None is none are available.
Returns:
Dictionary with current weather conditions.
None is none are available.
"""
return self.currently
|
"""Module providing logic for retrieving bibitems
via xml2rfc-style paths, and serializing them to
xml2rfc-style RFC 7991 XML.
"""
|
"""Module providing logic for retrieving bibitems
via xml2rfc-style paths, and serializing them to
xml2rfc-style RFC 7991 XML.
"""
|
#
# PySNMP MIB module AILUXCONNECT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AILUXCONNECT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:00:39 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
AIIConnType, = mibBuilder.importSymbols("AISYSTEM-MIB", "AIIConnType")
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint")
InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Counter32, Bits, Gauge32, enterprises, ObjectIdentity, NotificationType, Counter64, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, TimeTicks, Unsigned32, IpAddress, iso, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "Bits", "Gauge32", "enterprises", "ObjectIdentity", "NotificationType", "Counter64", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "TimeTicks", "Unsigned32", "IpAddress", "iso", "MibIdentifier")
DisplayString, TextualConvention, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "TruthValue")
aii = MibIdentifier((1, 3, 6, 1, 4, 1, 539))
aiLuxConnect = ModuleIdentity((1, 3, 6, 1, 4, 1, 539, 33))
aiLuxConnect.setRevisions(('2001-04-30 17:00',))
if mibBuilder.loadTexts: aiLuxConnect.setLastUpdated('200104301700Z')
if mibBuilder.loadTexts: aiLuxConnect.setOrganization('Applied Innovation Inc.')
aiLCTrapInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 539, 33, 0))
aiLCTrapGtranSwitch = NotificationType((1, 3, 6, 1, 4, 1, 539, 33, 0, 1)).setObjects(("AILUXCONNECT-MIB", "aiLCGtranActiveIndex"), ("AILUXCONNECT-MIB", "aiLCGtranActiveSpan"))
if mibBuilder.loadTexts: aiLCTrapGtranSwitch.setStatus('current')
aiLCTrapGbicInserted = NotificationType((1, 3, 6, 1, 4, 1, 539, 33, 0, 2)).setObjects(("AILUXCONNECT-MIB", "aiLCGbicIndex"), ("AILUXCONNECT-MIB", "aiLCGbicConnectorType"))
if mibBuilder.loadTexts: aiLCTrapGbicInserted.setStatus('current')
aiLCTrapGbicRemoved = NotificationType((1, 3, 6, 1, 4, 1, 539, 33, 0, 3)).setObjects(("AILUXCONNECT-MIB", "aiLCGbicIndex"), ("AILUXCONNECT-MIB", "aiLCGbicConnectorType"))
if mibBuilder.loadTexts: aiLCTrapGbicRemoved.setStatus('current')
aiLCGtranActiveTable = MibTable((1, 3, 6, 1, 4, 1, 539, 33, 1), )
if mibBuilder.loadTexts: aiLCGtranActiveTable.setStatus('current')
aiLCGtranActiveEntry = MibTableRow((1, 3, 6, 1, 4, 1, 539, 33, 1, 1), ).setIndexNames((0, "AILUXCONNECT-MIB", "aiLCGtranActiveIndex"))
if mibBuilder.loadTexts: aiLCGtranActiveEntry.setStatus('current')
aiLCGtranActiveIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 1), InterfaceIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: aiLCGtranActiveIndex.setStatus('current')
aiLCGtranActiveBackupIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 2), InterfaceIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: aiLCGtranActiveBackupIndex.setStatus('current')
aiLCGtranActiveSpan = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("work", 1), ("protect", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: aiLCGtranActiveSpan.setStatus('current')
aiLCGtranActiveRxUtilization = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("readonly")
if mibBuilder.loadTexts: aiLCGtranActiveRxUtilization.setStatus('current')
aiLCGtranActiveTxUtilization = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("readonly")
if mibBuilder.loadTexts: aiLCGtranActiveTxUtilization.setStatus('current')
aiLCGtranActiveClockSlave = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 6), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: aiLCGtranActiveClockSlave.setStatus('current')
aiLCGtranActiveCoolerStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("up", 1), ("down", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: aiLCGtranActiveCoolerStatus.setStatus('current')
aiLCGtranActiveTemperature = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("okay", 1), ("trouble", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: aiLCGtranActiveTemperature.setStatus('current')
aiLCGtranActiveRxPower = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("okay", 1), ("under", 2), ("over", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: aiLCGtranActiveRxPower.setStatus('current')
aiLCGtranActiveTxPower = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("okay", 1), ("under", 2), ("over", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: aiLCGtranActiveTxPower.setStatus('current')
aiLCGtranBackupTable = MibTable((1, 3, 6, 1, 4, 1, 539, 33, 2), )
if mibBuilder.loadTexts: aiLCGtranBackupTable.setStatus('current')
aiLCGtranBackupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 539, 33, 2, 1), ).setIndexNames((0, "AILUXCONNECT-MIB", "aiLCGtranBackupIndex"))
if mibBuilder.loadTexts: aiLCGtranBackupEntry.setStatus('current')
aiLCGtranBackupIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 2, 1, 1), InterfaceIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: aiLCGtranBackupIndex.setStatus('current')
aiLCGtranBackupActiveIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 2, 1, 2), InterfaceIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: aiLCGtranBackupActiveIndex.setStatus('current')
aiLcGbicTable = MibTable((1, 3, 6, 1, 4, 1, 539, 33, 3), )
if mibBuilder.loadTexts: aiLcGbicTable.setStatus('current')
aiLCGbicEntry = MibTableRow((1, 3, 6, 1, 4, 1, 539, 33, 3, 1), ).setIndexNames((0, "AILUXCONNECT-MIB", "aiLCGbicIndex"))
if mibBuilder.loadTexts: aiLCGbicEntry.setStatus('current')
aiLCGbicIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 3, 1, 1), InterfaceIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: aiLCGbicIndex.setStatus('current')
aiLCGbicConnectorType = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 3, 1, 2), AIIConnType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: aiLCGbicConnectorType.setStatus('current')
aiLCGbicTxMode = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("down", 1), ("up", 2), ("gtran", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: aiLCGbicTxMode.setStatus('current')
aiLCGbicRxUtilization = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 3, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("readonly")
if mibBuilder.loadTexts: aiLCGbicRxUtilization.setStatus('current')
aiLCGbicTxUtilization = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 3, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("readonly")
if mibBuilder.loadTexts: aiLCGbicTxUtilization.setStatus('current')
mibBuilder.exportSymbols("AILUXCONNECT-MIB", aiLCGtranActiveBackupIndex=aiLCGtranActiveBackupIndex, aiLCGbicConnectorType=aiLCGbicConnectorType, aiLCGtranActiveEntry=aiLCGtranActiveEntry, aiLCGtranActiveClockSlave=aiLCGtranActiveClockSlave, aiLCTrapGbicInserted=aiLCTrapGbicInserted, aiLCGbicEntry=aiLCGbicEntry, aiLCGtranBackupIndex=aiLCGtranBackupIndex, aiLCGtranActiveTxPower=aiLCGtranActiveTxPower, aiLCTrapGbicRemoved=aiLCTrapGbicRemoved, aiLCGtranBackupEntry=aiLCGtranBackupEntry, aiLCTrapGtranSwitch=aiLCTrapGtranSwitch, aiLuxConnect=aiLuxConnect, aii=aii, aiLCGtranActiveRxUtilization=aiLCGtranActiveRxUtilization, aiLCGtranBackupTable=aiLCGtranBackupTable, aiLCGtranActiveIndex=aiLCGtranActiveIndex, aiLCTrapInfo=aiLCTrapInfo, aiLCGtranActiveTable=aiLCGtranActiveTable, aiLCGtranActiveTxUtilization=aiLCGtranActiveTxUtilization, aiLCGtranBackupActiveIndex=aiLCGtranBackupActiveIndex, PYSNMP_MODULE_ID=aiLuxConnect, aiLCGbicTxUtilization=aiLCGbicTxUtilization, aiLCGtranActiveRxPower=aiLCGtranActiveRxPower, aiLcGbicTable=aiLcGbicTable, aiLCGbicIndex=aiLCGbicIndex, aiLCGtranActiveSpan=aiLCGtranActiveSpan, aiLCGtranActiveTemperature=aiLCGtranActiveTemperature, aiLCGbicRxUtilization=aiLCGbicRxUtilization, aiLCGbicTxMode=aiLCGbicTxMode, aiLCGtranActiveCoolerStatus=aiLCGtranActiveCoolerStatus)
|
(aii_conn_type,) = mibBuilder.importSymbols('AISYSTEM-MIB', 'AIIConnType')
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_union, constraints_intersection, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsUnion', 'ConstraintsIntersection', 'SingleValueConstraint')
(interface_index,) = mibBuilder.importSymbols('IF-MIB', 'InterfaceIndex')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(counter32, bits, gauge32, enterprises, object_identity, notification_type, counter64, integer32, mib_scalar, mib_table, mib_table_row, mib_table_column, module_identity, time_ticks, unsigned32, ip_address, iso, mib_identifier) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter32', 'Bits', 'Gauge32', 'enterprises', 'ObjectIdentity', 'NotificationType', 'Counter64', 'Integer32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ModuleIdentity', 'TimeTicks', 'Unsigned32', 'IpAddress', 'iso', 'MibIdentifier')
(display_string, textual_convention, truth_value) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention', 'TruthValue')
aii = mib_identifier((1, 3, 6, 1, 4, 1, 539))
ai_lux_connect = module_identity((1, 3, 6, 1, 4, 1, 539, 33))
aiLuxConnect.setRevisions(('2001-04-30 17:00',))
if mibBuilder.loadTexts:
aiLuxConnect.setLastUpdated('200104301700Z')
if mibBuilder.loadTexts:
aiLuxConnect.setOrganization('Applied Innovation Inc.')
ai_lc_trap_info = mib_identifier((1, 3, 6, 1, 4, 1, 539, 33, 0))
ai_lc_trap_gtran_switch = notification_type((1, 3, 6, 1, 4, 1, 539, 33, 0, 1)).setObjects(('AILUXCONNECT-MIB', 'aiLCGtranActiveIndex'), ('AILUXCONNECT-MIB', 'aiLCGtranActiveSpan'))
if mibBuilder.loadTexts:
aiLCTrapGtranSwitch.setStatus('current')
ai_lc_trap_gbic_inserted = notification_type((1, 3, 6, 1, 4, 1, 539, 33, 0, 2)).setObjects(('AILUXCONNECT-MIB', 'aiLCGbicIndex'), ('AILUXCONNECT-MIB', 'aiLCGbicConnectorType'))
if mibBuilder.loadTexts:
aiLCTrapGbicInserted.setStatus('current')
ai_lc_trap_gbic_removed = notification_type((1, 3, 6, 1, 4, 1, 539, 33, 0, 3)).setObjects(('AILUXCONNECT-MIB', 'aiLCGbicIndex'), ('AILUXCONNECT-MIB', 'aiLCGbicConnectorType'))
if mibBuilder.loadTexts:
aiLCTrapGbicRemoved.setStatus('current')
ai_lc_gtran_active_table = mib_table((1, 3, 6, 1, 4, 1, 539, 33, 1))
if mibBuilder.loadTexts:
aiLCGtranActiveTable.setStatus('current')
ai_lc_gtran_active_entry = mib_table_row((1, 3, 6, 1, 4, 1, 539, 33, 1, 1)).setIndexNames((0, 'AILUXCONNECT-MIB', 'aiLCGtranActiveIndex'))
if mibBuilder.loadTexts:
aiLCGtranActiveEntry.setStatus('current')
ai_lc_gtran_active_index = mib_table_column((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 1), interface_index()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
aiLCGtranActiveIndex.setStatus('current')
ai_lc_gtran_active_backup_index = mib_table_column((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 2), interface_index()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
aiLCGtranActiveBackupIndex.setStatus('current')
ai_lc_gtran_active_span = mib_table_column((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('work', 1), ('protect', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
aiLCGtranActiveSpan.setStatus('current')
ai_lc_gtran_active_rx_utilization = mib_table_column((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(0, 100))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
aiLCGtranActiveRxUtilization.setStatus('current')
ai_lc_gtran_active_tx_utilization = mib_table_column((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(0, 100))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
aiLCGtranActiveTxUtilization.setStatus('current')
ai_lc_gtran_active_clock_slave = mib_table_column((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 6), truth_value()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
aiLCGtranActiveClockSlave.setStatus('current')
ai_lc_gtran_active_cooler_status = mib_table_column((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('up', 1), ('down', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
aiLCGtranActiveCoolerStatus.setStatus('current')
ai_lc_gtran_active_temperature = mib_table_column((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 8), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('okay', 1), ('trouble', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
aiLCGtranActiveTemperature.setStatus('current')
ai_lc_gtran_active_rx_power = mib_table_column((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 9), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('okay', 1), ('under', 2), ('over', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
aiLCGtranActiveRxPower.setStatus('current')
ai_lc_gtran_active_tx_power = mib_table_column((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 10), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('okay', 1), ('under', 2), ('over', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
aiLCGtranActiveTxPower.setStatus('current')
ai_lc_gtran_backup_table = mib_table((1, 3, 6, 1, 4, 1, 539, 33, 2))
if mibBuilder.loadTexts:
aiLCGtranBackupTable.setStatus('current')
ai_lc_gtran_backup_entry = mib_table_row((1, 3, 6, 1, 4, 1, 539, 33, 2, 1)).setIndexNames((0, 'AILUXCONNECT-MIB', 'aiLCGtranBackupIndex'))
if mibBuilder.loadTexts:
aiLCGtranBackupEntry.setStatus('current')
ai_lc_gtran_backup_index = mib_table_column((1, 3, 6, 1, 4, 1, 539, 33, 2, 1, 1), interface_index()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
aiLCGtranBackupIndex.setStatus('current')
ai_lc_gtran_backup_active_index = mib_table_column((1, 3, 6, 1, 4, 1, 539, 33, 2, 1, 2), interface_index()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
aiLCGtranBackupActiveIndex.setStatus('current')
ai_lc_gbic_table = mib_table((1, 3, 6, 1, 4, 1, 539, 33, 3))
if mibBuilder.loadTexts:
aiLcGbicTable.setStatus('current')
ai_lc_gbic_entry = mib_table_row((1, 3, 6, 1, 4, 1, 539, 33, 3, 1)).setIndexNames((0, 'AILUXCONNECT-MIB', 'aiLCGbicIndex'))
if mibBuilder.loadTexts:
aiLCGbicEntry.setStatus('current')
ai_lc_gbic_index = mib_table_column((1, 3, 6, 1, 4, 1, 539, 33, 3, 1, 1), interface_index()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
aiLCGbicIndex.setStatus('current')
ai_lc_gbic_connector_type = mib_table_column((1, 3, 6, 1, 4, 1, 539, 33, 3, 1, 2), aii_conn_type()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
aiLCGbicConnectorType.setStatus('current')
ai_lc_gbic_tx_mode = mib_table_column((1, 3, 6, 1, 4, 1, 539, 33, 3, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('down', 1), ('up', 2), ('gtran', 3)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
aiLCGbicTxMode.setStatus('current')
ai_lc_gbic_rx_utilization = mib_table_column((1, 3, 6, 1, 4, 1, 539, 33, 3, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(0, 100))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
aiLCGbicRxUtilization.setStatus('current')
ai_lc_gbic_tx_utilization = mib_table_column((1, 3, 6, 1, 4, 1, 539, 33, 3, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(0, 100))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
aiLCGbicTxUtilization.setStatus('current')
mibBuilder.exportSymbols('AILUXCONNECT-MIB', aiLCGtranActiveBackupIndex=aiLCGtranActiveBackupIndex, aiLCGbicConnectorType=aiLCGbicConnectorType, aiLCGtranActiveEntry=aiLCGtranActiveEntry, aiLCGtranActiveClockSlave=aiLCGtranActiveClockSlave, aiLCTrapGbicInserted=aiLCTrapGbicInserted, aiLCGbicEntry=aiLCGbicEntry, aiLCGtranBackupIndex=aiLCGtranBackupIndex, aiLCGtranActiveTxPower=aiLCGtranActiveTxPower, aiLCTrapGbicRemoved=aiLCTrapGbicRemoved, aiLCGtranBackupEntry=aiLCGtranBackupEntry, aiLCTrapGtranSwitch=aiLCTrapGtranSwitch, aiLuxConnect=aiLuxConnect, aii=aii, aiLCGtranActiveRxUtilization=aiLCGtranActiveRxUtilization, aiLCGtranBackupTable=aiLCGtranBackupTable, aiLCGtranActiveIndex=aiLCGtranActiveIndex, aiLCTrapInfo=aiLCTrapInfo, aiLCGtranActiveTable=aiLCGtranActiveTable, aiLCGtranActiveTxUtilization=aiLCGtranActiveTxUtilization, aiLCGtranBackupActiveIndex=aiLCGtranBackupActiveIndex, PYSNMP_MODULE_ID=aiLuxConnect, aiLCGbicTxUtilization=aiLCGbicTxUtilization, aiLCGtranActiveRxPower=aiLCGtranActiveRxPower, aiLcGbicTable=aiLcGbicTable, aiLCGbicIndex=aiLCGbicIndex, aiLCGtranActiveSpan=aiLCGtranActiveSpan, aiLCGtranActiveTemperature=aiLCGtranActiveTemperature, aiLCGbicRxUtilization=aiLCGbicRxUtilization, aiLCGbicTxMode=aiLCGbicTxMode, aiLCGtranActiveCoolerStatus=aiLCGtranActiveCoolerStatus)
|
def test_get_custom_properties(exporters, mocker):
blender_data = mocker.MagicMock()
vector = mocker.MagicMock()
vector.to_list.return_value = [0.0, 0.0, 1.0]
blender_data.items.return_value = [
['str', 'spam'],
['float', 1.0],
['int', 42],
['bool', False],
['vector', vector],
]
assert exporters.BaseExporter.get_custom_properties(blender_data) == {
'str': 'spam',
'float': 1.0,
'int': 42,
'bool': False,
'vector': [0.0, 0.0, 1.0]
}
def test_ignore_properties(exporters, mocker):
blender_data = mocker.MagicMock()
blender_data.items.return_value = [
['_RNA_UI', None],
['cycles', None],
['cycles_visibility', None],
['str', 'remains'],
]
assert exporters.BaseExporter.get_custom_properties(blender_data) == {
'str': 'remains',
}
def test_invalid_properties(exporters, mocker):
blender_data = mocker.MagicMock()
blender_data.items.return_value = [
['unserializable', set()],
['str', 'remains'],
]
assert exporters.BaseExporter.get_custom_properties(blender_data) == {
'str': 'remains',
}
def test_check(exporters):
assert exporters.BaseExporter.check(None, None)
def test_default(exporters, mocker):
blender_data = mocker.MagicMock()
blender_data.name = 'Name'
assert exporters.BaseExporter.default(None, blender_data) == {'name': 'Name'}
def test_export(exporters):
assert exporters.BaseExporter.export(None, None) == {}
|
def test_get_custom_properties(exporters, mocker):
blender_data = mocker.MagicMock()
vector = mocker.MagicMock()
vector.to_list.return_value = [0.0, 0.0, 1.0]
blender_data.items.return_value = [['str', 'spam'], ['float', 1.0], ['int', 42], ['bool', False], ['vector', vector]]
assert exporters.BaseExporter.get_custom_properties(blender_data) == {'str': 'spam', 'float': 1.0, 'int': 42, 'bool': False, 'vector': [0.0, 0.0, 1.0]}
def test_ignore_properties(exporters, mocker):
blender_data = mocker.MagicMock()
blender_data.items.return_value = [['_RNA_UI', None], ['cycles', None], ['cycles_visibility', None], ['str', 'remains']]
assert exporters.BaseExporter.get_custom_properties(blender_data) == {'str': 'remains'}
def test_invalid_properties(exporters, mocker):
blender_data = mocker.MagicMock()
blender_data.items.return_value = [['unserializable', set()], ['str', 'remains']]
assert exporters.BaseExporter.get_custom_properties(blender_data) == {'str': 'remains'}
def test_check(exporters):
assert exporters.BaseExporter.check(None, None)
def test_default(exporters, mocker):
blender_data = mocker.MagicMock()
blender_data.name = 'Name'
assert exporters.BaseExporter.default(None, blender_data) == {'name': 'Name'}
def test_export(exporters):
assert exporters.BaseExporter.export(None, None) == {}
|
{
'includes': [ '../common.gypi' ],
'targets': [
{
'target_name': 'shbench',
'product_name': 'shbench',
'type' : 'executable',
'conditions': [
['OS=="linux"', {
'ldflags': [
'-pthread'
]
}],
],
'defines': [
'SYS_MULTI_THREAD'
],
'sources': [
'src/sh6bench.c'
],
'include_dirs': [ 'src' ]
}
]
}
|
{'includes': ['../common.gypi'], 'targets': [{'target_name': 'shbench', 'product_name': 'shbench', 'type': 'executable', 'conditions': [['OS=="linux"', {'ldflags': ['-pthread']}]], 'defines': ['SYS_MULTI_THREAD'], 'sources': ['src/sh6bench.c'], 'include_dirs': ['src']}]}
|
#
# Copyright (c) 2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
Definitions file:
It's main functionality are:
1) housing project constants and enums.
2) housing configuration parameters.
3) housing resource paths.
"""
class Definitions:
GROUP_NAME = "rl_coach"
PROCESS_NAME = "coach"
DASHBOARD_PROC = "firefox"
class Flags:
css = "checkpoint_save_secs"
crd = "checkpoint_restore_dir"
et = "environment_type"
ept = "exploration_policy_type"
cp = "custom_parameter"
seed = "seed"
dccp = "distributed_coach_config_path"
"""
Arguments that can be tested for python coach command
** None = Flag - no need for string or int
** {} = Add format for this parameter
"""
cmd_args = {
# '-l': None,
# '-e': '{}',
# '-r': None,
# '-n': '{' + enw + '}',
# '-c': None,
# '-ew': None,
'--play': None,
'--evaluate': None,
# '-v': None,
# '-tfv': None,
'--nocolor': None,
# '-s': '{' + css + '}',
# '-crd': '{' + crd + '}',
'-dg': None,
'-dm': None,
# '-et': '{' + et + '}',
# '-ept': '{' + ept + '}',
# '-lvl': '{level}',
# '-cp': '{' + cp + '}',
'--print_networks_summary': None,
'-tb': None,
'-ns': None,
'-d': None,
# '--seed': '{' + seed + '}',
'-onnx': None,
'-dc': None,
# '-dcp': '{' + dccp + '}',
'-asc': None,
'--dump_worker_logs': None,
}
class Presets:
# Preset list for testing the flags/ arguments of python coach command
args_test = [
"CartPole_A3C",
# "CartPole_NEC",
]
class Path:
experiments = "./experiments"
tensorboard = "tensorboard"
gifs = "gifs"
videos = "videos"
class Consts:
ASSERT_MSG = "Expected: {}, Actual: {}."
RESULTS_SORTED = "Results stored at:"
TOTAL_RUNTIME = "Total runtime:"
DISCARD_EXP = "Do you want to discard the experiment results"
REACHED_REQ_ASC = "Reached required success rate. Exiting."
INPUT_EMBEDDER = "Input Embedder:"
MIDDLEWARE = "Middleware:"
OUTPUT_HEAD = "Output Head:"
ONNX_WARNING = "Exporting ONNX graphs requires setting the " \
"--checkpoint_save_secs flag. The --export_onnx_graph" \
" will have no effect."
COLOR_PREFIX = "## agent: Starting evaluation phase"
TRAINING = "Training - "
PLAY_WARNING = "Both the --preset and the --play flags were set. " \
"These flags can not be used together. For human " \
"control, please use the --play flag together with " \
"the environment type flag (-et)"
class TimeOuts:
test_time_limit = 60 * 60
wait_for_files = 20
|
"""
Definitions file:
It's main functionality are:
1) housing project constants and enums.
2) housing configuration parameters.
3) housing resource paths.
"""
class Definitions:
group_name = 'rl_coach'
process_name = 'coach'
dashboard_proc = 'firefox'
class Flags:
css = 'checkpoint_save_secs'
crd = 'checkpoint_restore_dir'
et = 'environment_type'
ept = 'exploration_policy_type'
cp = 'custom_parameter'
seed = 'seed'
dccp = 'distributed_coach_config_path'
'\n Arguments that can be tested for python coach command\n ** None = Flag - no need for string or int\n ** {} = Add format for this parameter\n '
cmd_args = {'--play': None, '--evaluate': None, '--nocolor': None, '-dg': None, '-dm': None, '--print_networks_summary': None, '-tb': None, '-ns': None, '-d': None, '-onnx': None, '-dc': None, '-asc': None, '--dump_worker_logs': None}
class Presets:
args_test = ['CartPole_A3C']
class Path:
experiments = './experiments'
tensorboard = 'tensorboard'
gifs = 'gifs'
videos = 'videos'
class Consts:
assert_msg = 'Expected: {}, Actual: {}.'
results_sorted = 'Results stored at:'
total_runtime = 'Total runtime:'
discard_exp = 'Do you want to discard the experiment results'
reached_req_asc = 'Reached required success rate. Exiting.'
input_embedder = 'Input Embedder:'
middleware = 'Middleware:'
output_head = 'Output Head:'
onnx_warning = 'Exporting ONNX graphs requires setting the --checkpoint_save_secs flag. The --export_onnx_graph will have no effect.'
color_prefix = '## agent: Starting evaluation phase'
training = 'Training - '
play_warning = 'Both the --preset and the --play flags were set. These flags can not be used together. For human control, please use the --play flag together with the environment type flag (-et)'
class Timeouts:
test_time_limit = 60 * 60
wait_for_files = 20
|
class AST:
""" Base class for abstract syntax trees """
pass
class BinOp(AST):
""" Binary operation for abstract syntax trees """
def __init__(self, left, op, right):
self.left = left
self.op = op
self.right = right
class Num(AST):
""" Node for numbers in abstract syntax trees """
def __init__(self, token):
self.token = token
self.value = token.value
|
class Ast:
""" Base class for abstract syntax trees """
pass
class Binop(AST):
""" Binary operation for abstract syntax trees """
def __init__(self, left, op, right):
self.left = left
self.op = op
self.right = right
class Num(AST):
""" Node for numbers in abstract syntax trees """
def __init__(self, token):
self.token = token
self.value = token.value
|
data = [['accesstoken', 'title', 'tab', 'content'],
['6eb92a53-9392-4dc5-a10a-3a853cad6e2c', 'helloworld', 'share', 'hshahdhsahashhdhahda']]
def parse_data():
json_data ={}
for i in range(len(data)):
for j in range(len(data[i])):
json_data[data[0][j]] = data[1][j]
print(json_data)
# parse_data()
jsondata = {
"accesstoken": "6eb92a53-9392-4dc5-a10a-3a853cad6e2c",
"title": "helloworld",
"tab": "share",
"content": "how to do api testing"
}
def queue_json_data():
# print(jsondata.keys(),jsondata.values())
for x in jsondata.keys():
temp = jsondata[x]
jsondata[x] = ""
print(jsondata)
jsondata[x] = temp
queue_json_data()
|
data = [['accesstoken', 'title', 'tab', 'content'], ['6eb92a53-9392-4dc5-a10a-3a853cad6e2c', 'helloworld', 'share', 'hshahdhsahashhdhahda']]
def parse_data():
json_data = {}
for i in range(len(data)):
for j in range(len(data[i])):
json_data[data[0][j]] = data[1][j]
print(json_data)
jsondata = {'accesstoken': '6eb92a53-9392-4dc5-a10a-3a853cad6e2c', 'title': 'helloworld', 'tab': 'share', 'content': 'how to do api testing'}
def queue_json_data():
for x in jsondata.keys():
temp = jsondata[x]
jsondata[x] = ''
print(jsondata)
jsondata[x] = temp
queue_json_data()
|
# Wrapper node Model
# Holds the rules and associated key
class Node:
def __init__(self, rules, key) -> None:
self.rules = rules
self.key = key
|
class Node:
def __init__(self, rules, key) -> None:
self.rules = rules
self.key = key
|
# binary search tree
# author: D1N3SHh
# https://github.com/D1N3SHh/algorithms
class Red_black_tree():
def __init__(self):
self.nil = Node(0, 'black', None, None)
self.root = self.nil
def __repr__(self):
return str(self.root)
def left_rotate(self, x):
y = x.right
x.right = y.left
if y.left != self.nil:
y.left.parent = x
y.parent = x.parent
if x.parent == self.nil:
self.root = y
elif x == x.parent.left:
x.parent.left = y
else: x.parent.right = y
x.left = x
x.parent = y
def right_rotate(self, x):
y = x.left
x.left = y.right
if y.right != self.nil:
y.right.parent = x
y.parent = x.parent
if x.parent == self.nil:
self.root = y
elif x == x.parent.right:
x.parent.right = y
else: x.parent.left = y
x.right = x
x.parent = y
def insert(self, z):
y = self.nil
x = self.root
while x != self.nil:
y = x
if z.key < x.key:
x = x.left
else: x = x.right
z.parent = y
if y == self.nil:
self.root = z
elif z.key < y.key or y.key == None:
y.left = z
else: y.right = z
z.left = self.nil
z.right = self.nil
z.color = 'red'
self.insert_fixup(z)
def insert_fixup(self, z):
while z != self.root and z.parent.color == 'red':
if z.parent == z.parent.parent.left:
y = z.parent.parent.right
if y.color == 'red':
z.parent.color = 'black'
y.color = 'black'
z.parent.parent.color = 'red'
z = z.parent.parent
else:
if z == z.parent.right:
z = z.parent
self.left_rotate(z)
z.parent.color = 'black'
z.parent.parent.color = 'red'
self.right_rotate(z.parent.parent)
else:
y = z.parent.parent.left
if y.color == 'red':
z.parent.color = 'black'
y.color = 'black'
z.parent.parent.color = 'red'
z = z.parent.parent
else:
if z == z.parent.left:
z = z.parent
self.right_rotate(z)
z.parent.color = 'black'
z.parent.parent.color = 'red'
self.left_rotate(z.parent.parent)
self.root.color = 'black'
def transplant(self, u, v):
if u.parent == self.nil:
self.root = v
elif u == u.parent.left:
u.parent.left = v
else: u.parent.right = v
v.parent = u.parent
def delete(self, z):
y = z
y_original_color = y.color
if z.left == self.nil:
x = z.right
self.transplant(z, z.right)
elif z.right == self.nil:
x = z.left
self.transplant(z, z.left)
else:
y = self.minimum(z.right)
y_original_color = y.color
x = y.right
if y.parent == z:
x.parent = y
else:
self.transplant(y, y.right)
y.right = z.right
y.right.parent = y
self.transplant(z, y)
y.left = z.left
y.left.parent = y
y.color = z.color
if y_original_color == 'black':
self.delete_fixup(x)
def delete_fixup(self, x):
while x != self.root and x.color == 'black':
if x == x.parent.left:
w = x.parent.right
if w.color == 'red':
w.color = 'black'
x.parent.color = 'red'
self.left_rotate(x.parent)
w = x.parent.right
if w.left.color == 'black' and w.right.color == 'black':
w.color = 'red'
x = x.parent
else:
if w.right.color == 'black':
w.left.color = 'black'
w.color = 'red'
self.right_rotate(w)
w = x.parent.right
w.color = x.parent.color
x.parent.color = 'black'
w.right.color = 'black'
self.left_rotate(x.parent)
x = self.root
else:
w = x.parent.left
if w.color == 'red':
w.color = 'black'
x.parent.color = 'red'
self.right_rotate(x.parent)
w = x.parent.left
if w.right.color == 'black' and w.left.color == 'black':
w.color = 'red'
x = x.parent
else:
if w.left.color == 'black':
w.right.color = 'black'
w.color = 'red'
self.left_rotate(w)
w = x.parent.left
w.color = x.parent.color
x.parent.color = 'black'
w.left.color = 'black'
self.right_rotate(x.parent)
x = self.root
x.color = 'black'
def minimum(self, x):
while x.left.left != None:
x = x.left
return x.key
def maximum(self, x):
while x.right.right != None:
x = x.right
return x.key
def search(self, x, key):
if x == None or key == x.key:
return x
if key < x.key:
return self.search(x.left, key)
else: return self.search(x.right, key)
class Node():
def __init__(self, key, color = 'red', parent = None, left = None, right = None):
self.key = key
self.color = color
self.parent = parent
self.left = left
self.right = right
def __repr__(self) -> str:
return '{|%s%s|:%s,%s}' % (self.color, self.key, self.left, self.right)
def example_usage():
rb_tree = Red_black_tree()
node_1 = Node(6) # 6
node_2 = Node(4) # / \
node_3 = Node(8) # 4 8
node_4 = Node(2) # /
rb_tree.insert(node_1) # 2
rb_tree.insert(node_2)
rb_tree.insert(node_3)
rb_tree.insert(node_4)
print('Tree text reprezentation:', rb_tree)
print('Searching for key = 4:', rb_tree.search(rb_tree.root, 4))
print('Minimum:', rb_tree.minimum(rb_tree.root))
print('Maksimum:', rb_tree.maximum(rb_tree.root))
rb_tree.delete(node_2)
print('Tree text reprezentation after removing node 2 (key=4):', rb_tree)
if __name__ == "__main__":
example_usage() # run an example on start
|
class Red_Black_Tree:
def __init__(self):
self.nil = node(0, 'black', None, None)
self.root = self.nil
def __repr__(self):
return str(self.root)
def left_rotate(self, x):
y = x.right
x.right = y.left
if y.left != self.nil:
y.left.parent = x
y.parent = x.parent
if x.parent == self.nil:
self.root = y
elif x == x.parent.left:
x.parent.left = y
else:
x.parent.right = y
x.left = x
x.parent = y
def right_rotate(self, x):
y = x.left
x.left = y.right
if y.right != self.nil:
y.right.parent = x
y.parent = x.parent
if x.parent == self.nil:
self.root = y
elif x == x.parent.right:
x.parent.right = y
else:
x.parent.left = y
x.right = x
x.parent = y
def insert(self, z):
y = self.nil
x = self.root
while x != self.nil:
y = x
if z.key < x.key:
x = x.left
else:
x = x.right
z.parent = y
if y == self.nil:
self.root = z
elif z.key < y.key or y.key == None:
y.left = z
else:
y.right = z
z.left = self.nil
z.right = self.nil
z.color = 'red'
self.insert_fixup(z)
def insert_fixup(self, z):
while z != self.root and z.parent.color == 'red':
if z.parent == z.parent.parent.left:
y = z.parent.parent.right
if y.color == 'red':
z.parent.color = 'black'
y.color = 'black'
z.parent.parent.color = 'red'
z = z.parent.parent
else:
if z == z.parent.right:
z = z.parent
self.left_rotate(z)
z.parent.color = 'black'
z.parent.parent.color = 'red'
self.right_rotate(z.parent.parent)
else:
y = z.parent.parent.left
if y.color == 'red':
z.parent.color = 'black'
y.color = 'black'
z.parent.parent.color = 'red'
z = z.parent.parent
else:
if z == z.parent.left:
z = z.parent
self.right_rotate(z)
z.parent.color = 'black'
z.parent.parent.color = 'red'
self.left_rotate(z.parent.parent)
self.root.color = 'black'
def transplant(self, u, v):
if u.parent == self.nil:
self.root = v
elif u == u.parent.left:
u.parent.left = v
else:
u.parent.right = v
v.parent = u.parent
def delete(self, z):
y = z
y_original_color = y.color
if z.left == self.nil:
x = z.right
self.transplant(z, z.right)
elif z.right == self.nil:
x = z.left
self.transplant(z, z.left)
else:
y = self.minimum(z.right)
y_original_color = y.color
x = y.right
if y.parent == z:
x.parent = y
else:
self.transplant(y, y.right)
y.right = z.right
y.right.parent = y
self.transplant(z, y)
y.left = z.left
y.left.parent = y
y.color = z.color
if y_original_color == 'black':
self.delete_fixup(x)
def delete_fixup(self, x):
while x != self.root and x.color == 'black':
if x == x.parent.left:
w = x.parent.right
if w.color == 'red':
w.color = 'black'
x.parent.color = 'red'
self.left_rotate(x.parent)
w = x.parent.right
if w.left.color == 'black' and w.right.color == 'black':
w.color = 'red'
x = x.parent
else:
if w.right.color == 'black':
w.left.color = 'black'
w.color = 'red'
self.right_rotate(w)
w = x.parent.right
w.color = x.parent.color
x.parent.color = 'black'
w.right.color = 'black'
self.left_rotate(x.parent)
x = self.root
else:
w = x.parent.left
if w.color == 'red':
w.color = 'black'
x.parent.color = 'red'
self.right_rotate(x.parent)
w = x.parent.left
if w.right.color == 'black' and w.left.color == 'black':
w.color = 'red'
x = x.parent
else:
if w.left.color == 'black':
w.right.color = 'black'
w.color = 'red'
self.left_rotate(w)
w = x.parent.left
w.color = x.parent.color
x.parent.color = 'black'
w.left.color = 'black'
self.right_rotate(x.parent)
x = self.root
x.color = 'black'
def minimum(self, x):
while x.left.left != None:
x = x.left
return x.key
def maximum(self, x):
while x.right.right != None:
x = x.right
return x.key
def search(self, x, key):
if x == None or key == x.key:
return x
if key < x.key:
return self.search(x.left, key)
else:
return self.search(x.right, key)
class Node:
def __init__(self, key, color='red', parent=None, left=None, right=None):
self.key = key
self.color = color
self.parent = parent
self.left = left
self.right = right
def __repr__(self) -> str:
return '{|%s%s|:%s,%s}' % (self.color, self.key, self.left, self.right)
def example_usage():
rb_tree = red_black_tree()
node_1 = node(6)
node_2 = node(4)
node_3 = node(8)
node_4 = node(2)
rb_tree.insert(node_1)
rb_tree.insert(node_2)
rb_tree.insert(node_3)
rb_tree.insert(node_4)
print('Tree text reprezentation:', rb_tree)
print('Searching for key = 4:', rb_tree.search(rb_tree.root, 4))
print('Minimum:', rb_tree.minimum(rb_tree.root))
print('Maksimum:', rb_tree.maximum(rb_tree.root))
rb_tree.delete(node_2)
print('Tree text reprezentation after removing node 2 (key=4):', rb_tree)
if __name__ == '__main__':
example_usage()
|
# -*- coding: utf-8 -*-
"""Top-level package for pyDarknetServer."""
__author__ = """Lionel Atty"""
__email__ = 'yoyonel@hotmail.com'
__version__ = '0.2.0'
|
"""Top-level package for pyDarknetServer."""
__author__ = 'Lionel Atty'
__email__ = 'yoyonel@hotmail.com'
__version__ = '0.2.0'
|
# -*- coding: utf-8 -*-
'''A completely generic, data-driven, configuration dialog'''
class ConfigDialog(QtGui.QDialog):
def __init__(self, parent):
QtGui.QDialog.__init__(self, parent)
# Set up the UI from designer
self.ui=UI_ConfigDialog()
self.ui.setupUi(self)
pages=[]
sections=[]
self.values={}
for sectionName, options in config.options:
# Create a page widget/layout for this section:
page=QtGui.QScrollArea()
innerpage=QtGui.QFrame()
layout=QtGui.QGridLayout()
row=-2
for optionName, definition in options:
row+=2
if definition[0]=='bool':
cb=QtGui.QCheckBox(optionName)
cb.setChecked(config.getValue(sectionName, optionName, definition[1]))
layout.addWidget(cb, row, 0, 1, 2)
self.values[sectionName+'/'+optionName]=[cb, lambda cb: cb.isChecked()]
elif definition[0]=='int':
label=QtGui.QLabel(optionName+":")
label.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter)
spin=QtGui.QSpinBox()
if definition[3] is not None:
spin.setMinimum(definition[3])
else:
spin.setMinimum(-99999)
if definition[4] is not None:
spin.setMaximum(definition[4])
else:
spin.setMaximum(99999)
spin.setValue(config.getValue(sectionName, optionName, definition[1]))
layout.addWidget(label, row, 0, 1, 1)
layout.addWidget(spin, row, 1, 1, 1)
self.values[sectionName+'/'+optionName]=[spin, lambda spin: spin.value()]
elif definition[0]=='string':
label=QtGui.QLabel(optionName+":")
label.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter)
text=QtGui.QLineEdit()
text.setText(str(config.getValue(sectionName, optionName, definition[1])))
layout.addWidget(label, row, 0, 1, 1)
layout.addWidget(text, row, 1, 1, 1)
self.values[sectionName+'/'+optionName]=[text, lambda text: str(text.text())]
elif definition[0]=='password':
label=QtGui.QLabel(optionName+":")
label.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter)
text=QtGui.QLineEdit()
text.setEchoMode(QtGui.QLineEdit.Password)
text.setText(str(config.getValue(sectionName, optionName, definition[1])))
layout.addWidget(label, row, 0, 1, 1)
layout.addWidget(text, row, 1, 1, 1)
self.values[sectionName+'/'+optionName]=[text, lambda text: str(text.text())]
help=QtGui.QLabel(definition[2])
help.setWordWrap(True)
layout.addWidget(help, row, 2, 1, 1)
separator=QtGui.QFrame()
separator.setFrameStyle(QtGui.QFrame.HLine|QtGui.QFrame.Plain)
layout.addWidget(separator, row+1, 0, 1, 3)
innerpage.setLayout(layout)
innerpage.adjustSize()
page.resize(QtCore.QSize(innerpage.width()+5, page.height()))
page.setWidget(innerpage)
pages.append(page)
sections.append(sectionName)
for page, name in zip(pages,sections) :
# Make a tab out of it
self.ui.tabs.addTab(page, name)
self.ui.tabs.setCurrentIndex(1)
self.ui.tabs.removeTab(0)
def accept(self):
for k in self.values:
sec, opt=k.split('/')
widget, l = self.values[k]
config.setValue(sec, opt, l(widget))
QtGui.QDialog.accept(self)
|
"""A completely generic, data-driven, configuration dialog"""
class Configdialog(QtGui.QDialog):
def __init__(self, parent):
QtGui.QDialog.__init__(self, parent)
self.ui = ui__config_dialog()
self.ui.setupUi(self)
pages = []
sections = []
self.values = {}
for (section_name, options) in config.options:
page = QtGui.QScrollArea()
innerpage = QtGui.QFrame()
layout = QtGui.QGridLayout()
row = -2
for (option_name, definition) in options:
row += 2
if definition[0] == 'bool':
cb = QtGui.QCheckBox(optionName)
cb.setChecked(config.getValue(sectionName, optionName, definition[1]))
layout.addWidget(cb, row, 0, 1, 2)
self.values[sectionName + '/' + optionName] = [cb, lambda cb: cb.isChecked()]
elif definition[0] == 'int':
label = QtGui.QLabel(optionName + ':')
label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
spin = QtGui.QSpinBox()
if definition[3] is not None:
spin.setMinimum(definition[3])
else:
spin.setMinimum(-99999)
if definition[4] is not None:
spin.setMaximum(definition[4])
else:
spin.setMaximum(99999)
spin.setValue(config.getValue(sectionName, optionName, definition[1]))
layout.addWidget(label, row, 0, 1, 1)
layout.addWidget(spin, row, 1, 1, 1)
self.values[sectionName + '/' + optionName] = [spin, lambda spin: spin.value()]
elif definition[0] == 'string':
label = QtGui.QLabel(optionName + ':')
label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
text = QtGui.QLineEdit()
text.setText(str(config.getValue(sectionName, optionName, definition[1])))
layout.addWidget(label, row, 0, 1, 1)
layout.addWidget(text, row, 1, 1, 1)
self.values[sectionName + '/' + optionName] = [text, lambda text: str(text.text())]
elif definition[0] == 'password':
label = QtGui.QLabel(optionName + ':')
label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
text = QtGui.QLineEdit()
text.setEchoMode(QtGui.QLineEdit.Password)
text.setText(str(config.getValue(sectionName, optionName, definition[1])))
layout.addWidget(label, row, 0, 1, 1)
layout.addWidget(text, row, 1, 1, 1)
self.values[sectionName + '/' + optionName] = [text, lambda text: str(text.text())]
help = QtGui.QLabel(definition[2])
help.setWordWrap(True)
layout.addWidget(help, row, 2, 1, 1)
separator = QtGui.QFrame()
separator.setFrameStyle(QtGui.QFrame.HLine | QtGui.QFrame.Plain)
layout.addWidget(separator, row + 1, 0, 1, 3)
innerpage.setLayout(layout)
innerpage.adjustSize()
page.resize(QtCore.QSize(innerpage.width() + 5, page.height()))
page.setWidget(innerpage)
pages.append(page)
sections.append(sectionName)
for (page, name) in zip(pages, sections):
self.ui.tabs.addTab(page, name)
self.ui.tabs.setCurrentIndex(1)
self.ui.tabs.removeTab(0)
def accept(self):
for k in self.values:
(sec, opt) = k.split('/')
(widget, l) = self.values[k]
config.setValue(sec, opt, l(widget))
QtGui.QDialog.accept(self)
|
# The XPATH to determine if the main page has fully loaded
HOME_PAGE_XPATH: str = '/html/body/center/table/tbody/tr[2]/td/center/table[1]/tbody/tr/td[3]' + \
'/table/tbody/tr/td/ul[1]/li[1]/a'
# The XPATH on the main page to the table listing the kits
KITS_XPATH: str = '/html/body/center/table/tbody/tr[2]/td/center/table[1]/tbody/tr/td[1]' + \
'/table/tbody/tr[4]/td/table/tbody/tr[4]/td/table'
|
home_page_xpath: str = '/html/body/center/table/tbody/tr[2]/td/center/table[1]/tbody/tr/td[3]' + '/table/tbody/tr/td/ul[1]/li[1]/a'
kits_xpath: str = '/html/body/center/table/tbody/tr[2]/td/center/table[1]/tbody/tr/td[1]' + '/table/tbody/tr[4]/td/table/tbody/tr[4]/td/table'
|
"""
09: See my workflow as a graph
-------------------------------
"""
|
"""
09: See my workflow as a graph
-------------------------------
"""
|
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 14 14:43:55 2022
@author: D.Albert-Weiss
"""
spec_win1D = [
('win', int32),
]
|
"""
Created on Mon Mar 14 14:43:55 2022
@author: D.Albert-Weiss
"""
spec_win1_d = [('win', int32)]
|
def test_parameter_exclusion_empty(api_client, api_prefix):
response = api_client.get(f"{api_prefix}/parameters/1/exclusions/")
assert response.status_code == 200
json_dict = response.json
expected = {
"message": "exclusions for parameter 1",
"parameter": {"excluded": [], "excluded_by": [], "name": "Colour", "uid": 1},
"parameter_url": f"{api_prefix}/parameters/1",
"parameter_exclusion_url": f"{api_prefix}/parameters/1/exclusions/",
}
assert json_dict == expected
def test_parameter_exclusion_non_empty(api_client, api_prefix):
request_data = {
"excluded": [
3,
],
}
response = api_client.post(
f"{api_prefix}/parameters/1/exclusions/", json=request_data
)
assert response.status_code == 201
response = api_client.get(f"{api_prefix}/parameters/1/exclusions/")
assert response.status_code == 200
json_dict = response.json
expected = {
"message": "exclusions for parameter 1",
"parameter": {
"name": "Colour",
"uid": 1,
"excluded": [{"name": "Speed", "uid": 3}],
"excluded_by": [],
},
"parameter_url": f"{api_prefix}/parameters/1",
"parameter_exclusion_url": f"{api_prefix}/parameters/1/exclusions/",
}
assert json_dict == expected
def test_parameter_exclusion_post(api_client, api_prefix):
request_data = {
"excluded": [3, 4],
}
response = api_client.post(
f"{api_prefix}/parameters/1/exclusions/", json=request_data
)
assert response.status_code == 201
json_dict = response.json
expected = {
"message": "parameter exclusion created",
"parameter": {
"uid": 1,
"name": "Colour",
"excluded": [
{"name": "Speed", "uid": 3},
{"name": "Music", "uid": 4},
],
"excluded_by": [],
},
"parameter_url": "/tconfig/api/v1/parameters/1",
}
assert json_dict == expected
|
def test_parameter_exclusion_empty(api_client, api_prefix):
response = api_client.get(f'{api_prefix}/parameters/1/exclusions/')
assert response.status_code == 200
json_dict = response.json
expected = {'message': 'exclusions for parameter 1', 'parameter': {'excluded': [], 'excluded_by': [], 'name': 'Colour', 'uid': 1}, 'parameter_url': f'{api_prefix}/parameters/1', 'parameter_exclusion_url': f'{api_prefix}/parameters/1/exclusions/'}
assert json_dict == expected
def test_parameter_exclusion_non_empty(api_client, api_prefix):
request_data = {'excluded': [3]}
response = api_client.post(f'{api_prefix}/parameters/1/exclusions/', json=request_data)
assert response.status_code == 201
response = api_client.get(f'{api_prefix}/parameters/1/exclusions/')
assert response.status_code == 200
json_dict = response.json
expected = {'message': 'exclusions for parameter 1', 'parameter': {'name': 'Colour', 'uid': 1, 'excluded': [{'name': 'Speed', 'uid': 3}], 'excluded_by': []}, 'parameter_url': f'{api_prefix}/parameters/1', 'parameter_exclusion_url': f'{api_prefix}/parameters/1/exclusions/'}
assert json_dict == expected
def test_parameter_exclusion_post(api_client, api_prefix):
request_data = {'excluded': [3, 4]}
response = api_client.post(f'{api_prefix}/parameters/1/exclusions/', json=request_data)
assert response.status_code == 201
json_dict = response.json
expected = {'message': 'parameter exclusion created', 'parameter': {'uid': 1, 'name': 'Colour', 'excluded': [{'name': 'Speed', 'uid': 3}, {'name': 'Music', 'uid': 4}], 'excluded_by': []}, 'parameter_url': '/tconfig/api/v1/parameters/1'}
assert json_dict == expected
|
g = int(input())
l = list(map(int,input().split()))
mi = min(l)
ma = max(l)
y=0
for i in l:
if i == ma:
break
y+=1
l.remove(ma)
l.insert(0,ma)
x = l[-1::-1]
for j in x:
if j==mi:
break
y+=1
print(y)
|
g = int(input())
l = list(map(int, input().split()))
mi = min(l)
ma = max(l)
y = 0
for i in l:
if i == ma:
break
y += 1
l.remove(ma)
l.insert(0, ma)
x = l[-1::-1]
for j in x:
if j == mi:
break
y += 1
print(y)
|
def vsota_stevk(n):
s = str(n)
vsota = 0
for x in s:
vsota += int(x)
return vsota
def euler56():
najvecja_vsota = 0
for a in range(1,100):
for b in range(1,100):
st = a ** b
s = vsota_stevk(st)
if s > najvecja_vsota:
najvecja_vsota = s
return najvecja_vsota
euler56()
|
def vsota_stevk(n):
s = str(n)
vsota = 0
for x in s:
vsota += int(x)
return vsota
def euler56():
najvecja_vsota = 0
for a in range(1, 100):
for b in range(1, 100):
st = a ** b
s = vsota_stevk(st)
if s > najvecja_vsota:
najvecja_vsota = s
return najvecja_vsota
euler56()
|
def newArr(arr):
"""
MapReduce: O(n^2)
1. Map: construct the Map with Key is each element and Value is the array
2. Reduce: product all element of Value except the key
"""
result = []
hashmap = {}
for i in arr:
hashmap[i] = arr
for key, value in hashmap.items():
product = 1
for v in value:
if (v != key):
product *=v
result.append(product)
return result
def optimizedNewArr(arr):
"""
Ref: https://www.geeksforgeeks.org/a-product-array-puzzle/ O(n)
1) Construct a temporary array left[] such that left[i] contains product of all elements on left of arr[i] excluding arr[i].
2) Construct another temporary array right[] such that right[i] contains product of all elements on on right of arr[i] excluding arr[i].
3) To get prod[], multiply left[] and right[].
"""
result = []
temp = 1
for i in range(len(arr)):
result.append(temp)
temp *= arr[i]
temp = 1
j = len(arr) - 1
while (j >= 0):
result[j] *= temp
temp *= arr[j]
j -= 1
return result
|
def new_arr(arr):
"""
MapReduce: O(n^2)
1. Map: construct the Map with Key is each element and Value is the array
2. Reduce: product all element of Value except the key
"""
result = []
hashmap = {}
for i in arr:
hashmap[i] = arr
for (key, value) in hashmap.items():
product = 1
for v in value:
if v != key:
product *= v
result.append(product)
return result
def optimized_new_arr(arr):
"""
Ref: https://www.geeksforgeeks.org/a-product-array-puzzle/ O(n)
1) Construct a temporary array left[] such that left[i] contains product of all elements on left of arr[i] excluding arr[i].
2) Construct another temporary array right[] such that right[i] contains product of all elements on on right of arr[i] excluding arr[i].
3) To get prod[], multiply left[] and right[].
"""
result = []
temp = 1
for i in range(len(arr)):
result.append(temp)
temp *= arr[i]
temp = 1
j = len(arr) - 1
while j >= 0:
result[j] *= temp
temp *= arr[j]
j -= 1
return result
|
# this one needs to be a multiple of 8
bitsString = "1111111101111111001111110001111100001111000001110000001100000001"
# store here the hex values
bhex = list()
# check the size of bitsString
if len(bitsString) % 8 != 0 : print("Invalid string len provided")
# split, convert to 8 and append to a string (make this more pythonable)
for i in range(0, len(bitsString), 8):
bhex.append(hex(int(bitsString[i:i+8], 2)))
print(bhex)
# move to bytes
for i in range(len(bhex)):
c = bytearray(bhex[i],encoding='utf8')
print(c, end='\t')
print(bin(int(bhex[i], 16))[2:].zfill(8))
|
bits_string = '1111111101111111001111110001111100001111000001110000001100000001'
bhex = list()
if len(bitsString) % 8 != 0:
print('Invalid string len provided')
for i in range(0, len(bitsString), 8):
bhex.append(hex(int(bitsString[i:i + 8], 2)))
print(bhex)
for i in range(len(bhex)):
c = bytearray(bhex[i], encoding='utf8')
print(c, end='\t')
print(bin(int(bhex[i], 16))[2:].zfill(8))
|
def gcd(a, b):
while b: a, b = b, a % b
return a
def isPrimeMR(n):
d = n - 1
d = d // (d & -d)
L = [2]
for a in L:
t = d
y = pow(a, t, n)
if y == 1: continue
while y != n - 1:
y = (y * y) % n
if y == 1 or t == n - 1: return 0
t <<= 1
return 1
def findFactorRho(n):
m = 1 << n.bit_length() // 8
for c in range(1, 99):
f = lambda x: (x * x + c) % n
y, r, q, g = 2, 1, 1, 1
while g == 1:
x = y
for _ in range(r):
y = f(y)
k = 0
while k < r and g == 1:
ys = y
for _ in range(min(m, r - k)):
y = f(y)
q = q * abs(x - y) % n
g = gcd(q, n)
k += m
r <<= 1
if g == n:
g = 1
while g == 1:
ys = f(ys)
g = gcd(abs(x - ys), n)
if g < n:
if isPrimeMR(g): return g
elif isPrimeMR(n // g): return n // g
return findFactorRho(g)
def primeFactor(n):
i = 2
ret = {}
rhoFlg = 0
while i*i <= n:
k = 0
while n % i == 0:
n //= i
k += 1
if k: ret[i] = k
i += 1 + i % 2
if i == 101 and n >= 2 ** 20:
while n > 1:
if isPrimeMR(n):
ret[n], n = 1, 1
else:
rhoFlg = 1
j = findFactorRho(n)
k = 0
while n % j == 0:
n //= j
k += 1
ret[j] = k
if n > 1: ret[n] = 1
if rhoFlg: ret = {x: ret[x] for x in sorted(ret)}
return ret
if __name__ == "__main__":
print(primeFactor(1234567891012354))
|
def gcd(a, b):
while b:
(a, b) = (b, a % b)
return a
def is_prime_mr(n):
d = n - 1
d = d // (d & -d)
l = [2]
for a in L:
t = d
y = pow(a, t, n)
if y == 1:
continue
while y != n - 1:
y = y * y % n
if y == 1 or t == n - 1:
return 0
t <<= 1
return 1
def find_factor_rho(n):
m = 1 << n.bit_length() // 8
for c in range(1, 99):
f = lambda x: (x * x + c) % n
(y, r, q, g) = (2, 1, 1, 1)
while g == 1:
x = y
for _ in range(r):
y = f(y)
k = 0
while k < r and g == 1:
ys = y
for _ in range(min(m, r - k)):
y = f(y)
q = q * abs(x - y) % n
g = gcd(q, n)
k += m
r <<= 1
if g == n:
g = 1
while g == 1:
ys = f(ys)
g = gcd(abs(x - ys), n)
if g < n:
if is_prime_mr(g):
return g
elif is_prime_mr(n // g):
return n // g
return find_factor_rho(g)
def prime_factor(n):
i = 2
ret = {}
rho_flg = 0
while i * i <= n:
k = 0
while n % i == 0:
n //= i
k += 1
if k:
ret[i] = k
i += 1 + i % 2
if i == 101 and n >= 2 ** 20:
while n > 1:
if is_prime_mr(n):
(ret[n], n) = (1, 1)
else:
rho_flg = 1
j = find_factor_rho(n)
k = 0
while n % j == 0:
n //= j
k += 1
ret[j] = k
if n > 1:
ret[n] = 1
if rhoFlg:
ret = {x: ret[x] for x in sorted(ret)}
return ret
if __name__ == '__main__':
print(prime_factor(1234567891012354))
|
x=int(input())
for i in range(0,x):
a,b=map(int,input().split())
print(a+b)
|
x = int(input())
for i in range(0, x):
(a, b) = map(int, input().split())
print(a + b)
|
suppressions = [
# This one cannot be covered by any Python language test because there is
# no code pathway to it. But it is part of the C API, so must not be
# excised from the code.
[ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ],
# PyArray_Std trivially forwards to and appears to be superceded by
# __New_PyArray_Std, which is exercised by the test framework.
[ r".*/multiarray/calculation\.", "PyArray_Std" ],
# PyCapsule_Check is declared in a header, and used in
# multiarray/ctors.c. So it isn't really untested.
[ r".*/multiarray/common\.", "PyCapsule_Check" ],
]
|
suppressions = [['.*/multiarray/mapping\\.', 'PyArray_MapIterReset'], ['.*/multiarray/calculation\\.', 'PyArray_Std'], ['.*/multiarray/common\\.', 'PyCapsule_Check']]
|
# _*_coding:utf-8_*_
class Solution:
def get_maybe(self, index, pushV):
maybe = [None]
j = index - 1
while j >= 0:
if None is not pushV[j]:
maybe[0] = j
break
j -= 1
j = index + 1
while j < len(pushV):
if None is not pushV[j]:
maybe.append(j)
j += 1
return maybe
def IsPopOrder(self, pushV, popV):
if None is pushV or None is popV:
return False
if len(pushV) != len(popV) or len(pushV) <= 0 or len(popV) <= 0:
return False
val = popV[0]
index = -1
for i, value in enumerate(pushV):
if val == value:
index = i
break
if -1 == index:
return False
pushV[index] = None
maybe = self.get_maybe(index, pushV)
for i in range(1, len(popV)):
val = popV[i]
for maybeValue in maybe:
if None is not maybeValue and maybeValue >= 0 and maybeValue < len(pushV) and val == pushV[maybeValue]:
index = maybeValue
pushV[index] = None
maybe = self.get_maybe(index, pushV)
break
else:
return False
return True
s = Solution()
case_list = [
([1], [2]),
([1,2,3,4,5], [4,3,5,1,2]),
([1,2,3,4,5],[3,5,4,2,1]),
([1,2,3,4,5], [4,5,3,2,1]),
([1,2,3,4,], [4,5,3,2,1]),
(None, [4,5,3,2,1])
]
for case in case_list:
print(s.IsPopOrder(case[0], case[1]))
|
class Solution:
def get_maybe(self, index, pushV):
maybe = [None]
j = index - 1
while j >= 0:
if None is not pushV[j]:
maybe[0] = j
break
j -= 1
j = index + 1
while j < len(pushV):
if None is not pushV[j]:
maybe.append(j)
j += 1
return maybe
def is_pop_order(self, pushV, popV):
if None is pushV or None is popV:
return False
if len(pushV) != len(popV) or len(pushV) <= 0 or len(popV) <= 0:
return False
val = popV[0]
index = -1
for (i, value) in enumerate(pushV):
if val == value:
index = i
break
if -1 == index:
return False
pushV[index] = None
maybe = self.get_maybe(index, pushV)
for i in range(1, len(popV)):
val = popV[i]
for maybe_value in maybe:
if None is not maybeValue and maybeValue >= 0 and (maybeValue < len(pushV)) and (val == pushV[maybeValue]):
index = maybeValue
pushV[index] = None
maybe = self.get_maybe(index, pushV)
break
else:
return False
return True
s = solution()
case_list = [([1], [2]), ([1, 2, 3, 4, 5], [4, 3, 5, 1, 2]), ([1, 2, 3, 4, 5], [3, 5, 4, 2, 1]), ([1, 2, 3, 4, 5], [4, 5, 3, 2, 1]), ([1, 2, 3, 4], [4, 5, 3, 2, 1]), (None, [4, 5, 3, 2, 1])]
for case in case_list:
print(s.IsPopOrder(case[0], case[1]))
|
# 2020.07.09
# Problem Statement:
# https://leetcode.com/problems/longest-palindromic-substring/
class Solution:
def longestPalindrome(self, s: str) -> str:
# discuss corner cases
if len(s) == 0:
return ""
elif len(s) == 1:
return s
elif len(s) == 2:
if s[0] == s[1]:
return s
else:
return s[0]
# declare current best result and current palindromic substring
current_longest = ''
current_longest = s[0]
current_explored = ''
current_explored = s[0]
center_index = 0
# if there exists substrings with repeat chars, eg: "abbbc"
# need to know the number of repeat chars
# if even, center should be 2 chars, palindromic substring shoule be even
# otherwise center should be 1 char, palindtomic substring should be odd
# initialize count for repeating substrings
count_left = 0
count_right = 0
count_continuous = 1
# each element can be the center of the substring
# first and last excluded, since current_longest is already initialized as a single-element string
for index in range(1, len(s)-1):
count_left, count_right, count_continuous = 0, 0, 1
center_index = index
# if not continuously reapeating
if s[center_index] != s[center_index-1] and s[center_index] != s[center_index+1]:
for i in range(0, min(index+1, len(s)-index)) :
if s[center_index-i] == s[center_index+i]:
current_explored = s[center_index-i: center_index+i+1]
else: # not a palindromic string
break
# continuously repeating
else:
for left_index in range(1, index+1) :
if s[center_index] == s[center_index-left_index]:
count_left = count_left + 1
else:
break
for right_index in range(1, len(s)-index):
if s[center_index] == s[center_index+right_index]:
count_right = count_right + 1
else:
break
count_continuous = count_continuous + count_left + count_right
# even
if count_continuous % 2 == 0:
current_explored = count_continuous * s[center_index]
for j in range(0, min(index, len(s)-index)):
if s[center_index-1-j] == s[center_index+j]:
current_explored = s[center_index-1-j: center_index+j+1]
else:
break
# odd
else:
for k in range(0, min(index+1, len(s)-index)) :
if s[center_index-k] == s[center_index+k]:
current_explored = s[center_index-k: center_index+k+1]
else:
break
# update if current result is better
if len(current_explored) >= len(current_longest):
current_longest = current_explored
return current_longest
|
class Solution:
def longest_palindrome(self, s: str) -> str:
if len(s) == 0:
return ''
elif len(s) == 1:
return s
elif len(s) == 2:
if s[0] == s[1]:
return s
else:
return s[0]
current_longest = ''
current_longest = s[0]
current_explored = ''
current_explored = s[0]
center_index = 0
count_left = 0
count_right = 0
count_continuous = 1
for index in range(1, len(s) - 1):
(count_left, count_right, count_continuous) = (0, 0, 1)
center_index = index
if s[center_index] != s[center_index - 1] and s[center_index] != s[center_index + 1]:
for i in range(0, min(index + 1, len(s) - index)):
if s[center_index - i] == s[center_index + i]:
current_explored = s[center_index - i:center_index + i + 1]
else:
break
else:
for left_index in range(1, index + 1):
if s[center_index] == s[center_index - left_index]:
count_left = count_left + 1
else:
break
for right_index in range(1, len(s) - index):
if s[center_index] == s[center_index + right_index]:
count_right = count_right + 1
else:
break
count_continuous = count_continuous + count_left + count_right
if count_continuous % 2 == 0:
current_explored = count_continuous * s[center_index]
for j in range(0, min(index, len(s) - index)):
if s[center_index - 1 - j] == s[center_index + j]:
current_explored = s[center_index - 1 - j:center_index + j + 1]
else:
break
else:
for k in range(0, min(index + 1, len(s) - index)):
if s[center_index - k] == s[center_index + k]:
current_explored = s[center_index - k:center_index + k + 1]
else:
break
if len(current_explored) >= len(current_longest):
current_longest = current_explored
return current_longest
|
"""
Data model module.
In this module the data types used in CGnal framework are defined.
"""
|
"""
Data model module.
In this module the data types used in CGnal framework are defined.
"""
|
# -*- coding: utf-8 -*-
"""Top-level package for Tractography Meta-Pipeline Command Line Tool (TRAMPOLINO)."""
__author__ = """Matteo Mancini"""
__email__ = 'ingmatteomancini@gmail.com'
__version__ = '0.1.9'
|
"""Top-level package for Tractography Meta-Pipeline Command Line Tool (TRAMPOLINO)."""
__author__ = 'Matteo Mancini'
__email__ = 'ingmatteomancini@gmail.com'
__version__ = '0.1.9'
|
class Solution:
@staticmethod
def naive(nums,target):
l,r = 0,len(nums)-1
while l<=r:
m = (l+r)//2
if nums[m]==target:
return m
if nums[l]<=nums[m]:
if target>=nums[l] and target<nums[m]:
r=m-1
else:
l=m+1
else:
if target<=nums[r] and target>nums[m]:
l=m+1
else:
r=m-1
return -1
|
class Solution:
@staticmethod
def naive(nums, target):
(l, r) = (0, len(nums) - 1)
while l <= r:
m = (l + r) // 2
if nums[m] == target:
return m
if nums[l] <= nums[m]:
if target >= nums[l] and target < nums[m]:
r = m - 1
else:
l = m + 1
elif target <= nums[r] and target > nums[m]:
l = m + 1
else:
r = m - 1
return -1
|
step(
"""
create unique index unq_image_tag_image_id_tag_id
on image_tag (image_id, tag_id)
""",
"""
drop index unq_image_tag_image_id_tag_id
"""
)
|
step('\n create unique index unq_image_tag_image_id_tag_id\n on image_tag (image_id, tag_id)\n ', '\n drop index unq_image_tag_image_id_tag_id\n ')
|
consumer_key = 'gdLsE3urZ6HqjE2RjiwaFBwag'
consumer_secret = 'rubc1WvJoYOnsBoUMXXV660MUOhw685uTFjqnYmrRWdqoq6Y48'
access_token = '846813944186650627-CpBzbP1i8ag3pREHkd6YcGQeMHbaLOx'
access_secret = 'rX2ikxxtI4zplBp9kbEEpibWVKyCwKJmvuxTiKxFgeJKA'
|
consumer_key = 'gdLsE3urZ6HqjE2RjiwaFBwag'
consumer_secret = 'rubc1WvJoYOnsBoUMXXV660MUOhw685uTFjqnYmrRWdqoq6Y48'
access_token = '846813944186650627-CpBzbP1i8ag3pREHkd6YcGQeMHbaLOx'
access_secret = 'rX2ikxxtI4zplBp9kbEEpibWVKyCwKJmvuxTiKxFgeJKA'
|
"""
The Notebook module.
"""
class Notebook:
"""
This notebook does...
"""
def run(self):
"""
Your notebook code goes here.
"""
notebook = Notebook()
notebook.run()
|
"""
The Notebook module.
"""
class Notebook:
"""
This notebook does...
"""
def run(self):
"""
Your notebook code goes here.
"""
notebook = notebook()
notebook.run()
|
save_dir = './logs'
# miniImageNet_path = '../../semifew_data/miniImagenetFullSize'
miniImageNet_path = '/home/ojas/projects/unsupervised-meta-learning/data/untarred/miniImagenetFullSize'
ISIC_path = "../../semifew_data/ISIC"
ChestX_path = "../../semifew_data/chestX"
CropDisease_path = "../../semifew_data/plant-disease"
EuroSAT_path = "/home/ojas/projects/unsupervised-meta-learning/data/untarred/EuroSat"
|
save_dir = './logs'
mini_image_net_path = '/home/ojas/projects/unsupervised-meta-learning/data/untarred/miniImagenetFullSize'
isic_path = '../../semifew_data/ISIC'
chest_x_path = '../../semifew_data/chestX'
crop_disease_path = '../../semifew_data/plant-disease'
euro_sat_path = '/home/ojas/projects/unsupervised-meta-learning/data/untarred/EuroSat'
|
class Result(object):
'''
Simple wrapper object to contain result of single iteration MPI computation
'''
def __init__(self, rank, idx):
self.rank = rank
self.idx = idx
self.result = None
def __repr__(self):
return "rank: %d idx: %s result: %s" % (self.rank, self.idx, self.result)
def __eq__(self, other):
return self.result == other.result
def __ne__(self, other):
return self.result != other.result
def __hash__(self):
return hash(self.result)
|
class Result(object):
"""
Simple wrapper object to contain result of single iteration MPI computation
"""
def __init__(self, rank, idx):
self.rank = rank
self.idx = idx
self.result = None
def __repr__(self):
return 'rank: %d idx: %s result: %s' % (self.rank, self.idx, self.result)
def __eq__(self, other):
return self.result == other.result
def __ne__(self, other):
return self.result != other.result
def __hash__(self):
return hash(self.result)
|
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ------------------------------------------------------------------
# GA Details
GA_ACCOUNT_ID = "" # requierd for DI only
GA_PROPERTY_ID = "" # required for both DI and MP
GA_DATASET_ID = "" # required for DI only
GA_IMPORT_METHOD = "di" # "di" - Data Import or "mp" - Measurement Protocol
# GA measurement protocol hit details. Add any additional fields which are
# the same for all hits here.
GA_MP_STANDARD_HIT_DETAILS = {
# mandatory fields below. Do not remove.
"v": 1, # MP API version
"tid": GA_PROPERTY_ID, # ga property id - same as above
"t": "", # hit type
# optional fields below:
"ni": 1, # non interaction hit: 1 or 0,
"ec": "", # event category
"ea": "", # event action
"el": "", # event label
"ds": "", # data source
"ua": "modem", # user agent override
}
# BigQuery Query Details - BQML query or normal BQ Query possible
# Ensure that the BQ result headers resemble the data import schema in SELECT
# E.g. If data import schema looks like - ga:dimension32, ga:dimension1, etc.
# BQ result headers should like SELECT X AS ga_dimension32, Y AS ga_dimension1
BQML_PREDICT_QUERY = """
"""
# -------------------------------------------------------------------
# Options for logging & error monitoring
# LOGGING: Create BQ Table for logs with schema as follows -
# time TIMESTAMP, status STRING, error ERROR
ENABLE_BQ_LOGGING = False
# ERROR MONITORING: Sign up for the free Sendgrid API.
ENABLE_SENDGRID_EMAIL_REPORTING = False
# (OPTIONAL) Workflow Logging - BQ details, if enabled
GCP_PROJECT_ID = ""
BQ_DATASET_NAME = ""
BQ_TABLE_NAME = ""
# (OPTIONAL) Email Reporting - Sendgrid details, if enabled
SENDGRID_API_KEY = ""
TO_EMAIL = ""
# -------------------------------------------------------------------
# (OPTIONAL) Email Reporting - Additional Parameters
FROM_EMAIL = "workflow@example.com"
SUBJECT = "FAILED: Audience Upload to GA"
HTML_CONTENT = """
<p>
Hi WorkflowUser, <br>
Your BQML Custom Audience Upload has failed- <br>
Time: {0} UTC <br>
Reason: {1}
</p>
"""
|
ga_account_id = ''
ga_property_id = ''
ga_dataset_id = ''
ga_import_method = 'di'
ga_mp_standard_hit_details = {'v': 1, 'tid': GA_PROPERTY_ID, 't': '', 'ni': 1, 'ec': '', 'ea': '', 'el': '', 'ds': '', 'ua': 'modem'}
bqml_predict_query = '\n '
enable_bq_logging = False
enable_sendgrid_email_reporting = False
gcp_project_id = ''
bq_dataset_name = ''
bq_table_name = ''
sendgrid_api_key = ''
to_email = ''
from_email = 'workflow@example.com'
subject = 'FAILED: Audience Upload to GA'
html_content = '\n <p>\n Hi WorkflowUser, <br>\n Your BQML Custom Audience Upload has failed- <br>\n Time: {0} UTC <br>\n Reason: {1}\n </p>\n '
|
option='y'
while option=='y':
print("Enter the number whose factorial to find")
num=int(input())
fac=1
while(num!=1):
fac=fac*num
num=num-1
print("Factorial is "+str(fac))
print("Do you want to continue?(y/n)")
option=input()
print('Thank you for using this programme')
|
option = 'y'
while option == 'y':
print('Enter the number whose factorial to find')
num = int(input())
fac = 1
while num != 1:
fac = fac * num
num = num - 1
print('Factorial is ' + str(fac))
print('Do you want to continue?(y/n)')
option = input()
print('Thank you for using this programme')
|
def poly(a, x):
val = 0
for ai in reversed(a):
val *= x
val += ai
return val
def diff(a):
return [a[i + 1] * (i + 1) for i in range(len(a) - 1)]
def divroot(a, x0):
b, a[-1] = a[-1], 0
for i in reversed(range(len(a) - 1)):
a[i], b = a[i + 1] * x0 + b, a[i]
a.pop()
return a
|
def poly(a, x):
val = 0
for ai in reversed(a):
val *= x
val += ai
return val
def diff(a):
return [a[i + 1] * (i + 1) for i in range(len(a) - 1)]
def divroot(a, x0):
(b, a[-1]) = (a[-1], 0)
for i in reversed(range(len(a) - 1)):
(a[i], b) = (a[i + 1] * x0 + b, a[i])
a.pop()
return a
|
tickers = [
'aapl',
'tsla',
]
|
tickers = ['aapl', 'tsla']
|
LAMBDA_232 = 4.934E-11#Amelin and Zaitsev, 2002.
# LAMBDA_232 = 4.9475E-11 #old value, used in isoplot
ERR_LAMBDA_232 = 0.015E-11#Amelin and Zaitsev, 2002.
LAMBDA_235 = 9.8485E-10
#ERR_LAMBDA_235 =
LAMBDA_238 = 1.55125E-10
#ERR_LAMBDA_238 =
U238_U235 = 137.817 #https://doi.org/10.1016/j.gca.2018.06.014
# U238_U235 = 137.88 #old value, used in isoplot
ERR_U238_U235 = 0.031 ##https://doi.org/10.1016/j.gca.2018.06.014
lambdas = [LAMBDA_238, LAMBDA_235, LAMBDA_232]
isotope_ratios = ["U238_Pb206", "U235_Pb207", "Th232_Pb208", "Pb206_Pb207"]
minerals = ["zircon", "baddeleyite", "perovskite", "monazite", "apatite"]
EarthAge = 4600
sqrt2pi = 2.506628274631
listColumnNames = ['Th232/Pb208', 'err.Th232/Pb208',
'206Pb/207Pb', 'err.206Pb/207Pb',
'235U/207Pb', 'err.235U/207Pb',
'238U/206Pb', 'err.238U/206Pb',
'corr.',
'Age_232Th/208Pb', 'err.Age_232Th/208Pb',
'Age_206Pb/207Pb', 'err.Age_206Pb/207Pb',
'Age_238U/206Pb', 'err.Age_238U/206Pb',
'Age_235U/207Pb', 'err.Age_235U/207Pb',
'%disc.67-86', '%disc.86-57', 'is grain good?']
|
lambda_232 = 4.934e-11
err_lambda_232 = 1.5e-13
lambda_235 = 9.8485e-10
lambda_238 = 1.55125e-10
u238_u235 = 137.817
err_u238_u235 = 0.031
lambdas = [LAMBDA_238, LAMBDA_235, LAMBDA_232]
isotope_ratios = ['U238_Pb206', 'U235_Pb207', 'Th232_Pb208', 'Pb206_Pb207']
minerals = ['zircon', 'baddeleyite', 'perovskite', 'monazite', 'apatite']
earth_age = 4600
sqrt2pi = 2.506628274631
list_column_names = ['Th232/Pb208', 'err.Th232/Pb208', '206Pb/207Pb', 'err.206Pb/207Pb', '235U/207Pb', 'err.235U/207Pb', '238U/206Pb', 'err.238U/206Pb', 'corr.', 'Age_232Th/208Pb', 'err.Age_232Th/208Pb', 'Age_206Pb/207Pb', 'err.Age_206Pb/207Pb', 'Age_238U/206Pb', 'err.Age_238U/206Pb', 'Age_235U/207Pb', 'err.Age_235U/207Pb', '%disc.67-86', '%disc.86-57', 'is grain good?']
|
# Bar chart
# a graph that represents the category of data with rectangular bars with lengths and heights that are proportional
# to the values which they represent.
# Can be vertical or horizontal. Can also be grouped.
# matplotlib
fig, ax = plt.subplots(1, figsize=(24,14))
plt.bar(wrestling_count.index, wrestling_count.ID, width=0.9, color='xkcd:plum', edgecolor='ivory', linewidth=0, hatch='-')
plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode='anchor')
plt.title('\nHUNGARIAN WRESTLERS\n', fontsize=55, loc='left')
ax.tick_params(axis='x', size=8, labelsize=26)
ax.tick_params(axis='y', size=8, labelsize=26)
fig.show()
# plotly of the above
fig = px.bar(
wrestling_count,
x='Games',
y='ID',
labels={'index':'Games'},
title='HUNGARIAN WRESTLERS',
text="ID",
color="ID",
template = "plotly_dark",
)
fig.update_traces(textfont_size=12, textangle=0, textposition="outside", cliponaxis=False)
fig.show()
# horizontal bars
y = np.array(winter_games_gold_fs['Games'])
x = np.array(winter_games_gold_fs['Age'])
fig, ax = plt.subplots(1, figsize=(24,15))
ax.barh(y, x, color='xkcd:darkblue', edgecolor='ivory', linewidth=0, hatch='-')
ax.set_yticks(y, labels=winter_games_gold_fs['Games'], fontsize=20)
ax.invert_yaxis()
ax.set_xlabel('Age', fontsize=35)
ax.set_title("\nFREESTYLE SKIER'S AGES -\nGOLD MEDALISTS\n", fontsize=44, loc='left')
ax.tick_params(axis='x', labelsize=30)
ax.tick_params(axis='y', labelsize=30)
plt.show()
# plotly of the above
fig = px.bar(
winter_games_gold_fs,
x='Age',
y='Games',
title="FREESTYLE SKIER'S AGES - GOLD MEDALISTS",
text="Age",
color="Age",
color_continuous_scale='Bluered_r',
template = "plotly_dark",
orientation="h"
)
fig.update_traces(textfont_size=12, textangle=0, textposition="inside", cliponaxis=False)
fig.show()
# grouped bars
fig, ax = plt.subplots(figsize = (30,20))
width = 0.4
labels = gymnists_fn.Year.unique()
label_locations = np.arange(len(gymnists_fn.Games.unique()))
y_m = np.array(gymnists_fn_m.ID)
y_w = np.array(gymnists_fn_w.ID)
semi_bar_m = ax.bar(label_locations-width/2, y_m, width, label="M", color='xkcd:brown')
semi_bar_w = ax.bar(label_locations+width/2, y_w, width, label="F", color='purple')
ax.set_ylabel('Athlete Count', fontsize=30)
ax.set_title('\nFRENCH GYMNISTS FROM 1952 \n', fontsize=46, loc='left')
ax.set_xticks(label_locations, labels, fontsize=30)
ax.tick_params(axis='y', labelsize=26)
ax.legend(prop={'size': 36}, shadow=True)
ax.bar_label(semi_bar_m, padding=3, fontsize=24)
ax.bar_label(semi_bar_w, padding=3, fontsize=24)
plt.show()
# plotly of the above
# done with graph objects
fig = go.Figure()
fig.add_trace(go.Bar(
x=labels,
y= y_m,
name='Male',
marker_color='saddlebrown'
))
fig.add_trace(go.Bar(
x=labels,
y=y_w,
name='Female',
marker_color='lightsalmon'
))
# Here we modify the tickangle of the xaxis, resulting in rotated labels.
fig.update_layout(barmode='group', xaxis_tickangle=-45, font=dict(size=18), title="FRENCH GYMNISTS FROM 1952")
fig.show()
|
(fig, ax) = plt.subplots(1, figsize=(24, 14))
plt.bar(wrestling_count.index, wrestling_count.ID, width=0.9, color='xkcd:plum', edgecolor='ivory', linewidth=0, hatch='-')
plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode='anchor')
plt.title('\nHUNGARIAN WRESTLERS\n', fontsize=55, loc='left')
ax.tick_params(axis='x', size=8, labelsize=26)
ax.tick_params(axis='y', size=8, labelsize=26)
fig.show()
fig = px.bar(wrestling_count, x='Games', y='ID', labels={'index': 'Games'}, title='HUNGARIAN WRESTLERS', text='ID', color='ID', template='plotly_dark')
fig.update_traces(textfont_size=12, textangle=0, textposition='outside', cliponaxis=False)
fig.show()
y = np.array(winter_games_gold_fs['Games'])
x = np.array(winter_games_gold_fs['Age'])
(fig, ax) = plt.subplots(1, figsize=(24, 15))
ax.barh(y, x, color='xkcd:darkblue', edgecolor='ivory', linewidth=0, hatch='-')
ax.set_yticks(y, labels=winter_games_gold_fs['Games'], fontsize=20)
ax.invert_yaxis()
ax.set_xlabel('Age', fontsize=35)
ax.set_title("\nFREESTYLE SKIER'S AGES -\nGOLD MEDALISTS\n", fontsize=44, loc='left')
ax.tick_params(axis='x', labelsize=30)
ax.tick_params(axis='y', labelsize=30)
plt.show()
fig = px.bar(winter_games_gold_fs, x='Age', y='Games', title="FREESTYLE SKIER'S AGES - GOLD MEDALISTS", text='Age', color='Age', color_continuous_scale='Bluered_r', template='plotly_dark', orientation='h')
fig.update_traces(textfont_size=12, textangle=0, textposition='inside', cliponaxis=False)
fig.show()
(fig, ax) = plt.subplots(figsize=(30, 20))
width = 0.4
labels = gymnists_fn.Year.unique()
label_locations = np.arange(len(gymnists_fn.Games.unique()))
y_m = np.array(gymnists_fn_m.ID)
y_w = np.array(gymnists_fn_w.ID)
semi_bar_m = ax.bar(label_locations - width / 2, y_m, width, label='M', color='xkcd:brown')
semi_bar_w = ax.bar(label_locations + width / 2, y_w, width, label='F', color='purple')
ax.set_ylabel('Athlete Count', fontsize=30)
ax.set_title('\nFRENCH GYMNISTS FROM 1952 \n', fontsize=46, loc='left')
ax.set_xticks(label_locations, labels, fontsize=30)
ax.tick_params(axis='y', labelsize=26)
ax.legend(prop={'size': 36}, shadow=True)
ax.bar_label(semi_bar_m, padding=3, fontsize=24)
ax.bar_label(semi_bar_w, padding=3, fontsize=24)
plt.show()
fig = go.Figure()
fig.add_trace(go.Bar(x=labels, y=y_m, name='Male', marker_color='saddlebrown'))
fig.add_trace(go.Bar(x=labels, y=y_w, name='Female', marker_color='lightsalmon'))
fig.update_layout(barmode='group', xaxis_tickangle=-45, font=dict(size=18), title='FRENCH GYMNISTS FROM 1952')
fig.show()
|
{
"targets": [
{
"target_name": "gles3",
"sources": [ "src/node-gles3.cpp" ],
'include_dirs': [
'src', 'src/include'
],
'cflags':[],
'conditions': [
['OS=="mac"',
{
'libraries': [
'-lGLEW',
'-framework OpenGL'
],
'include_dirs': [
'./node_modules/native-graphics-deps/include'
],
'library_dirs': [
'../node_modules/native-graphics-deps/lib/macos/glew'
],
'xcode_settings': {
'MACOSX_DEPLOYMENT_TARGET': '10.13',
'OTHER_CFLAGS': [
"-Wno-unused-but-set-variable","-Wno-unused-parameter","-Wno-unused-variable","-Wno-int-to-void-pointer-cast"
],
}
}
],
['OS=="linux"', {
'libraries': [
'-lGLEW','-lGL']
}
],
['OS=="win"',
{
'include_dirs': [
'./node_modules/native-graphics-deps/include',
],
'library_dirs': [
'./node_modules/native-graphics-deps/lib/windows/glew',
'lib/<(target_arch)',
],
'libraries': [
'glew32.lib',
'opengl32.lib'
],
'defines' : [
'WIN32_LEAN_AND_MEAN',
'VC_EXTRALEAN'
],
'msvs_settings' : {
'VCCLCompilerTool' : {
'AdditionalOptions' : []
},
'VCLinkerTool' : {
'AdditionalOptions' : ['/OPT:REF','/OPT:ICF','/LTCG']
},
},
'copies': [
{
'destination': './build/<(CONFIGURATION_NAME)/',
'files': [
'./node_modules/native-graphics-deps/lib/windows/glew/glew32.dll'
]
}
],
}
],
],
},
{
"target_name": "glfw3",
"sources": [ "src/node-glfw3.cpp" ],
'include_dirs': [
'src', 'src/include'
],
'cflags':[],
'conditions': [
['OS=="mac"',
{
'libraries': [
'-framework Cocoa',
'../node_modules/native-graphics-deps/lib/macos/glfw/libglfw3.a'
],
'include_dirs': [
'./node_modules/native-graphics-deps/include'
],
'library_dirs': [
],
'xcode_settings': {
'MACOSX_DEPLOYMENT_TARGET': '10.13',
'OTHER_CFLAGS': [
"-Wno-unused-but-set-variable","-Wno-unused-parameter","-Wno-unused-variable"
],
}
}
],
['OS=="linux"', {
'libraries': []
}
],
['OS=="win"',
{
'include_dirs': [
'./node_modules/native-graphics-deps/include',
],
'library_dirs': [
'./node_modules/native-graphics-deps/lib/windows/glfw'
],
'libraries': [
'glfw3dll.lib'
],
'defines' : [
'WIN32_LEAN_AND_MEAN',
'VC_EXTRALEAN'
],
'msvs_settings' : {
'VCCLCompilerTool' : {
'AdditionalOptions' : []
},
'VCLinkerTool' : {
'AdditionalOptions' : ['/OPT:REF','/OPT:ICF','/LTCG']
},
},
'copies': [
{
'destination': './build/<(CONFIGURATION_NAME)/',
'files': [
'./node_modules/native-graphics-deps/lib/windows/glfw/glfw3.dll'
]
}
],
}
],
],
},
{
"target_name": "openvr",
"sources": [ "src/node-openvr.cpp" ],
'include_dirs': [
'./node_modules/native-graphics-deps/include',
'./node_modules/native-openvr-deps/headers',
'src', 'src/include'
],
"cflags": ["-std=c++11", "-Wall", "-pedantic"],
'conditions': [
['OS=="mac"',
{
'libraries': [
],
'library_dirs': [
],
'xcode_settings': {
'MACOSX_DEPLOYMENT_TARGET': '10.13',
'OTHER_CFLAGS': [
"-Wno-unused-but-set-variable","-Wno-unused-parameter","-Wno-unused-variable","-Wno-int-to-void-pointer-cast"
],
},
'copies': [
{
'destination': './build/<(CONFIGURATION_NAME)/',
'files': [
'./node_modules/native-openvr-deps/lib/osx32/libopenvr_api.dylib'
]
}
],
}
],
['OS=="linux"', {
'libraries': [
'-lGLEW','-lGL']
}
],
['OS=="win"',
{
'library_dirs': [
'./node_modules/native-openvr-deps/lib/win64',
],
'libraries': [
'openvr_api.lib'
],
'defines' : [
'WIN32_LEAN_AND_MEAN',
'VC_EXTRALEAN'
],
'msvs_settings' : {
'VCCLCompilerTool' : {
'AdditionalOptions' : []
},
'VCLinkerTool' : {
'AdditionalOptions' : ['/OPT:REF','/OPT:ICF','/LTCG']
},
},
'copies': [
{
'destination': './build/<(CONFIGURATION_NAME)/',
'files': [
'./node_modules/native-openvr-deps/bin/win64/openvr_api.dll'
]
}
],
}
],
],
},
{
"target_name": "audio",
"sources": [ "src/node-audio.cpp" ],
"defines": [],
"cflags": ["-std=c++11", "-Wall", "-pedantic"],
'cflags!': [ '-fno-exceptions' ],
'cflags_cc!': [ '-fno-exceptions' ],
"include_dirs": [
"<!(node -p \"require('node-addon-api').include_dir\")",
"src/miniaudio.h"
],
"libraries": [],
"dependencies": [],
"conditions": [
['OS=="win"', {
'msvs_settings': {
'VCCLCompilerTool': { 'ExceptionHandling': 1 },
}
}],
['OS=="mac"', {
'cflags+': ['-fvisibility=hidden'],
'xcode_settings': {
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
'CLANG_CXX_LIBRARY': 'libc++',
'MACOSX_DEPLOYMENT_TARGET': '10.7',
'GCC_SYMBOLS_PRIVATE_EXTERN': 'YES', # -fvisibility=hidden
},
}],
['OS=="linux"', {}],
],
},
{
"target_name": "zed",
"sources": [],
"defines": [],
"cflags": ["-std=c++11", "-Wall", "-pedantic"],
"include_dirs": [
"<!(node -p \"require('node-addon-api').include_dir\")",
],
"libraries": [],
"dependencies": [],
"conditions": [
['OS=="win"', {
"sources": [ "src/node-zed.cpp" ],
'include_dirs': [
"$(CUDA_PATH)/include",
"$(ZED_SDK_ROOT_DIR)/include"],
'library_dirs': [
'$(ZED_SDK_ROOT_DIR)/lib',
],
'libraries': [
'sl_zed64.lib'
],
'msvs_settings': {
'VCCLCompilerTool': { 'ExceptionHandling': 1 }
}
}],
['OS=="mac"', {
'cflags+': ['-fvisibility=hidden'],
'xcode_settings': {},
}],
['OS=="linux"', {}],
],
},
{
"target_name": "realsense",
"sources": [ "src/node-realsense.cpp" ],
"defines": [],
"cflags": ["-std=c++11", "-Wall", "-pedantic"],
"include_dirs": [
"<!(node -p \"require('node-addon-api').include_dir\")"
],
"libraries": [],
"dependencies": [],
"conditions": [
['OS=="win"', {
'include_dirs': [
"C:\\Program Files (x86)\\Intel RealSense SDK 2.0\\include"
],
'library_dirs': [
'C:\\Program Files (x86)\\Intel RealSense SDK 2.0\\lib\\x64',
],
'libraries': [
'-lrealsense2.lib'
],
'msvs_settings': {
'VCCLCompilerTool': { 'ExceptionHandling': 1 }
},
"copies": [{
'destination': './build/<(CONFIGURATION_NAME)/',
'files': ['C:\\Program Files (x86)\\Intel RealSense SDK 2.0\\bin\\x64\\realsense2.dll']
}]
}],
['OS=="mac"', {
'cflags+': ['-fvisibility=hidden'],
'xcode_settings': {},
}],
['OS=="linux"', {}],
],
}
]
}
|
{'targets': [{'target_name': 'gles3', 'sources': ['src/node-gles3.cpp'], 'include_dirs': ['src', 'src/include'], 'cflags': [], 'conditions': [['OS=="mac"', {'libraries': ['-lGLEW', '-framework OpenGL'], 'include_dirs': ['./node_modules/native-graphics-deps/include'], 'library_dirs': ['../node_modules/native-graphics-deps/lib/macos/glew'], 'xcode_settings': {'MACOSX_DEPLOYMENT_TARGET': '10.13', 'OTHER_CFLAGS': ['-Wno-unused-but-set-variable', '-Wno-unused-parameter', '-Wno-unused-variable', '-Wno-int-to-void-pointer-cast']}}], ['OS=="linux"', {'libraries': ['-lGLEW', '-lGL']}], ['OS=="win"', {'include_dirs': ['./node_modules/native-graphics-deps/include'], 'library_dirs': ['./node_modules/native-graphics-deps/lib/windows/glew', 'lib/<(target_arch)'], 'libraries': ['glew32.lib', 'opengl32.lib'], 'defines': ['WIN32_LEAN_AND_MEAN', 'VC_EXTRALEAN'], 'msvs_settings': {'VCCLCompilerTool': {'AdditionalOptions': []}, 'VCLinkerTool': {'AdditionalOptions': ['/OPT:REF', '/OPT:ICF', '/LTCG']}}, 'copies': [{'destination': './build/<(CONFIGURATION_NAME)/', 'files': ['./node_modules/native-graphics-deps/lib/windows/glew/glew32.dll']}]}]]}, {'target_name': 'glfw3', 'sources': ['src/node-glfw3.cpp'], 'include_dirs': ['src', 'src/include'], 'cflags': [], 'conditions': [['OS=="mac"', {'libraries': ['-framework Cocoa', '../node_modules/native-graphics-deps/lib/macos/glfw/libglfw3.a'], 'include_dirs': ['./node_modules/native-graphics-deps/include'], 'library_dirs': [], 'xcode_settings': {'MACOSX_DEPLOYMENT_TARGET': '10.13', 'OTHER_CFLAGS': ['-Wno-unused-but-set-variable', '-Wno-unused-parameter', '-Wno-unused-variable']}}], ['OS=="linux"', {'libraries': []}], ['OS=="win"', {'include_dirs': ['./node_modules/native-graphics-deps/include'], 'library_dirs': ['./node_modules/native-graphics-deps/lib/windows/glfw'], 'libraries': ['glfw3dll.lib'], 'defines': ['WIN32_LEAN_AND_MEAN', 'VC_EXTRALEAN'], 'msvs_settings': {'VCCLCompilerTool': {'AdditionalOptions': []}, 'VCLinkerTool': {'AdditionalOptions': ['/OPT:REF', '/OPT:ICF', '/LTCG']}}, 'copies': [{'destination': './build/<(CONFIGURATION_NAME)/', 'files': ['./node_modules/native-graphics-deps/lib/windows/glfw/glfw3.dll']}]}]]}, {'target_name': 'openvr', 'sources': ['src/node-openvr.cpp'], 'include_dirs': ['./node_modules/native-graphics-deps/include', './node_modules/native-openvr-deps/headers', 'src', 'src/include'], 'cflags': ['-std=c++11', '-Wall', '-pedantic'], 'conditions': [['OS=="mac"', {'libraries': [], 'library_dirs': [], 'xcode_settings': {'MACOSX_DEPLOYMENT_TARGET': '10.13', 'OTHER_CFLAGS': ['-Wno-unused-but-set-variable', '-Wno-unused-parameter', '-Wno-unused-variable', '-Wno-int-to-void-pointer-cast']}, 'copies': [{'destination': './build/<(CONFIGURATION_NAME)/', 'files': ['./node_modules/native-openvr-deps/lib/osx32/libopenvr_api.dylib']}]}], ['OS=="linux"', {'libraries': ['-lGLEW', '-lGL']}], ['OS=="win"', {'library_dirs': ['./node_modules/native-openvr-deps/lib/win64'], 'libraries': ['openvr_api.lib'], 'defines': ['WIN32_LEAN_AND_MEAN', 'VC_EXTRALEAN'], 'msvs_settings': {'VCCLCompilerTool': {'AdditionalOptions': []}, 'VCLinkerTool': {'AdditionalOptions': ['/OPT:REF', '/OPT:ICF', '/LTCG']}}, 'copies': [{'destination': './build/<(CONFIGURATION_NAME)/', 'files': ['./node_modules/native-openvr-deps/bin/win64/openvr_api.dll']}]}]]}, {'target_name': 'audio', 'sources': ['src/node-audio.cpp'], 'defines': [], 'cflags': ['-std=c++11', '-Wall', '-pedantic'], 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exceptions'], 'include_dirs': ['<!(node -p "require(\'node-addon-api\').include_dir")', 'src/miniaudio.h'], 'libraries': [], 'dependencies': [], 'conditions': [['OS=="win"', {'msvs_settings': {'VCCLCompilerTool': {'ExceptionHandling': 1}}}], ['OS=="mac"', {'cflags+': ['-fvisibility=hidden'], 'xcode_settings': {'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', 'CLANG_CXX_LIBRARY': 'libc++', 'MACOSX_DEPLOYMENT_TARGET': '10.7', 'GCC_SYMBOLS_PRIVATE_EXTERN': 'YES'}}], ['OS=="linux"', {}]]}, {'target_name': 'zed', 'sources': [], 'defines': [], 'cflags': ['-std=c++11', '-Wall', '-pedantic'], 'include_dirs': ['<!(node -p "require(\'node-addon-api\').include_dir")'], 'libraries': [], 'dependencies': [], 'conditions': [['OS=="win"', {'sources': ['src/node-zed.cpp'], 'include_dirs': ['$(CUDA_PATH)/include', '$(ZED_SDK_ROOT_DIR)/include'], 'library_dirs': ['$(ZED_SDK_ROOT_DIR)/lib'], 'libraries': ['sl_zed64.lib'], 'msvs_settings': {'VCCLCompilerTool': {'ExceptionHandling': 1}}}], ['OS=="mac"', {'cflags+': ['-fvisibility=hidden'], 'xcode_settings': {}}], ['OS=="linux"', {}]]}, {'target_name': 'realsense', 'sources': ['src/node-realsense.cpp'], 'defines': [], 'cflags': ['-std=c++11', '-Wall', '-pedantic'], 'include_dirs': ['<!(node -p "require(\'node-addon-api\').include_dir")'], 'libraries': [], 'dependencies': [], 'conditions': [['OS=="win"', {'include_dirs': ['C:\\Program Files (x86)\\Intel RealSense SDK 2.0\\include'], 'library_dirs': ['C:\\Program Files (x86)\\Intel RealSense SDK 2.0\\lib\\x64'], 'libraries': ['-lrealsense2.lib'], 'msvs_settings': {'VCCLCompilerTool': {'ExceptionHandling': 1}}, 'copies': [{'destination': './build/<(CONFIGURATION_NAME)/', 'files': ['C:\\Program Files (x86)\\Intel RealSense SDK 2.0\\bin\\x64\\realsense2.dll']}]}], ['OS=="mac"', {'cflags+': ['-fvisibility=hidden'], 'xcode_settings': {}}], ['OS=="linux"', {}]]}]}
|
'''
Created on 7 jan. 2013
@author: sander
'''
# The following Key ID values are defined by this specification as used
# in any packet type that references a Key ID field:
#
# Name Number Defined in
#-----------------------------------------------
# None 0 n/a
# HMAC-SHA-1-96 1 [RFC2404]
# HMAC-SHA-256-128 2 [RFC6234]
KEY_ID_NONE = 0
KEY_ID_HMAC_SHA_1_96 = 1
KEY_ID_HMAC_SHA_256_128 = 2
|
"""
Created on 7 jan. 2013
@author: sander
"""
key_id_none = 0
key_id_hmac_sha_1_96 = 1
key_id_hmac_sha_256_128 = 2
|
#!/usr/bin/python3
# ref: https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange#Cryptographic_explanation
# ref: https://en.wikipedia.org/wiki/RSA_(cryptosystem)
shared_modulus = 23
shared_base = 5
print("shared modulus: %s" % shared_modulus)
print("shared base: %s" % shared_base)
print("-"*40)
alice_secret = 4
bob_secret = 3
print("alice's secret key: %s" % alice_secret)
print("bob's secret key: %s" % bob_secret)
print("-"*40)
A = (shared_base**alice_secret) % shared_modulus
B = (shared_base**bob_secret) % shared_modulus
print("alice's public key: %s" % A)
print("bob's public key: %s" % B)
print("-"*40)
alice_s = (B**alice_secret) % shared_modulus
bob_s = (A**bob_secret) % shared_modulus
print("alice's shared secret key: %s" % alice_s)
print("bob's shared secret key: %s" % bob_s)
|
shared_modulus = 23
shared_base = 5
print('shared modulus: %s' % shared_modulus)
print('shared base: %s' % shared_base)
print('-' * 40)
alice_secret = 4
bob_secret = 3
print("alice's secret key: %s" % alice_secret)
print("bob's secret key: %s" % bob_secret)
print('-' * 40)
a = shared_base ** alice_secret % shared_modulus
b = shared_base ** bob_secret % shared_modulus
print("alice's public key: %s" % A)
print("bob's public key: %s" % B)
print('-' * 40)
alice_s = B ** alice_secret % shared_modulus
bob_s = A ** bob_secret % shared_modulus
print("alice's shared secret key: %s" % alice_s)
print("bob's shared secret key: %s" % bob_s)
|
#!/usr/bin/env python
# @Time : 2019-06-03
# @Author : hongshu
BUFF_SIZE = 32 * 1024
|
buff_size = 32 * 1024
|
###########################
# 6.0002 Problem Set 1b: Space Change
# Name:
# Collaborators:
# Time:
# Author: charz, cdenise
#================================
# Part B: Golden Eggs
#================================
# Problem 1
def dp_make_weight(egg_weights, target_weight, memo = {}):
"""
Find number of eggs to bring back, using the smallest number of eggs. Assumes there is
an infinite supply of eggs of each weight, and there is always a egg of value 1.
Parameters:
egg_weights - tuple of integers, available egg weights sorted from smallest to largest value (1 = d1 < d2 < ... < dk)
target_weight - int, amount of weight we want to find eggs to fit
memo - dictionary, OPTIONAL parameter for memoization (you may not need to use this parameter depending on your implementation)
Returns: int, smallest number of eggs needed to make target weight
"""
# base case if target weight is zero!
if target_weight == 0:
return 0
# try to get solution for current target_weight from memo
try:
return memo[target_weight]
# if unsuccesful apply recursion to get solution
except KeyError:
solutions = []
for e in egg_weights:
# weight if we choose this egg?
new_weight = target_weight - e
# always true for at least one weight if there is always a egg of value 1
if new_weight >= 0:
solutions.append(1 + dp_make_weight(egg_weights, new_weight, memo))
best_solution = min(solutions)
memo[target_weight] = best_solution
return best_solution
# EXAMPLE TESTING CODE, feel free to add more if you'd like
if __name__ == '__main__':
egg_weights = (1, 5, 10, 25)
n = 99
print("Egg weights = (1, 5, 10, 25)")
print("n = 99")
print("Expected ouput: 9 (3 * 25 + 2 * 10 + 4 * 1 = 99)")
print("Actual output:", dp_make_weight(egg_weights, n))
print()
|
def dp_make_weight(egg_weights, target_weight, memo={}):
"""
Find number of eggs to bring back, using the smallest number of eggs. Assumes there is
an infinite supply of eggs of each weight, and there is always a egg of value 1.
Parameters:
egg_weights - tuple of integers, available egg weights sorted from smallest to largest value (1 = d1 < d2 < ... < dk)
target_weight - int, amount of weight we want to find eggs to fit
memo - dictionary, OPTIONAL parameter for memoization (you may not need to use this parameter depending on your implementation)
Returns: int, smallest number of eggs needed to make target weight
"""
if target_weight == 0:
return 0
try:
return memo[target_weight]
except KeyError:
solutions = []
for e in egg_weights:
new_weight = target_weight - e
if new_weight >= 0:
solutions.append(1 + dp_make_weight(egg_weights, new_weight, memo))
best_solution = min(solutions)
memo[target_weight] = best_solution
return best_solution
if __name__ == '__main__':
egg_weights = (1, 5, 10, 25)
n = 99
print('Egg weights = (1, 5, 10, 25)')
print('n = 99')
print('Expected ouput: 9 (3 * 25 + 2 * 10 + 4 * 1 = 99)')
print('Actual output:', dp_make_weight(egg_weights, n))
print()
|
# from functools import wraps
# def debugMethod(func, cls=None):
# '''decorator for debugging passed function'''
# @wraps(func)
# def wrapper(*args, **kwargs):
# print({
# 'class': cls, # class object, not string
# 'method': func.__qualname__, # method name, string
# 'args': args, # all args, including self
# 'kwargs': kwargs
# })
# return func(*args, **kwargs)
# return wrapper
class Meta(type):
# def __new__(cls, clsname, bases, clsdict):
# obj = super().__new__(cls, clsname, bases, clsdict)
# def IS_DUNDER(x): return x.startswith("__") and x.endswith("__")
# for item, val in vars(obj).items():
# if callable(val):
# # setattr(obj, item, debugMethod(val, cls=cls))
# pass
# return obj
def __getattribute__(self, name):
print({'action': "get", 'attr': name})
return object.__getattribute__(self, name)
class A(object, metaclass=Meta):
# def __init__(self):
# pass
# def __setattr__(self, name, value):
# print("setting attribute", name, value)
# return super().__setattr__(name, value)
# def __getattribute__(self, name):
# print("getting attribute", name)
# return super().__getattribute__(name)
def add(self, x, y):
return x+y
def mul(self, x, y):
return x*y
a = A()
# a.mul(2, 3)
# a.mul(0, 100)
# a.mul(2, 100)
# a.mul(2323, 3)
# a.mul(2, 2)
# a.mul(2, 3414)
# another setter
a.x = 200
# print(vars(a))
# # settter
# a.x = 1000
# # setter
# a.x = "23931903"
# # finally a getter
# my_getter_val = a.x
|
class Meta(type):
def __getattribute__(self, name):
print({'action': 'get', 'attr': name})
return object.__getattribute__(self, name)
class A(object, metaclass=Meta):
def add(self, x, y):
return x + y
def mul(self, x, y):
return x * y
a = a()
a.x = 200
|
#!/usr/bin/env python3
"""Solves problem xxx from the Project Euler website"""
def solve():
"""Solve the problem and return the result"""
oneToNine = sum(
[len('one'),
len('two'),
len('three'),
len('four'),
len('five'),
len('six'),
len('seven'),
len('eight'),
len('nine')])
oneToNintynine = 10 * sum(
[len('twenty'),
len('thirty'),
len('forty'),
len('fifty'),
len('sixty'),
len('seventy'),
len('eighty'),
len('ninety')]) + sum(
[len('ten'),
len('eleven'),
len('twelve'),
len('thirteen'),
len('fourteen'),
len('fifteen'),
len('sixteen'),
len('seventeen'),
len('eighteen'),
len('nineteen')]) + 9 * oneToNine
result = len('one') + len('thousand') + 100 * (9 * len('hundred') + oneToNine) + 99 * 9 * len(
'and') + 10 * oneToNintynine
return result
if __name__ == '__main__':
print(solve())
|
"""Solves problem xxx from the Project Euler website"""
def solve():
"""Solve the problem and return the result"""
one_to_nine = sum([len('one'), len('two'), len('three'), len('four'), len('five'), len('six'), len('seven'), len('eight'), len('nine')])
one_to_nintynine = 10 * sum([len('twenty'), len('thirty'), len('forty'), len('fifty'), len('sixty'), len('seventy'), len('eighty'), len('ninety')]) + sum([len('ten'), len('eleven'), len('twelve'), len('thirteen'), len('fourteen'), len('fifteen'), len('sixteen'), len('seventeen'), len('eighteen'), len('nineteen')]) + 9 * oneToNine
result = len('one') + len('thousand') + 100 * (9 * len('hundred') + oneToNine) + 99 * 9 * len('and') + 10 * oneToNintynine
return result
if __name__ == '__main__':
print(solve())
|
class NCBaseError(Exception):
def __init__(self, message) -> None:
super(NCBaseError, self).__init__(message)
class DataTypeMismatchError(Exception):
def __init__(self, provided_data, place:str=None, required_data_type:str=None) -> None:
message = f"{provided_data} datatype isn't supported for {place}.\nRequired datatype is: {required_data_type}, got: {str(type(provided_data).__name__)}"
super(DataTypeMismatchError, self).__init__(message)
class InsufficientArgumentsError(Exception):
def __init__(self, message):
message = f"Insufficient arguments.\n{message}"
super(InsufficientArgumentsError, self).__init__(message)
class InvalidArgumentsError(Exception):
def __init__(self, message:str) -> None:
super(InvalidArgumentsError, self).__init__(message)
class DirectoryAlreadyExistsError(Exception):
def __init__(self,project_dir):
message = f"{project_dir} already exists at the location."
super(DirectoryAlreadyExistsError, self).__init__(message)
class ImportNameNotFoundError(Exception):
def __init__(self, location) -> None:
message = f"import_name notm provided for the sister app at {location}"
super(ImportNameNotFoundError, self).__init__(message)
class ConfigurationError(Exception):
def __init__(self, message) -> None:
super(ConfigurationError, self).__init__(message)
|
class Ncbaseerror(Exception):
def __init__(self, message) -> None:
super(NCBaseError, self).__init__(message)
class Datatypemismatcherror(Exception):
def __init__(self, provided_data, place: str=None, required_data_type: str=None) -> None:
message = f"{provided_data} datatype isn't supported for {place}.\nRequired datatype is: {required_data_type}, got: {str(type(provided_data).__name__)}"
super(DataTypeMismatchError, self).__init__(message)
class Insufficientargumentserror(Exception):
def __init__(self, message):
message = f'Insufficient arguments.\n{message}'
super(InsufficientArgumentsError, self).__init__(message)
class Invalidargumentserror(Exception):
def __init__(self, message: str) -> None:
super(InvalidArgumentsError, self).__init__(message)
class Directoryalreadyexistserror(Exception):
def __init__(self, project_dir):
message = f'{project_dir} already exists at the location.'
super(DirectoryAlreadyExistsError, self).__init__(message)
class Importnamenotfounderror(Exception):
def __init__(self, location) -> None:
message = f'import_name notm provided for the sister app at {location}'
super(ImportNameNotFoundError, self).__init__(message)
class Configurationerror(Exception):
def __init__(self, message) -> None:
super(ConfigurationError, self).__init__(message)
|
class Node:
def __init__(self, data):
self.data= data
self.previous= None
self.next= None
class DoublyLinkedList:
def __init__(self):
self.head= None
def create_list(self, arr):
start= self.head
n= len(arr)
temp= start
i=0
while(i<n):
new_node= Node(arr[i])
if (i==0):
start= new_node
temp= start
else:
temp.next= new_node
new_node.prev= temp
temp= temp.next
i+=1
self.head= start
return start
def count_elements(self):
temp= self.head
count=0
while(temp):
count+=1
temp=temp.next
return count
def insert_node(self, value, pos):
temp= self.head
count_of_elem= self.count_elements()
#index is 6, count is 5, valid
#index is 7, count is 5,
if (count_of_elem+1<pos):
return temp
new_node= Node(value)
if (pos==1):
new_node.next= temp
temp.previous= new_node
self.head= new_node
return self.head
if (pos==count_of_elem+1):
while(temp.next):
temp= temp.next
temp.next= new_node
new_node.previous= temp
return self.head
counter = 1
while (counter < pos):
temp = temp.next
counter += 1
node_at_target = temp
previous_node = node_at_target.previous
previous_node.next = new_node
new_node.previous = previous_node
new_node.next = node_at_target
node_at_target.previous = new_node
return self.head
def delete_node(self, pos):
temp= self.head
count_of_elem= self.count_elements()
if (count_of_elem<pos):
return 'delete position {} is greater than list size {}'.format(pos, count_of_elem)
if (pos==1):
temp= temp.next
self.head=temp
return self.head
if(pos==count_of_elem):
while(temp.next and temp.next.next):
temp=temp.next
temp.next= None
return self.head
i=1
while(i<pos-1):
temp= temp.next
i+=1
prev_node= temp
target_node= temp.next
next_node= target_node.next
next_node.previous= prev_node
prev_node.next= next_node
return self.head
def print_list(self):
temp= self.head
linked_list= "head=>"
while(temp.next):
linked_list+= str(temp.data)+"<=>"
temp= temp.next
linked_list+= str(temp.data)
print(linked_list)
arr= [1,2,3,4,5]
dll= DoublyLinkedList()
dll.create_list(arr)
dll.print_list()
dll.count_elements()
dll.insert_node(6,3)
dll.print_list()
dll.count_elements()
dll.insert_node(10000,3)
dll.print_list()
# dll.delete_node(2)
# dll.print_list()
|
class Node:
def __init__(self, data):
self.data = data
self.previous = None
self.next = None
class Doublylinkedlist:
def __init__(self):
self.head = None
def create_list(self, arr):
start = self.head
n = len(arr)
temp = start
i = 0
while i < n:
new_node = node(arr[i])
if i == 0:
start = new_node
temp = start
else:
temp.next = new_node
new_node.prev = temp
temp = temp.next
i += 1
self.head = start
return start
def count_elements(self):
temp = self.head
count = 0
while temp:
count += 1
temp = temp.next
return count
def insert_node(self, value, pos):
temp = self.head
count_of_elem = self.count_elements()
if count_of_elem + 1 < pos:
return temp
new_node = node(value)
if pos == 1:
new_node.next = temp
temp.previous = new_node
self.head = new_node
return self.head
if pos == count_of_elem + 1:
while temp.next:
temp = temp.next
temp.next = new_node
new_node.previous = temp
return self.head
counter = 1
while counter < pos:
temp = temp.next
counter += 1
node_at_target = temp
previous_node = node_at_target.previous
previous_node.next = new_node
new_node.previous = previous_node
new_node.next = node_at_target
node_at_target.previous = new_node
return self.head
def delete_node(self, pos):
temp = self.head
count_of_elem = self.count_elements()
if count_of_elem < pos:
return 'delete position {} is greater than list size {}'.format(pos, count_of_elem)
if pos == 1:
temp = temp.next
self.head = temp
return self.head
if pos == count_of_elem:
while temp.next and temp.next.next:
temp = temp.next
temp.next = None
return self.head
i = 1
while i < pos - 1:
temp = temp.next
i += 1
prev_node = temp
target_node = temp.next
next_node = target_node.next
next_node.previous = prev_node
prev_node.next = next_node
return self.head
def print_list(self):
temp = self.head
linked_list = 'head=>'
while temp.next:
linked_list += str(temp.data) + '<=>'
temp = temp.next
linked_list += str(temp.data)
print(linked_list)
arr = [1, 2, 3, 4, 5]
dll = doubly_linked_list()
dll.create_list(arr)
dll.print_list()
dll.count_elements()
dll.insert_node(6, 3)
dll.print_list()
dll.count_elements()
dll.insert_node(10000, 3)
dll.print_list()
|
# The ranges below are as specified in the Yellow Paper.
# Note: range(s, e) excludes e, hence the +1
valid_opcodes = [
*range(0x00, 0x0b + 1),
*range(0x10, 0x1d + 1),
0x20,
*range(0x30, 0x3f + 1),
*range(0x40, 0x48 + 1),
*range(0x50, 0x5b + 1),
*range(0x60, 0x6f + 1),
*range(0x70, 0x7f + 1),
*range(0x80, 0x8f + 1),
*range(0x90, 0x9f + 1),
*range(0xa0, 0xa4 + 1),
# Note: 0xfe is considered assigned.
*range(0xf0, 0xf5 + 1), 0xfa, 0xfd, 0xfe, 0xff
]
# STOP, RETURN, REVERT, INVALID, SELFDESTRUCT
terminating_opcodes = [ 0x00, 0xf3, 0xfd, 0xfe, 0xff ]
# Only for PUSH1..PUSH32
immediate_sizes = 256 * [0]
for opcode in range(0x60, 0x7f + 1): # PUSH1..PUSH32
immediate_sizes[opcode] = opcode - 0x60 + 1
# Fails with assertion on invalid code
def validate_code(code: bytes):
# Note that EOF1 already asserts this with the code section requirements
assert len(code) > 0
opcode = 0
pos = 0
while pos < len(code):
# Ensure the opcode is valid
opcode = code[pos]
pos += 1
assert opcode in valid_opcodes
# Skip immediates
pos += immediate_sizes[opcode]
# Ensure last opcode's immediate doesn't go over code end
assert pos == len(code)
# opcode is the *last opcode*
assert opcode in terminating_opcodes
def test_validate_code(code: bytes) -> bool:
try:
validate_code(code)
return True
except:
return False
# Some valid opcodes
assert test_validate_code(b'\x30\x00') == True
assert test_validate_code(b'\x50\x00') == True
assert test_validate_code(b'\xfe\x00') == True
assert test_validate_code(b'\xff\x00') == True
# PUSHes with valid immediates
assert test_validate_code(b'\x60\x00\x00') == True
assert test_validate_code(b'\x61' + b'\x00' * 2 + b'\x00') == True
assert test_validate_code(b'\x62' + b'\x00' * 3 + b'\x00') == True
assert test_validate_code(b'\x63' + b'\x00' * 4 + b'\x00') == True
assert test_validate_code(b'\x64' + b'\x00' * 5 + b'\x00') == True
assert test_validate_code(b'\x65' + b'\x00' * 6 + b'\x00') == True
assert test_validate_code(b'\x66' + b'\x00' * 7 + b'\x00') == True
assert test_validate_code(b'\x67' + b'\x00' * 8 + b'\x00') == True
assert test_validate_code(b'\x68' + b'\x00' * 9 + b'\x00') == True
assert test_validate_code(b'\x69' + b'\x00' * 10 + b'\x00') == True
assert test_validate_code(b'\x6a' + b'\x00' * 11 + b'\x00') == True
assert test_validate_code(b'\x6b' + b'\x00' * 12 + b'\x00') == True
assert test_validate_code(b'\x6c' + b'\x00' * 13 + b'\x00') == True
assert test_validate_code(b'\x6d' + b'\x00' * 14 + b'\x00') == True
assert test_validate_code(b'\x6e' + b'\x00' * 15 + b'\x00') == True
assert test_validate_code(b'\x6f' + b'\x00' * 16 + b'\x00') == True
assert test_validate_code(b'\x70' + b'\x00' * 17 + b'\x00') == True
assert test_validate_code(b'\x71' + b'\x00' * 18 + b'\x00') == True
assert test_validate_code(b'\x72' + b'\x00' * 19 + b'\x00') == True
assert test_validate_code(b'\x73' + b'\x00' * 20 + b'\x00') == True
assert test_validate_code(b'\x74' + b'\x00' * 21 + b'\x00') == True
assert test_validate_code(b'\x75' + b'\x00' * 22 + b'\x00') == True
assert test_validate_code(b'\x76' + b'\x00' * 23 + b'\x00') == True
assert test_validate_code(b'\x77' + b'\x00' * 24 + b'\x00') == True
assert test_validate_code(b'\x78' + b'\x00' * 25 + b'\x00') == True
assert test_validate_code(b'\x79' + b'\x00' * 26 + b'\x00') == True
assert test_validate_code(b'\x7a' + b'\x00' * 27 + b'\x00') == True
assert test_validate_code(b'\x7b' + b'\x00' * 28 + b'\x00') == True
assert test_validate_code(b'\x7c' + b'\x00' * 29 + b'\x00') == True
assert test_validate_code(b'\x7d' + b'\x00' * 30 + b'\x00') == True
assert test_validate_code(b'\x7e' + b'\x00' * 31 + b'\x00') == True
assert test_validate_code(b'\x7f' + b'\x00' * 32 + b'\x00') == True
# Valid code terminators
assert test_validate_code(b'\x00') == True
assert test_validate_code(b'\xf3') == True
assert test_validate_code(b'\xfd') == True
assert test_validate_code(b'\xfe') == True
# Empty code
assert test_validate_code(b'') == False
# Valid opcode, but invalid as terminator
assert test_validate_code(b'\x5b') == False
# Invalid opcodes
assert test_validate_code(b'\x0c\x00') == False
assert test_validate_code(b'\x0d\x00') == False
assert test_validate_code(b'\x0e\x00') == False
assert test_validate_code(b'\x0f\x00') == False
assert test_validate_code(b'\x1e\x00') == False
assert test_validate_code(b'\x1f\x00') == False
assert test_validate_code(b'\x21\x00') == False
assert test_validate_code(b'\x22\x00') == False
assert test_validate_code(b'\x23\x00') == False
assert test_validate_code(b'\x24\x00') == False
assert test_validate_code(b'\x25\x00') == False
assert test_validate_code(b'\x26\x00') == False
assert test_validate_code(b'\x27\x00') == False
assert test_validate_code(b'\x28\x00') == False
assert test_validate_code(b'\x29\x00') == False
assert test_validate_code(b'\x2a\x00') == False
assert test_validate_code(b'\x2b\x00') == False
assert test_validate_code(b'\x2c\x00') == False
assert test_validate_code(b'\x2d\x00') == False
assert test_validate_code(b'\x2e\x00') == False
assert test_validate_code(b'\x2f\x00') == False
assert test_validate_code(b'\x49\x00') == False
assert test_validate_code(b'\x4a\x00') == False
assert test_validate_code(b'\x4b\x00') == False
assert test_validate_code(b'\x4c\x00') == False
assert test_validate_code(b'\x4d\x00') == False
assert test_validate_code(b'\x4e\x00') == False
assert test_validate_code(b'\x4f\x00') == False
assert test_validate_code(b'\x5c\x00') == False
assert test_validate_code(b'\x5d\x00') == False
assert test_validate_code(b'\x5e\x00') == False
assert test_validate_code(b'\x5f\x00') == False
assert test_validate_code(b'\xa5\x00') == False
assert test_validate_code(b'\xa6\x00') == False
assert test_validate_code(b'\xa7\x00') == False
assert test_validate_code(b'\xa8\x00') == False
assert test_validate_code(b'\xa9\x00') == False
assert test_validate_code(b'\xaa\x00') == False
assert test_validate_code(b'\xab\x00') == False
assert test_validate_code(b'\xac\x00') == False
assert test_validate_code(b'\xad\x00') == False
assert test_validate_code(b'\xae\x00') == False
assert test_validate_code(b'\xaf\x00') == False
assert test_validate_code(b'\xb0\x00') == False
assert test_validate_code(b'\xb1\x00') == False
assert test_validate_code(b'\xb2\x00') == False
assert test_validate_code(b'\xb3\x00') == False
assert test_validate_code(b'\xb4\x00') == False
assert test_validate_code(b'\xb5\x00') == False
assert test_validate_code(b'\xb6\x00') == False
assert test_validate_code(b'\xb7\x00') == False
assert test_validate_code(b'\xb8\x00') == False
assert test_validate_code(b'\xb9\x00') == False
assert test_validate_code(b'\xba\x00') == False
assert test_validate_code(b'\xbb\x00') == False
assert test_validate_code(b'\xbc\x00') == False
assert test_validate_code(b'\xbd\x00') == False
assert test_validate_code(b'\xbe\x00') == False
assert test_validate_code(b'\xbf\x00') == False
assert test_validate_code(b'\xc0\x00') == False
assert test_validate_code(b'\xc1\x00') == False
assert test_validate_code(b'\xc2\x00') == False
assert test_validate_code(b'\xc3\x00') == False
assert test_validate_code(b'\xc4\x00') == False
assert test_validate_code(b'\xc5\x00') == False
assert test_validate_code(b'\xc6\x00') == False
assert test_validate_code(b'\xc7\x00') == False
assert test_validate_code(b'\xc8\x00') == False
assert test_validate_code(b'\xc9\x00') == False
assert test_validate_code(b'\xca\x00') == False
assert test_validate_code(b'\xcb\x00') == False
assert test_validate_code(b'\xcc\x00') == False
assert test_validate_code(b'\xcd\x00') == False
assert test_validate_code(b'\xce\x00') == False
assert test_validate_code(b'\xcf\x00') == False
assert test_validate_code(b'\xd0\x00') == False
assert test_validate_code(b'\xd1\x00') == False
assert test_validate_code(b'\xd2\x00') == False
assert test_validate_code(b'\xd3\x00') == False
assert test_validate_code(b'\xd4\x00') == False
assert test_validate_code(b'\xd5\x00') == False
assert test_validate_code(b'\xd6\x00') == False
assert test_validate_code(b'\xd7\x00') == False
assert test_validate_code(b'\xd8\x00') == False
assert test_validate_code(b'\xd9\x00') == False
assert test_validate_code(b'\xda\x00') == False
assert test_validate_code(b'\xdb\x00') == False
assert test_validate_code(b'\xdc\x00') == False
assert test_validate_code(b'\xdd\x00') == False
assert test_validate_code(b'\xde\x00') == False
assert test_validate_code(b'\xdf\x00') == False
assert test_validate_code(b'\xe0\x00') == False
assert test_validate_code(b'\xe1\x00') == False
assert test_validate_code(b'\xe2\x00') == False
assert test_validate_code(b'\xe3\x00') == False
assert test_validate_code(b'\xe4\x00') == False
assert test_validate_code(b'\xe5\x00') == False
assert test_validate_code(b'\xe6\x00') == False
assert test_validate_code(b'\xe7\x00') == False
assert test_validate_code(b'\xe8\x00') == False
assert test_validate_code(b'\xe9\x00') == False
assert test_validate_code(b'\xea\x00') == False
assert test_validate_code(b'\xeb\x00') == False
assert test_validate_code(b'\xec\x00') == False
assert test_validate_code(b'\xed\x00') == False
assert test_validate_code(b'\xee\x00') == False
assert test_validate_code(b'\xef\x00') == False
assert test_validate_code(b'\xf6\x00') == False
assert test_validate_code(b'\xf7\x00') == False
assert test_validate_code(b'\xf8\x00') == False
assert test_validate_code(b'\xf9\x00') == False
assert test_validate_code(b'\xfb\x00') == False
assert test_validate_code(b'\xfc\x00') == False
# PUSHes with truncated immediates
assert test_validate_code(b'\x60\x00') == False
assert test_validate_code(b'\x61' + b'\x00' * 1 + b'\x00') == False
assert test_validate_code(b'\x62' + b'\x00' * 2 + b'\x00') == False
assert test_validate_code(b'\x63' + b'\x00' * 3 + b'\x00') == False
assert test_validate_code(b'\x64' + b'\x00' * 4 + b'\x00') == False
assert test_validate_code(b'\x65' + b'\x00' * 5 + b'\x00') == False
assert test_validate_code(b'\x66' + b'\x00' * 6 + b'\x00') == False
assert test_validate_code(b'\x67' + b'\x00' * 7 + b'\x00') == False
assert test_validate_code(b'\x68' + b'\x00' * 8 + b'\x00') == False
assert test_validate_code(b'\x69' + b'\x00' * 9 + b'\x00') == False
assert test_validate_code(b'\x6a' + b'\x00' * 10 + b'\x00') == False
assert test_validate_code(b'\x6b' + b'\x00' * 11 + b'\x00') == False
assert test_validate_code(b'\x6c' + b'\x00' * 12 + b'\x00') == False
assert test_validate_code(b'\x6d' + b'\x00' * 13 + b'\x00') == False
assert test_validate_code(b'\x6e' + b'\x00' * 14 + b'\x00') == False
assert test_validate_code(b'\x6f' + b'\x00' * 15 + b'\x00') == False
assert test_validate_code(b'\x70' + b'\x00' * 16 + b'\x00') == False
assert test_validate_code(b'\x71' + b'\x00' * 17 + b'\x00') == False
assert test_validate_code(b'\x72' + b'\x00' * 18 + b'\x00') == False
assert test_validate_code(b'\x73' + b'\x00' * 19 + b'\x00') == False
assert test_validate_code(b'\x74' + b'\x00' * 20 + b'\x00') == False
assert test_validate_code(b'\x75' + b'\x00' * 21 + b'\x00') == False
assert test_validate_code(b'\x76' + b'\x00' * 22 + b'\x00') == False
assert test_validate_code(b'\x77' + b'\x00' * 23 + b'\x00') == False
assert test_validate_code(b'\x78' + b'\x00' * 24 + b'\x00') == False
assert test_validate_code(b'\x79' + b'\x00' * 25 + b'\x00') == False
assert test_validate_code(b'\x7a' + b'\x00' * 26 + b'\x00') == False
assert test_validate_code(b'\x7b' + b'\x00' * 27 + b'\x00') == False
assert test_validate_code(b'\x7c' + b'\x00' * 28 + b'\x00') == False
assert test_validate_code(b'\x7d' + b'\x00' * 29 + b'\x00') == False
assert test_validate_code(b'\x7e' + b'\x00' * 30 + b'\x00') == False
assert test_validate_code(b'\x7f' + b'\x00' * 31 + b'\x00') == False
|
valid_opcodes = [*range(0, 11 + 1), *range(16, 29 + 1), 32, *range(48, 63 + 1), *range(64, 72 + 1), *range(80, 91 + 1), *range(96, 111 + 1), *range(112, 127 + 1), *range(128, 143 + 1), *range(144, 159 + 1), *range(160, 164 + 1), *range(240, 245 + 1), 250, 253, 254, 255]
terminating_opcodes = [0, 243, 253, 254, 255]
immediate_sizes = 256 * [0]
for opcode in range(96, 127 + 1):
immediate_sizes[opcode] = opcode - 96 + 1
def validate_code(code: bytes):
assert len(code) > 0
opcode = 0
pos = 0
while pos < len(code):
opcode = code[pos]
pos += 1
assert opcode in valid_opcodes
pos += immediate_sizes[opcode]
assert pos == len(code)
assert opcode in terminating_opcodes
def test_validate_code(code: bytes) -> bool:
try:
validate_code(code)
return True
except:
return False
assert test_validate_code(b'0\x00') == True
assert test_validate_code(b'P\x00') == True
assert test_validate_code(b'\xfe\x00') == True
assert test_validate_code(b'\xff\x00') == True
assert test_validate_code(b'`\x00\x00') == True
assert test_validate_code(b'a' + b'\x00' * 2 + b'\x00') == True
assert test_validate_code(b'b' + b'\x00' * 3 + b'\x00') == True
assert test_validate_code(b'c' + b'\x00' * 4 + b'\x00') == True
assert test_validate_code(b'd' + b'\x00' * 5 + b'\x00') == True
assert test_validate_code(b'e' + b'\x00' * 6 + b'\x00') == True
assert test_validate_code(b'f' + b'\x00' * 7 + b'\x00') == True
assert test_validate_code(b'g' + b'\x00' * 8 + b'\x00') == True
assert test_validate_code(b'h' + b'\x00' * 9 + b'\x00') == True
assert test_validate_code(b'i' + b'\x00' * 10 + b'\x00') == True
assert test_validate_code(b'j' + b'\x00' * 11 + b'\x00') == True
assert test_validate_code(b'k' + b'\x00' * 12 + b'\x00') == True
assert test_validate_code(b'l' + b'\x00' * 13 + b'\x00') == True
assert test_validate_code(b'm' + b'\x00' * 14 + b'\x00') == True
assert test_validate_code(b'n' + b'\x00' * 15 + b'\x00') == True
assert test_validate_code(b'o' + b'\x00' * 16 + b'\x00') == True
assert test_validate_code(b'p' + b'\x00' * 17 + b'\x00') == True
assert test_validate_code(b'q' + b'\x00' * 18 + b'\x00') == True
assert test_validate_code(b'r' + b'\x00' * 19 + b'\x00') == True
assert test_validate_code(b's' + b'\x00' * 20 + b'\x00') == True
assert test_validate_code(b't' + b'\x00' * 21 + b'\x00') == True
assert test_validate_code(b'u' + b'\x00' * 22 + b'\x00') == True
assert test_validate_code(b'v' + b'\x00' * 23 + b'\x00') == True
assert test_validate_code(b'w' + b'\x00' * 24 + b'\x00') == True
assert test_validate_code(b'x' + b'\x00' * 25 + b'\x00') == True
assert test_validate_code(b'y' + b'\x00' * 26 + b'\x00') == True
assert test_validate_code(b'z' + b'\x00' * 27 + b'\x00') == True
assert test_validate_code(b'{' + b'\x00' * 28 + b'\x00') == True
assert test_validate_code(b'|' + b'\x00' * 29 + b'\x00') == True
assert test_validate_code(b'}' + b'\x00' * 30 + b'\x00') == True
assert test_validate_code(b'~' + b'\x00' * 31 + b'\x00') == True
assert test_validate_code(b'\x7f' + b'\x00' * 32 + b'\x00') == True
assert test_validate_code(b'\x00') == True
assert test_validate_code(b'\xf3') == True
assert test_validate_code(b'\xfd') == True
assert test_validate_code(b'\xfe') == True
assert test_validate_code(b'') == False
assert test_validate_code(b'[') == False
assert test_validate_code(b'\x0c\x00') == False
assert test_validate_code(b'\r\x00') == False
assert test_validate_code(b'\x0e\x00') == False
assert test_validate_code(b'\x0f\x00') == False
assert test_validate_code(b'\x1e\x00') == False
assert test_validate_code(b'\x1f\x00') == False
assert test_validate_code(b'!\x00') == False
assert test_validate_code(b'"\x00') == False
assert test_validate_code(b'#\x00') == False
assert test_validate_code(b'$\x00') == False
assert test_validate_code(b'%\x00') == False
assert test_validate_code(b'&\x00') == False
assert test_validate_code(b"'\x00") == False
assert test_validate_code(b'(\x00') == False
assert test_validate_code(b')\x00') == False
assert test_validate_code(b'*\x00') == False
assert test_validate_code(b'+\x00') == False
assert test_validate_code(b',\x00') == False
assert test_validate_code(b'-\x00') == False
assert test_validate_code(b'.\x00') == False
assert test_validate_code(b'/\x00') == False
assert test_validate_code(b'I\x00') == False
assert test_validate_code(b'J\x00') == False
assert test_validate_code(b'K\x00') == False
assert test_validate_code(b'L\x00') == False
assert test_validate_code(b'M\x00') == False
assert test_validate_code(b'N\x00') == False
assert test_validate_code(b'O\x00') == False
assert test_validate_code(b'\\\x00') == False
assert test_validate_code(b']\x00') == False
assert test_validate_code(b'^\x00') == False
assert test_validate_code(b'_\x00') == False
assert test_validate_code(b'\xa5\x00') == False
assert test_validate_code(b'\xa6\x00') == False
assert test_validate_code(b'\xa7\x00') == False
assert test_validate_code(b'\xa8\x00') == False
assert test_validate_code(b'\xa9\x00') == False
assert test_validate_code(b'\xaa\x00') == False
assert test_validate_code(b'\xab\x00') == False
assert test_validate_code(b'\xac\x00') == False
assert test_validate_code(b'\xad\x00') == False
assert test_validate_code(b'\xae\x00') == False
assert test_validate_code(b'\xaf\x00') == False
assert test_validate_code(b'\xb0\x00') == False
assert test_validate_code(b'\xb1\x00') == False
assert test_validate_code(b'\xb2\x00') == False
assert test_validate_code(b'\xb3\x00') == False
assert test_validate_code(b'\xb4\x00') == False
assert test_validate_code(b'\xb5\x00') == False
assert test_validate_code(b'\xb6\x00') == False
assert test_validate_code(b'\xb7\x00') == False
assert test_validate_code(b'\xb8\x00') == False
assert test_validate_code(b'\xb9\x00') == False
assert test_validate_code(b'\xba\x00') == False
assert test_validate_code(b'\xbb\x00') == False
assert test_validate_code(b'\xbc\x00') == False
assert test_validate_code(b'\xbd\x00') == False
assert test_validate_code(b'\xbe\x00') == False
assert test_validate_code(b'\xbf\x00') == False
assert test_validate_code(b'\xc0\x00') == False
assert test_validate_code(b'\xc1\x00') == False
assert test_validate_code(b'\xc2\x00') == False
assert test_validate_code(b'\xc3\x00') == False
assert test_validate_code(b'\xc4\x00') == False
assert test_validate_code(b'\xc5\x00') == False
assert test_validate_code(b'\xc6\x00') == False
assert test_validate_code(b'\xc7\x00') == False
assert test_validate_code(b'\xc8\x00') == False
assert test_validate_code(b'\xc9\x00') == False
assert test_validate_code(b'\xca\x00') == False
assert test_validate_code(b'\xcb\x00') == False
assert test_validate_code(b'\xcc\x00') == False
assert test_validate_code(b'\xcd\x00') == False
assert test_validate_code(b'\xce\x00') == False
assert test_validate_code(b'\xcf\x00') == False
assert test_validate_code(b'\xd0\x00') == False
assert test_validate_code(b'\xd1\x00') == False
assert test_validate_code(b'\xd2\x00') == False
assert test_validate_code(b'\xd3\x00') == False
assert test_validate_code(b'\xd4\x00') == False
assert test_validate_code(b'\xd5\x00') == False
assert test_validate_code(b'\xd6\x00') == False
assert test_validate_code(b'\xd7\x00') == False
assert test_validate_code(b'\xd8\x00') == False
assert test_validate_code(b'\xd9\x00') == False
assert test_validate_code(b'\xda\x00') == False
assert test_validate_code(b'\xdb\x00') == False
assert test_validate_code(b'\xdc\x00') == False
assert test_validate_code(b'\xdd\x00') == False
assert test_validate_code(b'\xde\x00') == False
assert test_validate_code(b'\xdf\x00') == False
assert test_validate_code(b'\xe0\x00') == False
assert test_validate_code(b'\xe1\x00') == False
assert test_validate_code(b'\xe2\x00') == False
assert test_validate_code(b'\xe3\x00') == False
assert test_validate_code(b'\xe4\x00') == False
assert test_validate_code(b'\xe5\x00') == False
assert test_validate_code(b'\xe6\x00') == False
assert test_validate_code(b'\xe7\x00') == False
assert test_validate_code(b'\xe8\x00') == False
assert test_validate_code(b'\xe9\x00') == False
assert test_validate_code(b'\xea\x00') == False
assert test_validate_code(b'\xeb\x00') == False
assert test_validate_code(b'\xec\x00') == False
assert test_validate_code(b'\xed\x00') == False
assert test_validate_code(b'\xee\x00') == False
assert test_validate_code(b'\xef\x00') == False
assert test_validate_code(b'\xf6\x00') == False
assert test_validate_code(b'\xf7\x00') == False
assert test_validate_code(b'\xf8\x00') == False
assert test_validate_code(b'\xf9\x00') == False
assert test_validate_code(b'\xfb\x00') == False
assert test_validate_code(b'\xfc\x00') == False
assert test_validate_code(b'`\x00') == False
assert test_validate_code(b'a' + b'\x00' * 1 + b'\x00') == False
assert test_validate_code(b'b' + b'\x00' * 2 + b'\x00') == False
assert test_validate_code(b'c' + b'\x00' * 3 + b'\x00') == False
assert test_validate_code(b'd' + b'\x00' * 4 + b'\x00') == False
assert test_validate_code(b'e' + b'\x00' * 5 + b'\x00') == False
assert test_validate_code(b'f' + b'\x00' * 6 + b'\x00') == False
assert test_validate_code(b'g' + b'\x00' * 7 + b'\x00') == False
assert test_validate_code(b'h' + b'\x00' * 8 + b'\x00') == False
assert test_validate_code(b'i' + b'\x00' * 9 + b'\x00') == False
assert test_validate_code(b'j' + b'\x00' * 10 + b'\x00') == False
assert test_validate_code(b'k' + b'\x00' * 11 + b'\x00') == False
assert test_validate_code(b'l' + b'\x00' * 12 + b'\x00') == False
assert test_validate_code(b'm' + b'\x00' * 13 + b'\x00') == False
assert test_validate_code(b'n' + b'\x00' * 14 + b'\x00') == False
assert test_validate_code(b'o' + b'\x00' * 15 + b'\x00') == False
assert test_validate_code(b'p' + b'\x00' * 16 + b'\x00') == False
assert test_validate_code(b'q' + b'\x00' * 17 + b'\x00') == False
assert test_validate_code(b'r' + b'\x00' * 18 + b'\x00') == False
assert test_validate_code(b's' + b'\x00' * 19 + b'\x00') == False
assert test_validate_code(b't' + b'\x00' * 20 + b'\x00') == False
assert test_validate_code(b'u' + b'\x00' * 21 + b'\x00') == False
assert test_validate_code(b'v' + b'\x00' * 22 + b'\x00') == False
assert test_validate_code(b'w' + b'\x00' * 23 + b'\x00') == False
assert test_validate_code(b'x' + b'\x00' * 24 + b'\x00') == False
assert test_validate_code(b'y' + b'\x00' * 25 + b'\x00') == False
assert test_validate_code(b'z' + b'\x00' * 26 + b'\x00') == False
assert test_validate_code(b'{' + b'\x00' * 27 + b'\x00') == False
assert test_validate_code(b'|' + b'\x00' * 28 + b'\x00') == False
assert test_validate_code(b'}' + b'\x00' * 29 + b'\x00') == False
assert test_validate_code(b'~' + b'\x00' * 30 + b'\x00') == False
assert test_validate_code(b'\x7f' + b'\x00' * 31 + b'\x00') == False
|
QUESTIONS = {
'a1': {
'Q': 'What is the chemical symbol for gold?',
'A': 'au'
},
'a2': {
'Q': '',
'A': ''
},
'a3': {
'Q': '',
'A': ''
},
'a4': {
'Q': '',
'A': ''
},
'b1': {
'Q': '',
'A': ''
},
'b2': {
'Q': '',
'A': ''
},
'b3': {
'Q': '',
'A': ''
},
'b4': {
'Q': '',
'A': ''
},
'c1': {
'Q': '',
'A': ''
},
'c2': {
'Q': '',
'A': ''
},
'c3': {
'Q': '',
'A': ''
},
'c4': {
'Q': '',
'A': ''
},
'd1': {
'Q': '',
'A': ''
},
'd2': {
'Q': '',
'A': ''
},
'd3': {
'Q': '',
'A': ''
},
'd4': {
'Q': '',
'A': ''
},
}
|
questions = {'a1': {'Q': 'What is the chemical symbol for gold?', 'A': 'au'}, 'a2': {'Q': '', 'A': ''}, 'a3': {'Q': '', 'A': ''}, 'a4': {'Q': '', 'A': ''}, 'b1': {'Q': '', 'A': ''}, 'b2': {'Q': '', 'A': ''}, 'b3': {'Q': '', 'A': ''}, 'b4': {'Q': '', 'A': ''}, 'c1': {'Q': '', 'A': ''}, 'c2': {'Q': '', 'A': ''}, 'c3': {'Q': '', 'A': ''}, 'c4': {'Q': '', 'A': ''}, 'd1': {'Q': '', 'A': ''}, 'd2': {'Q': '', 'A': ''}, 'd3': {'Q': '', 'A': ''}, 'd4': {'Q': '', 'A': ''}}
|
#Multilevel Inner Classes
#In multilevel inner classes, the inner class contains another class which inner classes to the previous one.
class Outer:
"""Outer Class"""
def __init__(self):
## instantiating the 'Inner' class
self.inner = self.Inner()
## instantiating the multilevel 'InnerInner' class
self.innerinner = self.inner.InnerInner()
def show_classes(self):
print("This is Outer class's function")
self.inner.inner_display('message 1 ' )
self.innerinner.inner_display('message 3' )
## inner class
class Inner:
"""First Inner Class"""
def inner_display(self, msg):
print("This is Inner class's function")
print(msg)
def __init__(self):
## instantiating the 'InnerInner' class
self.innerinner = self.InnerInner()
def show_classes(self):
print("This is Inner class's function ")
self.innerinner.inner_display('message 2 ' )
## multilevel inner class
class InnerInner:
def inner_display(self, msg):
print("This is Inner's Inner class function")
print(msg)
c1 = Outer()
c1.show_classes()
c1.Inner().show_classes()
#output
'''
This is Outer class's function
This is Inner class's function
message 1
This is Inner's Inner class function
message 3
This is Inner class's function
This is Inner's Inner class function
message 2
'''
|
class Outer:
"""Outer Class"""
def __init__(self):
self.inner = self.Inner()
self.innerinner = self.inner.InnerInner()
def show_classes(self):
print("This is Outer class's function")
self.inner.inner_display('message 1 ')
self.innerinner.inner_display('message 3')
class Inner:
"""First Inner Class"""
def inner_display(self, msg):
print("This is Inner class's function")
print(msg)
def __init__(self):
self.innerinner = self.InnerInner()
def show_classes(self):
print("This is Inner class's function ")
self.innerinner.inner_display('message 2 ')
class Innerinner:
def inner_display(self, msg):
print("This is Inner's Inner class function")
print(msg)
c1 = outer()
c1.show_classes()
c1.Inner().show_classes()
"\nThis is Outer class's function\nThis is Inner class's function\nmessage 1 \nThis is Inner's Inner class function\nmessage 3\nThis is Inner class's function \nThis is Inner's Inner class function\nmessage 2 \n"
|
#!/usr/bin/python3
'''
Collects Weather Forecast by Indian Meterological Department, by parsing webpages :)
'''
__version__ = '0.2.0'
__author__ = 'Anjan Roy<anjanroy@yandex.com>'
|
"""
Collects Weather Forecast by Indian Meterological Department, by parsing webpages :)
"""
__version__ = '0.2.0'
__author__ = 'Anjan Roy<anjanroy@yandex.com>'
|
# Contains all the basic info about awards
class Award:
count = 0
def __init__(self, url, number, name, type, application, restrictions, renewable, value, due, description,
sequence):
self.url = url
self.number = number
self.name = name
self.type = type
self.application = application
self.restrictions = restrictions
self.renewable = renewable
self.value = value
self.due = due
self.description = description
self.sequence = sequence
Award.count += 1
def displayCount(self):
return "There are a total of %d awards" % Award.count
def displayAward(self):
return "Award Number: ", self.number, ", Name: ", self.name, ", Type: ", self.type, ", Application: ", self.application, ", Restrictions: ", self.restrictions, ", Renewable: ", self.renewable, ", Value: ", self.value, ", Due Day: ", self.due, ", description: ", self.description, ", URL: ", self.url
|
class Award:
count = 0
def __init__(self, url, number, name, type, application, restrictions, renewable, value, due, description, sequence):
self.url = url
self.number = number
self.name = name
self.type = type
self.application = application
self.restrictions = restrictions
self.renewable = renewable
self.value = value
self.due = due
self.description = description
self.sequence = sequence
Award.count += 1
def display_count(self):
return 'There are a total of %d awards' % Award.count
def display_award(self):
return ('Award Number: ', self.number, ', Name: ', self.name, ', Type: ', self.type, ', Application: ', self.application, ', Restrictions: ', self.restrictions, ', Renewable: ', self.renewable, ', Value: ', self.value, ', Due Day: ', self.due, ', description: ', self.description, ', URL: ', self.url)
|
"""
"""
load("@bazel_skylib//lib:paths.bzl", "paths")
load("@fbcode_macros//build_defs/lib/thrift:thrift_interface.bzl", "thrift_interface")
load("@fbcode_macros//build_defs/lib:common_paths.bzl", "common_paths")
load("@fbcode_macros//build_defs/lib:src_and_dep_helpers.bzl", "src_and_dep_helpers")
load("@fbcode_macros//build_defs/lib:thrift_common.bzl", "thrift_common")
load("@fbsource//tools/build_defs:fb_native_wrapper.bzl", "fb_native")
def _get_lang():
return "js"
def _get_names():
return ("js",)
def _get_generated_sources(
base_path,
name,
thrift_src,
services,
options,
**_kwargs):
_ignore = base_path
_ignore = name
thrift_base = paths.split_extension(paths.basename(thrift_src))[0]
genfiles = []
genfiles.append("%s_types.js" % thrift_base)
for service in services:
genfiles.append("%s.js" % service)
out_dir = "gen-nodejs" if "node" in options else "gen-js"
return {
paths.join("node_modules", thrift_base, path): paths.join(out_dir, path)
for path in genfiles
}
def _get_language_rule(
base_path,
name,
thrift_srcs,
options,
sources_map,
deps,
visibility = None,
**_kwargs):
_ignore = base_path
_ignore = thrift_srcs
_ignore = options
sources = thrift_common.merge_sources_map(sources_map)
cmds = []
for dep in deps:
cmds.append('rsync -a $(location {})/ "$OUT"'.format(dep))
for dst, raw_src in sources.items():
src = src_and_dep_helpers.get_source_name(raw_src)
dst = paths.join('"$OUT"', dst)
cmds.append("mkdir -p {}".format(paths.dirname(dst)))
cmds.append("cp {} {}".format(paths.basename(src), dst))
fb_native.genrule(
name = name,
visibility = visibility,
out = common_paths.CURRENT_DIRECTORY,
labels = ["generated"],
srcs = sources.values(),
cmd = " && ".join(cmds),
)
js_thrift_converter = thrift_interface.make(
get_lang = _get_lang,
get_names = _get_names,
get_generated_sources = _get_generated_sources,
get_language_rule = _get_language_rule,
)
|
"""
"""
load('@bazel_skylib//lib:paths.bzl', 'paths')
load('@fbcode_macros//build_defs/lib/thrift:thrift_interface.bzl', 'thrift_interface')
load('@fbcode_macros//build_defs/lib:common_paths.bzl', 'common_paths')
load('@fbcode_macros//build_defs/lib:src_and_dep_helpers.bzl', 'src_and_dep_helpers')
load('@fbcode_macros//build_defs/lib:thrift_common.bzl', 'thrift_common')
load('@fbsource//tools/build_defs:fb_native_wrapper.bzl', 'fb_native')
def _get_lang():
return 'js'
def _get_names():
return ('js',)
def _get_generated_sources(base_path, name, thrift_src, services, options, **_kwargs):
_ignore = base_path
_ignore = name
thrift_base = paths.split_extension(paths.basename(thrift_src))[0]
genfiles = []
genfiles.append('%s_types.js' % thrift_base)
for service in services:
genfiles.append('%s.js' % service)
out_dir = 'gen-nodejs' if 'node' in options else 'gen-js'
return {paths.join('node_modules', thrift_base, path): paths.join(out_dir, path) for path in genfiles}
def _get_language_rule(base_path, name, thrift_srcs, options, sources_map, deps, visibility=None, **_kwargs):
_ignore = base_path
_ignore = thrift_srcs
_ignore = options
sources = thrift_common.merge_sources_map(sources_map)
cmds = []
for dep in deps:
cmds.append('rsync -a $(location {})/ "$OUT"'.format(dep))
for (dst, raw_src) in sources.items():
src = src_and_dep_helpers.get_source_name(raw_src)
dst = paths.join('"$OUT"', dst)
cmds.append('mkdir -p {}'.format(paths.dirname(dst)))
cmds.append('cp {} {}'.format(paths.basename(src), dst))
fb_native.genrule(name=name, visibility=visibility, out=common_paths.CURRENT_DIRECTORY, labels=['generated'], srcs=sources.values(), cmd=' && '.join(cmds))
js_thrift_converter = thrift_interface.make(get_lang=_get_lang, get_names=_get_names, get_generated_sources=_get_generated_sources, get_language_rule=_get_language_rule)
|
# Cracking the Coding Interview 6th Edition
# Chapter 1 - Arrays and Strings. Page 88
# Question 1.2
# Solved by Yong Lin Wang
"""
Given two strings, write a method to decide if one is a permutation of the other.
"""
def check_permutation(str1, str2):
"""
If two strings are permutation to one another, they should have the same
characters. This solution evaluates the sum of the orders of the strings
if they are the same then they are permutation to one another, otherwise,
they are not and I am a fucking retard that cant get any shit done properly
i am such a failure in life that I cant do anything right. :(
"""
ord1 = 0
ord2 = 0
for char in str1:
ord1 += ord(char)
for char in str2:
ord2 += ord(char)
return ord1 == ord2
|
"""
Given two strings, write a method to decide if one is a permutation of the other.
"""
def check_permutation(str1, str2):
"""
If two strings are permutation to one another, they should have the same
characters. This solution evaluates the sum of the orders of the strings
if they are the same then they are permutation to one another, otherwise,
they are not and I am a fucking retard that cant get any shit done properly
i am such a failure in life that I cant do anything right. :(
"""
ord1 = 0
ord2 = 0
for char in str1:
ord1 += ord(char)
for char in str2:
ord2 += ord(char)
return ord1 == ord2
|
class Solution:
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if (not nums):
return None
n = len(nums)
result = [1] * n
prod = 1
for i in range(n):
result[i] = result[i] * prod
prod = prod * nums[i]
prod = 1
for i in range(n-1,-1,-1):
result[i] = result[i] * prod
prod = prod * nums[i]
return result
|
class Solution:
def product_except_self(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if not nums:
return None
n = len(nums)
result = [1] * n
prod = 1
for i in range(n):
result[i] = result[i] * prod
prod = prod * nums[i]
prod = 1
for i in range(n - 1, -1, -1):
result[i] = result[i] * prod
prod = prod * nums[i]
return result
|
class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
warmer_day = [0]*len(T)
recent_day = [2**31-1]*101
MAXLEN = 30000
for i in range(len(T)-1, -1, -1):
minday = 2**31-1
for warmer_temp in range(T[i]+1, 101):
if recent_day[warmer_temp] <= MAXLEN:
minday = min(minday, recent_day[warmer_temp]-i)
if minday <= MAXLEN:
warmer_day[i] = minday
recent_day[T[i]] = i
return warmer_day
|
class Solution:
def daily_temperatures(self, T: List[int]) -> List[int]:
warmer_day = [0] * len(T)
recent_day = [2 ** 31 - 1] * 101
maxlen = 30000
for i in range(len(T) - 1, -1, -1):
minday = 2 ** 31 - 1
for warmer_temp in range(T[i] + 1, 101):
if recent_day[warmer_temp] <= MAXLEN:
minday = min(minday, recent_day[warmer_temp] - i)
if minday <= MAXLEN:
warmer_day[i] = minday
recent_day[T[i]] = i
return warmer_day
|
# encoding: utf-8
class Animals(object):
def __init__(self, sound):
self.sound = sound
def speak(self):
return self.sound
|
class Animals(object):
def __init__(self, sound):
self.sound = sound
def speak(self):
return self.sound
|
"""Top-level package for Calorimeter."""
__author__ = """Jonathon Vandezande"""
__email__ = 'jevandezande@gmail.com'
__version__ = '0.2.1'
|
"""Top-level package for Calorimeter."""
__author__ = 'Jonathon Vandezande'
__email__ = 'jevandezande@gmail.com'
__version__ = '0.2.1'
|
f = open('graph.dot')
def find_between( s, first, last ):
try:
start = s.index( first ) + len( first )
end = s.index( last, start )
return s[start:end]
except ValueError:
return ""
s1 = "digraph "
s2 = """
{
graph [ rankdir="RL" ]
"""
s3 = "}"
for line in f:
name = find_between(line, 'label="', '\\n')
g = open(name+'.dot', 'w')
res = s1 + name + s2 + line + s3
g.write(res)
g.close()
f.close()
|
f = open('graph.dot')
def find_between(s, first, last):
try:
start = s.index(first) + len(first)
end = s.index(last, start)
return s[start:end]
except ValueError:
return ''
s1 = 'digraph '
s2 = '\n{\ngraph [ rankdir="RL" ]\n'
s3 = '}'
for line in f:
name = find_between(line, 'label="', '\\n')
g = open(name + '.dot', 'w')
res = s1 + name + s2 + line + s3
g.write(res)
g.close()
f.close()
|
# Copyright 2021 Nokia
# Licensed under the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
class ApiVersion(object):
def __init__(self, group: str, version: str):
self.group = group
self.version = version
class Kind(ApiVersion):
def __init__(self, group: str, version: str, kind: str):
super().__init__(group, version)
self.kind = kind
class Resource(ApiVersion):
def __init__(self, group: str, version: str, kind: str):
super().__init__(group, version)
self.resource = kind
def parse_api_version(api_version: str) -> ApiVersion:
if '/' in api_version:
return ApiVersion(*api_version.split('/', 1))
return ApiVersion('', api_version)
|
class Apiversion(object):
def __init__(self, group: str, version: str):
self.group = group
self.version = version
class Kind(ApiVersion):
def __init__(self, group: str, version: str, kind: str):
super().__init__(group, version)
self.kind = kind
class Resource(ApiVersion):
def __init__(self, group: str, version: str, kind: str):
super().__init__(group, version)
self.resource = kind
def parse_api_version(api_version: str) -> ApiVersion:
if '/' in api_version:
return api_version(*api_version.split('/', 1))
return api_version('', api_version)
|
class Accessor(object):
""""""
pass
class WriteThru(Accessor):
"""Implement write-thru access pattern."""
pass
class WriteAround(Accessor):
"""Implement write-around access pattern."""
pass
class WriteBack(Accessor):
"""Implement write-back access pattern."""
pass
|
class Accessor(object):
""""""
pass
class Writethru(Accessor):
"""Implement write-thru access pattern."""
pass
class Writearound(Accessor):
"""Implement write-around access pattern."""
pass
class Writeback(Accessor):
"""Implement write-back access pattern."""
pass
|
_base_ = '../cascade_rcnn/cascade_mask_rcnn_r50_fpn_mstrain_3x_coco.py'
model = dict(
backbone=dict(
type='ResNeXt',
depth=101,
groups=32,
base_width=8,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=False),
style='pytorch',
init_cfg=dict(
type='Pretrained',
checkpoint='open-mmlab://detectron2/resnext101_32x8d')),
roi_head=dict(
_delete_=True,
type='KeypointCascadeRoIHead',
output_heatmaps=False,
keypoint_decoder=dict(type='HeatmapDecodeOneKeypoint', upscale=4),
num_keypoints=5,
num_stages=3,
stage_loss_weights=[1, 0.5, 0.25],
bbox_roi_extractor=dict(
type='SingleRoIExtractor',
roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0),
out_channels=256,
featmap_strides=[4, 8, 16, 32]),
bbox_head=[
dict(
type='Shared2FCBBoxHead',
in_channels=256,
fc_out_channels=1024,
roi_feat_size=7,
num_classes=80,
bbox_coder=dict(
type='DeltaXYWHBBoxCoder',
target_means=[0., 0., 0., 0.],
target_stds=[0.1, 0.1, 0.2, 0.2]),
reg_class_agnostic=True,
loss_cls=dict(
type='CrossEntropyLoss',
use_sigmoid=False,
loss_weight=1.0),
loss_bbox=dict(type='SmoothL1Loss', beta=1.0,
loss_weight=1.0)),
dict(
type='Shared2FCBBoxHead',
in_channels=256,
fc_out_channels=1024,
roi_feat_size=7,
num_classes=80,
bbox_coder=dict(
type='DeltaXYWHBBoxCoder',
target_means=[0., 0., 0., 0.],
target_stds=[0.05, 0.05, 0.1, 0.1]),
reg_class_agnostic=True,
loss_cls=dict(
type='CrossEntropyLoss',
use_sigmoid=False,
loss_weight=1.0),
loss_bbox=dict(type='SmoothL1Loss', beta=1.0,
loss_weight=1.0)),
dict(
type='Shared2FCBBoxHead',
in_channels=256,
fc_out_channels=1024,
roi_feat_size=7,
num_classes=80,
bbox_coder=dict(
type='DeltaXYWHBBoxCoder',
target_means=[0., 0., 0., 0.],
target_stds=[0.033, 0.033, 0.067, 0.067]),
reg_class_agnostic=True,
loss_cls=dict(
type='CrossEntropyLoss',
use_sigmoid=False,
loss_weight=1.0),
loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0))
],
mask_roi_extractor=dict(
type='SingleRoIExtractor',
roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=0),
out_channels=256,
featmap_strides=[4, 8, 16, 32]),
mask_head=dict(
type='FCNMaskHead',
num_convs=4,
in_channels=256,
conv_out_channels=256,
num_classes=80,
loss_mask=dict(
type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)))
)
|
_base_ = '../cascade_rcnn/cascade_mask_rcnn_r50_fpn_mstrain_3x_coco.py'
model = dict(backbone=dict(type='ResNeXt', depth=101, groups=32, base_width=8, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=False), style='pytorch', init_cfg=dict(type='Pretrained', checkpoint='open-mmlab://detectron2/resnext101_32x8d')), roi_head=dict(_delete_=True, type='KeypointCascadeRoIHead', output_heatmaps=False, keypoint_decoder=dict(type='HeatmapDecodeOneKeypoint', upscale=4), num_keypoints=5, num_stages=3, stage_loss_weights=[1, 0.5, 0.25], bbox_roi_extractor=dict(type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32]), bbox_head=[dict(type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict(type='DeltaXYWHBBoxCoder', target_means=[0.0, 0.0, 0.0, 0.0], target_stds=[0.1, 0.1, 0.2, 0.2]), reg_class_agnostic=True, loss_cls=dict(type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), dict(type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict(type='DeltaXYWHBBoxCoder', target_means=[0.0, 0.0, 0.0, 0.0], target_stds=[0.05, 0.05, 0.1, 0.1]), reg_class_agnostic=True, loss_cls=dict(type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), dict(type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict(type='DeltaXYWHBBoxCoder', target_means=[0.0, 0.0, 0.0, 0.0], target_stds=[0.033, 0.033, 0.067, 0.067]), reg_class_agnostic=True, loss_cls=dict(type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0))], mask_roi_extractor=dict(type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32]), mask_head=dict(type='FCNMaskHead', num_convs=4, in_channels=256, conv_out_channels=256, num_classes=80, loss_mask=dict(type='CrossEntropyLoss', use_mask=True, loss_weight=1.0))))
|
def find_missing(S):
if len(S) > 0:
m = max(S)
vals = [ 0 for i in range(m)]
for x in S:
if x < 0:
print("Warning {} is <0. Ignoring it.".format(x))
else:
vals[x-1] += 1
return [x+1 for x in range(m) if vals[x] == 0]
else:
print("Warning: list is empty. Returning None")
if __name__ == "__main__":
S = [1,9,7, 7, 4, 3, 3, 3]
S1 = list(range(10))
print(find_missing(S))
print(find_missing(S1))
print(find_missing([]))
S2 = [1, -72, 4, -3, -3, 3,10]
M = find_missing(S2)
print(M)
|
def find_missing(S):
if len(S) > 0:
m = max(S)
vals = [0 for i in range(m)]
for x in S:
if x < 0:
print('Warning {} is <0. Ignoring it.'.format(x))
else:
vals[x - 1] += 1
return [x + 1 for x in range(m) if vals[x] == 0]
else:
print('Warning: list is empty. Returning None')
if __name__ == '__main__':
s = [1, 9, 7, 7, 4, 3, 3, 3]
s1 = list(range(10))
print(find_missing(S))
print(find_missing(S1))
print(find_missing([]))
s2 = [1, -72, 4, -3, -3, 3, 10]
m = find_missing(S2)
print(M)
|
def solution(inpnum):
upnum = int(str(9)*inpnum)
lownum = int(str(1)+(str(0)*(inpnum-1)))
ansnum = None
for i in range(upnum,lownum,-1):
if len(str(i))==len(set(str(i))):
if 2**(i-1)%i==1:
ansnum = i
break
return ansnum
|
def solution(inpnum):
upnum = int(str(9) * inpnum)
lownum = int(str(1) + str(0) * (inpnum - 1))
ansnum = None
for i in range(upnum, lownum, -1):
if len(str(i)) == len(set(str(i))):
if 2 ** (i - 1) % i == 1:
ansnum = i
break
return ansnum
|
def visualize(**images):
"""PLot images in one row."""
n = len(images)
plt.figure(figsize=(16, 5))
for i, (name, image) in enumerate(images.items()):
plt.subplot(1, n, i + 1)
plt.xticks([])
plt.yticks([])
plt.title(' '.join(name.split('_')).title())
plt.imshow(image)
plt.show()
def guided_filter(data, width=image_size, height=image_size, channel=num_channels):
r = 15
eps = 1.0
batch_q = np.zeros((height, width, channel))
for j in range(channel):
I = data[:, :, j]
p = data[:, :, j]
ones_array = np.ones([height, width])
N = cv2.boxFilter(ones_array, -1, (2 * r + 1, 2 * r + 1), normalize=False, borderType=0)
mean_I = cv2.boxFilter(I, -1, (2 * r + 1, 2 * r + 1), normalize=False, borderType=0) / N
mean_p = cv2.boxFilter(p, -1, (2 * r + 1, 2 * r + 1), normalize=False, borderType=0) / N
mean_Ip = cv2.boxFilter(I * p, -1, (2 * r + 1, 2 * r + 1), normalize=False, borderType=0) / N
cov_Ip = mean_Ip - mean_I * mean_p
mean_II = cv2.boxFilter(I * I, -1, (2 * r + 1, 2 * r + 1), normalize=False, borderType=0) / N
var_I = mean_II - mean_I * mean_I
a = cov_Ip / (var_I + eps)
b = mean_p - a * mean_I
mean_a = cv2.boxFilter(a, -1, (2 * r + 1, 2 * r + 1), normalize=False, borderType=0) / N
mean_b = cv2.boxFilter(b, -1, (2 * r + 1, 2 * r + 1), normalize=False, borderType=0) / N
q = mean_a * I + mean_b
batch_q[:, :, j] = q
return batch_q
|
def visualize(**images):
"""PLot images in one row."""
n = len(images)
plt.figure(figsize=(16, 5))
for (i, (name, image)) in enumerate(images.items()):
plt.subplot(1, n, i + 1)
plt.xticks([])
plt.yticks([])
plt.title(' '.join(name.split('_')).title())
plt.imshow(image)
plt.show()
def guided_filter(data, width=image_size, height=image_size, channel=num_channels):
r = 15
eps = 1.0
batch_q = np.zeros((height, width, channel))
for j in range(channel):
i = data[:, :, j]
p = data[:, :, j]
ones_array = np.ones([height, width])
n = cv2.boxFilter(ones_array, -1, (2 * r + 1, 2 * r + 1), normalize=False, borderType=0)
mean_i = cv2.boxFilter(I, -1, (2 * r + 1, 2 * r + 1), normalize=False, borderType=0) / N
mean_p = cv2.boxFilter(p, -1, (2 * r + 1, 2 * r + 1), normalize=False, borderType=0) / N
mean__ip = cv2.boxFilter(I * p, -1, (2 * r + 1, 2 * r + 1), normalize=False, borderType=0) / N
cov__ip = mean_Ip - mean_I * mean_p
mean_ii = cv2.boxFilter(I * I, -1, (2 * r + 1, 2 * r + 1), normalize=False, borderType=0) / N
var_i = mean_II - mean_I * mean_I
a = cov_Ip / (var_I + eps)
b = mean_p - a * mean_I
mean_a = cv2.boxFilter(a, -1, (2 * r + 1, 2 * r + 1), normalize=False, borderType=0) / N
mean_b = cv2.boxFilter(b, -1, (2 * r + 1, 2 * r + 1), normalize=False, borderType=0) / N
q = mean_a * I + mean_b
batch_q[:, :, j] = q
return batch_q
|
class Solution:
def toHex(self, num: int) -> str:
if num == 0:
return '0'
chars, result = '0123456789abcdef', []
if num < 0:
num += (1 << 32)
while num > 0:
result.insert(0, chars[num % 16])
num //= 16
return ''.join(result)
|
class Solution:
def to_hex(self, num: int) -> str:
if num == 0:
return '0'
(chars, result) = ('0123456789abcdef', [])
if num < 0:
num += 1 << 32
while num > 0:
result.insert(0, chars[num % 16])
num //= 16
return ''.join(result)
|
#!/usr/bin/python3
""" Class check module
Functions:
is_kind_of_class: checks if obj is inherit
from determined class
"""
def is_kind_of_class(obj, a_class):
""" checks class inheritance
Args:
obj: object to evaluate
a_class: suspect father
"""
return isinstance(obj, a_class)
|
""" Class check module
Functions:
is_kind_of_class: checks if obj is inherit
from determined class
"""
def is_kind_of_class(obj, a_class):
""" checks class inheritance
Args:
obj: object to evaluate
a_class: suspect father
"""
return isinstance(obj, a_class)
|
# Space: O(1)
# Time: O(n)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def diameterOfBinaryTree(self, root):
self.res = 0
self.dfs(root)
return self.res
def dfs(self, root):
if root is None: return 0
left, right = 0, 0
if root.left:
left = self.dfs(root.left) + 1
if root.right:
right = self.dfs(root.right) + 1
self.res = max(self.res, left + right)
return max(left, right)
|
class Solution:
def diameter_of_binary_tree(self, root):
self.res = 0
self.dfs(root)
return self.res
def dfs(self, root):
if root is None:
return 0
(left, right) = (0, 0)
if root.left:
left = self.dfs(root.left) + 1
if root.right:
right = self.dfs(root.right) + 1
self.res = max(self.res, left + right)
return max(left, right)
|
try:
n = int(input("Enter number"))
print(n*n)
except:
print("Non integer entered")
|
try:
n = int(input('Enter number'))
print(n * n)
except:
print('Non integer entered')
|
height = int(input())
for i in range(0,height+1):
for j in range(0,i+1):
if(j == i):
print(i,end=" ")
else:
print("*",end=" ")
print()
# Sample Input :- 5
# Output :-
# 0
# * 1
# * * 2
# * * * 3
# * * * * 4
# * * * * * 5
|
height = int(input())
for i in range(0, height + 1):
for j in range(0, i + 1):
if j == i:
print(i, end=' ')
else:
print('*', end=' ')
print()
|
statement_one = False
statement_two = True
credits = 120
gpa = 1.8
if not credits >= 120:
print('You do not have enough credits to graduate.')
if not gpa >= 2.0:
print('Your GPA is not high enough to graduate.')
if not (credits >= 120) and not (gpa >= 2.0):
print('You do not meet either requirement to graduate!')
|
statement_one = False
statement_two = True
credits = 120
gpa = 1.8
if not credits >= 120:
print('You do not have enough credits to graduate.')
if not gpa >= 2.0:
print('Your GPA is not high enough to graduate.')
if not credits >= 120 and (not gpa >= 2.0):
print('You do not meet either requirement to graduate!')
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Day 8: Dictionaries and Maps
Source : https://www.hackerrank.com/challenges/30-dictionaries-and-maps/problem
"""
n = int(input())
book = dict([input().split() for _ in range(n)])
for _ in range(n):
name = input()
print("%s=%s" % (name, book[name]) if name in book else "Not found")
|
"""Day 8: Dictionaries and Maps
Source : https://www.hackerrank.com/challenges/30-dictionaries-and-maps/problem
"""
n = int(input())
book = dict([input().split() for _ in range(n)])
for _ in range(n):
name = input()
print('%s=%s' % (name, book[name]) if name in book else 'Not found')
|
LOCALHOST_EQUIVALENTS = frozenset((
'localhost',
'127.0.0.1',
'0.0.0.0',
'0:0:0:0:0:0:0:0',
'0:0:0:0:0:0:0:1',
'::1',
'::',
))
|
localhost_equivalents = frozenset(('localhost', '127.0.0.1', '0.0.0.0', '0:0:0:0:0:0:0:0', '0:0:0:0:0:0:0:1', '::1', '::'))
|
count = int(input())
for i in range(count):
print("@"*(count*5))
for i in range(count*3):
print("@"*(count)," "*(count*3),"@"*(count),sep="")
for i in range(count):
print("@"*(count*5))
|
count = int(input())
for i in range(count):
print('@' * (count * 5))
for i in range(count * 3):
print('@' * count, ' ' * (count * 3), '@' * count, sep='')
for i in range(count):
print('@' * (count * 5))
|
a = input("Enter some list of numbers =")
for i in a:
print(i)
print(type(a))
|
a = input('Enter some list of numbers =')
for i in a:
print(i)
print(type(a))
|
# Cache bitcode
CACHE = False
# Save object file for module
ASM = False
# Write LLVM dump to file
DUMP = True
# Enable AST debugging dump
DEBUG = True
# Write dump files to same directory as module?
# if False, this will write all dumps to one "debug" file in the main dir
DUMP_TO_DIR = False
|
cache = False
asm = False
dump = True
debug = True
dump_to_dir = False
|
"""
Batch processing examples - Griatch 2012
"""
|
"""
Batch processing examples - Griatch 2012
"""
|
'''
Common settings for using in a project scope
'''
MODEL_ZIP_FILE_NAME_ENV_VAR = 'TF_AWS_MODEL_ZIP_FILE_NAME'
MODEL_PROTOBUF_FILE_NAME_ENV_VAR = 'TF_AWS_MODEL_PROTOBUF_FILE_NAME'
S3_MODEL_BUCKET_NAME_ENV_VAR = 'TF_AWS_S3_MODEL_BUCKET_NAME'
|
"""
Common settings for using in a project scope
"""
model_zip_file_name_env_var = 'TF_AWS_MODEL_ZIP_FILE_NAME'
model_protobuf_file_name_env_var = 'TF_AWS_MODEL_PROTOBUF_FILE_NAME'
s3_model_bucket_name_env_var = 'TF_AWS_S3_MODEL_BUCKET_NAME'
|
expected_output = {
'pid': 'CISCO3945-CHASSIS',
'os': 'ios',
'platform': 'c3900',
'version': '15.0(1)M7',
}
|
expected_output = {'pid': 'CISCO3945-CHASSIS', 'os': 'ios', 'platform': 'c3900', 'version': '15.0(1)M7'}
|
class RobertException(Exception):
def __init__(self, message: str = None):
message = 'An fatal error has occurred' if message is None else message
super().__init__(message)
class LanguageNotSupported(RobertException):
def __init__(self):
super().__init__('That language is not supported')
class UnknownSafeSearchType(RobertException):
def __init__(self, type):
super().__init__(f'Safe search {type} does not exist')
|
class Robertexception(Exception):
def __init__(self, message: str=None):
message = 'An fatal error has occurred' if message is None else message
super().__init__(message)
class Languagenotsupported(RobertException):
def __init__(self):
super().__init__('That language is not supported')
class Unknownsafesearchtype(RobertException):
def __init__(self, type):
super().__init__(f'Safe search {type} does not exist')
|
# TODO: Use these simplified dataclasses once support for Python 3.6 is
# dropped. Meanwhile we'll use the "polyfill" classes defined below.
#
# from dataclasses import dataclass, field
#
# @dataclass
# class Client:
# user_id: str
# user_type: str = field(default="client", init=False)
#
#
# @dataclass
# class Team:
# user_id: str
# user_type: str = field(default="team", init=False)
#
#
# @dataclass
# class User:
# user_id: str
# user_type: str = field(default="user", init=False)
class Client:
user_id: str
user_type: str
def __init__(self, user_id):
self.user_id = user_id
self.user_type = "client"
class Team:
user_id: str
user_type: str
def __init__(self, user_id):
self.user_id = user_id
self.user_type = "team"
class User:
user_id: str
user_type: str
def __init__(self, user_id):
self.user_id = user_id
self.user_type = "user"
def asdict(obj):
return obj.__dict__
|
class Client:
user_id: str
user_type: str
def __init__(self, user_id):
self.user_id = user_id
self.user_type = 'client'
class Team:
user_id: str
user_type: str
def __init__(self, user_id):
self.user_id = user_id
self.user_type = 'team'
class User:
user_id: str
user_type: str
def __init__(self, user_id):
self.user_id = user_id
self.user_type = 'user'
def asdict(obj):
return obj.__dict__
|
def update_dict(old_dict, values):
""" Update dictionary without change the original object """
new_dict = old_dict.copy()
new_dict.update(values)
return new_dict
|
def update_dict(old_dict, values):
""" Update dictionary without change the original object """
new_dict = old_dict.copy()
new_dict.update(values)
return new_dict
|
add = 3+2
print (add)
subtract = 3-2
print (subtract)
multiply = 3*2
print (multiply)
division = 3/2
print (division)
modulus = 3%2
print (modulus)
lessThan = 3<2
print (lessThan)
greaterThan = 3>2
print(greaterThan)
equals = 3==3
print (equals)
logicalAnd = (2==2) and (3==3) and (4==4)
print (logicalAnd)
logicalOr = (2==1) or (2==2) or (2==3)
print (logicalOr)
logicalNot = not (3==2)
print (logicalNot)
|
add = 3 + 2
print(add)
subtract = 3 - 2
print(subtract)
multiply = 3 * 2
print(multiply)
division = 3 / 2
print(division)
modulus = 3 % 2
print(modulus)
less_than = 3 < 2
print(lessThan)
greater_than = 3 > 2
print(greaterThan)
equals = 3 == 3
print(equals)
logical_and = 2 == 2 and 3 == 3 and (4 == 4)
print(logicalAnd)
logical_or = 2 == 1 or 2 == 2 or 2 == 3
print(logicalOr)
logical_not = not 3 == 2
print(logicalNot)
|
#!/usr/bin/env python3
#variable delaration
names = []
address = []
age = []
institute = []
dept = []
print('------+++++++Welcome to student info software+++++++------\n')
names.insert(0, input('Enter your Full name: '))
address.insert(0, input('Enter your Address: '))
age.insert(0, input('Enter your Age: '))
institute.insert(0, input('Enter your School: '))
dept.insert(0, input('Enter your Departiment: '))
print('\n\n')
print('-----+++++Your information is below+++++-----\n')
print("Name is: {} \nAddress is: {} \nAge is: {} \nInstitute is: {} \nDept is: {}".format(names,address,age,institute,dept))
|
names = []
address = []
age = []
institute = []
dept = []
print('------+++++++Welcome to student info software+++++++------\n')
names.insert(0, input('Enter your Full name: '))
address.insert(0, input('Enter your Address: '))
age.insert(0, input('Enter your Age: '))
institute.insert(0, input('Enter your School: '))
dept.insert(0, input('Enter your Departiment: '))
print('\n\n')
print('-----+++++Your information is below+++++-----\n')
print('Name is: {} \nAddress is: {} \nAge is: {} \nInstitute is: {} \nDept is: {}'.format(names, address, age, institute, dept))
|
def valid_palindrome(str):
left, right = 0, len(str) - 1
while left < right:
if not str[left].isalnum():
left += 1
elif not str[right].isalnum():
right -= 1
else:
if str[left].lower() != str[right].lower():
print('False')
return False
else:
left += 1
right -= 1
print('True')
return True
test = "A man, a plan, a canal: Panama"
valid_palindrome(test)
|
def valid_palindrome(str):
(left, right) = (0, len(str) - 1)
while left < right:
if not str[left].isalnum():
left += 1
elif not str[right].isalnum():
right -= 1
elif str[left].lower() != str[right].lower():
print('False')
return False
else:
left += 1
right -= 1
print('True')
return True
test = 'A man, a plan, a canal: Panama'
valid_palindrome(test)
|
{
4 : {
"operator" : "aggregation",
"numgroups" : 1000000
}
}
|
{4: {'operator': 'aggregation', 'numgroups': 1000000}}
|
def get_numbers_between(set_a, set_b):
numbers_between = 0
for candidate in range(1, 101):
found = True
for item in set_a:
if candidate % item:
found = False
break
if not found:
continue
for item in set_b:
if item % candidate:
found = False
break
if found:
numbers_between += 1
return numbers_between
if __name__ == "__main__":
n, m = input().strip().split(' ')
n, m = [int(n), int(m)]
a = list(map(int, input().strip().split(' ')))
b = list(map(int, input().strip().split(' ')))
total = get_numbers_between(a, b)
print(total)
|
def get_numbers_between(set_a, set_b):
numbers_between = 0
for candidate in range(1, 101):
found = True
for item in set_a:
if candidate % item:
found = False
break
if not found:
continue
for item in set_b:
if item % candidate:
found = False
break
if found:
numbers_between += 1
return numbers_between
if __name__ == '__main__':
(n, m) = input().strip().split(' ')
(n, m) = [int(n), int(m)]
a = list(map(int, input().strip().split(' ')))
b = list(map(int, input().strip().split(' ')))
total = get_numbers_between(a, b)
print(total)
|
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def python_dependencies_early():
http_archive(
name = "rules_python",
url = "https://github.com/bazelbuild/rules_python/releases/download/0.0.1/rules_python-0.0.1.tar.gz",
sha256 = "aa96a691d3a8177f3215b14b0edc9641787abaaa30363a080165d06ab65e1161",
)
|
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def python_dependencies_early():
http_archive(name='rules_python', url='https://github.com/bazelbuild/rules_python/releases/download/0.0.1/rules_python-0.0.1.tar.gz', sha256='aa96a691d3a8177f3215b14b0edc9641787abaaa30363a080165d06ab65e1161')
|
# Pow(x, n): https://leetcode.com/problems/powx-n/
# Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
# This problem is pretty straight forward we simply iterate over the n times
# multiplying the input every time. The only tricky thing is that if we have
# a negative number we need to make sure to set it to 1/x before multiplying together
class Solution:
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1.0
if x == 0:
return 0
if n < 0:
x = 1/x
n *= -1
result = 1
for _ in range(n):
result *= x
return result
# The above works! The code runs in o(N) steps and uses o(1) space the problem is this isn't the fastest we can do!
# This is based off of the math that 2 ^ 10 == 4 ^ 5 = 4 * 16 ^ 2 = 4 * 256 ^ 1 = 1024
# If you look at the above we can reduce n by half in every single iteration which means that we can have a resulting
# o(logn) solution
def myPowOptimus(self, x: float, n: int) -> float:
if n == 0:
return 1.0
if x == 0:
return 0
if n < 0:
x = 1/x
n *= -1
result = 1.0
current = x
index = n
while index > 0:
# If we have an odd number we mutliply the result times the current factor so we can make our factor even
# so we can multiply it by itslef to reduce to half
if index % 2 == 1:
result = result * current
# Multiply current by current to reduce exponent in half
current = current * current
# Make sure our iterator is decreased by half
index = index // 2
return result
# Score Card
# Did I need hints? Yes because I forgot that I switched my index to equal n to make things more clear
# Did you finish within 30 min? 20
# Was the solution optimal? Oh yeah this runs in o(logn) and o(1)
# Were there any bugs? Yeah i forgot to make my odd exponent check use the right variable
# 3 5 5 3 = 4
|
class Solution:
def my_pow(self, x: float, n: int) -> float:
if n == 0:
return 1.0
if x == 0:
return 0
if n < 0:
x = 1 / x
n *= -1
result = 1
for _ in range(n):
result *= x
return result
def my_pow_optimus(self, x: float, n: int) -> float:
if n == 0:
return 1.0
if x == 0:
return 0
if n < 0:
x = 1 / x
n *= -1
result = 1.0
current = x
index = n
while index > 0:
if index % 2 == 1:
result = result * current
current = current * current
index = index // 2
return result
|
# User input
num1=float(input("Enter the 1st number: "))
num2=float(input("Enter your 2nd number: "))
# Operations the program should perform
sum = num1 + num2
difference = num1 - num2
product = num1 * num2
divide = num1 / num2
modulus = num1 % num2
# Computer output
print(sum)
print(difference)
print(product)
print(divide)
print(modulus)
|
num1 = float(input('Enter the 1st number: '))
num2 = float(input('Enter your 2nd number: '))
sum = num1 + num2
difference = num1 - num2
product = num1 * num2
divide = num1 / num2
modulus = num1 % num2
print(sum)
print(difference)
print(product)
print(divide)
print(modulus)
|
def main():
print("Iterative:")
print("n=0 ->", fibonacci_iterative(0))
print("n=1 ->", fibonacci_iterative(1))
print("n=6 ->", fibonacci_iterative(6))
print()
print("Recursive:")
print("n=0 ->", fibonacci_recursive(0))
print("n=1 ->", fibonacci_recursive(1))
print("n=6 ->", fibonacci_recursive(6))
def fibonacci_iterative(n):
fib = [0, 1]
if n < 2:
return fib[n]
for i in range(n - 1):
fib.append(fib[i] + fib[i + 1])
return fib[n]
def fibonacci_recursive(n):
if n < 2:
return n
return fibonacci_recursive(n - 2) + fibonacci_recursive(n - 1)
main()
|
def main():
print('Iterative:')
print('n=0 ->', fibonacci_iterative(0))
print('n=1 ->', fibonacci_iterative(1))
print('n=6 ->', fibonacci_iterative(6))
print()
print('Recursive:')
print('n=0 ->', fibonacci_recursive(0))
print('n=1 ->', fibonacci_recursive(1))
print('n=6 ->', fibonacci_recursive(6))
def fibonacci_iterative(n):
fib = [0, 1]
if n < 2:
return fib[n]
for i in range(n - 1):
fib.append(fib[i] + fib[i + 1])
return fib[n]
def fibonacci_recursive(n):
if n < 2:
return n
return fibonacci_recursive(n - 2) + fibonacci_recursive(n - 1)
main()
|
wanted_income = float(input())
total_income = 0
cocktail = input()
while cocktail != "Party!":
order = int(input())
cocktail_price = len(cocktail)
cocktail_price = order * cocktail_price
if cocktail_price % 2 != 0:
discount = cocktail_price - (cocktail_price * 0.25)
total_income += discount
else:
total_income += cocktail_price
if total_income >= wanted_income:
break
cocktail = input()
if cocktail == "Party!":
print(f"We need {wanted_income - total_income:.2f} leva more.")
elif total_income >= wanted_income:
print("Target acquired.")
print(f"Club income - {total_income:.2f} leva.")
|
wanted_income = float(input())
total_income = 0
cocktail = input()
while cocktail != 'Party!':
order = int(input())
cocktail_price = len(cocktail)
cocktail_price = order * cocktail_price
if cocktail_price % 2 != 0:
discount = cocktail_price - cocktail_price * 0.25
total_income += discount
else:
total_income += cocktail_price
if total_income >= wanted_income:
break
cocktail = input()
if cocktail == 'Party!':
print(f'We need {wanted_income - total_income:.2f} leva more.')
elif total_income >= wanted_income:
print('Target acquired.')
print(f'Club income - {total_income:.2f} leva.')
|
#!/usr/bin/env python3
strings = [
"sszojmmrrkwuftyv",
"isaljhemltsdzlum",
"fujcyucsrxgatisb",
"qiqqlmcgnhzparyg",
"oijbmduquhfactbc",
"jqzuvtggpdqcekgk",
"zwqadogmpjmmxijf",
"uilzxjythsqhwndh",
"gtssqejjknzkkpvw",
"wrggegukhhatygfi",
"vhtcgqzerxonhsye",
"tedlwzdjfppbmtdx",
"iuvrelxiapllaxbg",
"feybgiimfthtplui",
"qxmmcnirvkzfrjwd",
"vfarmltinsriqxpu",
"oanqfyqirkraesfq",
"xilodxfuxphuiiii",
"yukhnchvjkfwcbiq",
"bdaibcbzeuxqplop",
"ivegnnpbiyxqsion",
"ybahkbzpditgwdgt",
"dmebdomwabxgtctu",
"ibtvimgfaeonknoh",
"jsqraroxudetmfyw",
"dqdbcwtpintfcvuz",
"tiyphjunlxddenpj",
"fgqwjgntxagidhah",
"nwenhxmakxqkeehg",
"zdoheaxqpcnlhnen",
"tfetfqojqcdzlpbm",
"qpnxkuldeiituggg",
"xwttlbdwxohahwar",
"hjkwzadmtrkegzye",
"koksqrqcfwcaxeof",
"wulwmrptktliyxeq",
"gyufbedqhhyqgqzj",
"txpunzodohikzlmj",
"jloqfuejfkemcrvu",
"amnflshcheuddqtc",
"pdvcsduggcogbiia",
"yrioavgfmeafjpcz",
"uyhbtmbutozzqfvq",
"mwhgfwsgyuwcdzik",
"auqylgxhmullxpaa",
"lgelzivplaeoivzh",
"uyvcepielfcmswoa",
"qhirixgwkkccuzlp",
"zoonniyosmkeejfg",
"iayfetpixkedyana",
"ictqeyzyqswdskiy",
"ejsgqteafvmorwxe",
"lhaiqrlqqwfbrqdx",
"ydjyboqwhfpqfydc",
"dwhttezyanrnbybv",
"edgzkqeqkyojowvr",
"rmjfdwsqamjqehdq",
"ozminkgnkwqctrxz",
"bztjhxpjthchhfcd",
"vrtioawyxkivrpiq",
"dpbcsznkpkaaclyy",
"vpoypksymdwttpvz",
"hhdlruwclartkyap",
"bqkrcbrksbzcggbo",
"jerbbbnxlwfvlaiw",
"dwkasufidwjrjfbf",
"kkfxtjhbnmqbmfwf",
"vmnfziwqxmioukmj",
"rqxvcultipkecdtu",
"fhmfdibhtjzkiqsd",
"hdpjbuzzbyafqrpd",
"emszboysjuvwwvts",
"msyigmwcuybfiooq",
"druyksfnbluvnwoh",
"fvgstvynnfbvxhsx",
"bmzalvducnqtuune",
"lzwkzfzttsvpllei",
"olmplpvjamynfyfd",
"padcwfkhystsvyfb",
"wjhbvxkwtbfqdilb",
"hruaqjwphonnterf",
"bufjobjtvxtzjpmj",
"oiedrjvmlbtwyyuy",
"sgiemafwfztwsyju",
"nsoqqfudrtwszyqf",
"vonbxquiiwxnazyl",
"yvnmjxtptujwqudn",
"rrnybqhvrcgwvrkq",
"taktoxzgotzxntfu",
"quffzywzpxyaepxa",
"rfvjebfiddcfgmwv",
"iaeozntougqwnzoh",
"scdqyrhoqmljhoil",
"bfmqticltmfhxwld",
"brbuktbyqlyfpsdl",
"oidnyhjkeqenjlhd",
"kujsaiqojopvrygg",
"vebzobmdbzvjnjtk",
"uunoygzqjopwgmbg",
"piljqxgicjzgifso",
"ikgptwcjzywswqnw",
"pujqsixoisvhdvwi",
"trtuxbgigogfsbbk",
"mplstsqclhhdyaqk",
"gzcwflvmstogdpvo",
"tfjywbkmimyyqcjd",
"gijutvhruqcsiznq",
"ibxkhjvzzxgavkha",
"btnxeqvznkxjsgmq",
"tjgofgauxaelmjoq",
"sokshvyhlkxerjrv",
"ltogbivktqmtezta",
"uduwytzvqvfluyuf",
"msuckpthtgzhdxan",
"fqmcglidvhvpirzr",
"gwztkqpcwnutvfga",
"bsjfgsrntdhlpqbx",
"xloczbqybxmiopwt",
"orvevzyjliomkkgu",
"mzjbhmfjjvaziget",
"tlsdxuhwdmghdyjb",
"atoecyjhwmznaewi",
"pyxpyvvipbqibiox",
"ajbfmpqqobfsmesj",
"siknbzefjblnohgd",
"eqfhgewbblwdfkmc",
"opylbscrotckkrbk",
"lbwxbofgjkzdxkle",
"ceixfjstaptdomvm",
"hnkrqxifjmmjktie",
"aqykzeuzvvetoygd",
"fouahjimfcisxima",
"prkzhutbqsyrhjzx",
"qqwliakathnsbzne",
"sayhgqtlcqqidqhj",
"ygduolbysehdudra",
"zricvxhdzznuxuce",
"ucvzakslykpgsixd",
"udirhgcttmyspgsb",
"yuwzppjzfsjhhdzi",
"gtqergjiuwookwre",
"xvxexbjyjkxovvwf",
"mlpaqhnnkqxrmwmm",
"ezuqbrjozwuqafhb",
"mcarusdthcbsonoq",
"weeguqeheeiigrue",
"pngtfugozxofaqxv",
"copphvbjcmfspenv",
"jiyahihykjjkdaya",
"gdqnmesvptuyrfwp",
"vbdscfywqmfxbohh",
"crtrfuxyjypzubrg",
"seihvevtxywxhflp",
"fvvpmgttnapklwou",
"qmqaqsajmqwhetpk",
"zetxvrgjmblxvakr",
"kpvwblrizaabmnhz",
"mwpvvzaaicntrkcp",
"clqyjiegtdsswqfm",
"ymrcnqgcpldgfwtm",
"nzyqpdenetncgnwq",
"cmkzevgacnmdkqro",
"kzfdsnamjqbeirhi",
"kpxrvgvvxapqlued",
"rzskbnfobevzrtqu",
"vjoahbfwtydugzap",
"ykbbldkoijlvicbl",
"mfdmroiztsgjlasb",
"quoigfyxwtwprmdr",
"ekxjqafwudgwfqjm",
"obtvyjkiycxfcdpb",
"lhoihfnbuqelthof",
"eydwzitgxryktddt",
"rxsihfybacnpoyny",
"bsncccxlplqgygtw",
"rvmlaudsifnzhcqh",
"huxwsyjyebckcsnn",
"gtuqzyihwhqvjtes",
"zreeyomtngvztveq",
"nwddzjingsarhkxb",
"nuqxqtctpoldrlsh",
"wkvnrwqgjooovhpf",
"kwgueyiyffudtbyg",
"tpkzapnjxefqnmew",
"ludwccvkihagvxal",
"lfdtzhfadvabghna",
"njqmlsnrkcfhtvbb",
"cajzbqleghhnlgap",
"vmitdcozzvqvzatp",
"eelzefwqwjiywbcz",
"uyztcuptfqvymjpi",
"aorhnrpkjqqtgnfo",
"lfrxfdrduoeqmwwp",
"vszpjvbctblplinh",
"zexhadgpqfifcqrz",
"ueirfnshekpemqua",
"qfremlntihbwabtb",
"nwznunammfexltjc",
"zkyieokaaogjehwt",
"vlrxgkpclzeslqkq",
"xrqrwfsuacywczhs",
"olghlnfjdiwgdbqc",
"difnlxnedpqcsrdf",
"dgpuhiisybjpidsj",
"vlwmwrikmitmoxbt",
"sazpcmcnviynoktm",
"pratafauetiknhln",
"ilgteekhzwlsfwcn",
"ywvwhrwhkaubvkbl",
"qlaxivzwxyhvrxcf",
"hbtlwjdriizqvjfb",
"nrmsononytuwslsa",
"mpxqgdthpoipyhjc",
"mcdiwmiqeidwcglk",
"vfbaeavmjjemfrmo",
"qzcbzmisnynzibrc",
"shzmpgxhehhcejhb",
"wirtjadsqzydtyxd",
"qjlrnjfokkqvnpue",
"dxawdvjntlbxtuqc",
"wttfmnrievfestog",
"eamjfvsjhvzzaobg",
"pbvfcwzjgxahlrag",
"omvmjkqqnobvnzkn",
"lcwmeibxhhlxnkzv",
"uiaeroqfbvlazegs",
"twniyldyuonfyzqw",
"wgjkmsbwgfotdabi",
"hnomamxoxvrzvtew",
"ycrcfavikkrxxfgw",
"isieyodknagzhaxy",
"mgzdqwikzullzyco",
"mumezgtxjrrejtrs",
"nwmwjcgrqiwgfqel",
"wjgxmebfmyjnxyyp",
"durpspyljdykvzxf",
"zuslbrpooyetgafh",
"kuzrhcjwbdouhyme",
"wyxuvbciodscbvfm",
"kbnpvuqwmxwfqtqe",
"zddzercqogdpxmft",
"sigrdchxtgavzzjh",
"lznjolnorbuddgcs",
"ycnqabxlcajagwbt",
"bnaudeaexahdgxsj",
"rlnykxvoctfwanms",
"jngyetkoplrstfzt",
"tdpxknwacksotdub",
"yutqgssfoptvizgr",
"lzmqnxeqjfnsxmsa",
"iqpgfsfmukovsdgu",
"qywreehbidowtjyz",
"iozamtgusdctvnkw",
"ielmujhtmynlwcfd",
"hzxnhtbnmmejlkyf",
"ftbslbzmiqkzebtd",
"bcwdqgiiizmohack",
"dqhfkzeddjzbdlxu",
"mxopokqffisxosci",
"vciatxhtuechbylk",
"khtkhcvelidjdena",
"blatarwzfqcapkdt",
"elamngegnczctcck",
"xeicefdbwrxhuxuf",
"sawvdhjoeahlgcdr",
"kmdcimzsfkdfpnir",
"axjayzqlosrduajb",
"mfhzreuzzumvoggr",
"iqlbkbhrkptquldb",
"xcvztvlshiefuhgb",
"pkvwyqmyoazocrio",
"ajsxkdnerbmhyxaj",
"tudibgsbnpnizvsi",
"cxuiydkgdccrqvkh",
"cyztpjesdzmbcpot",
"nnazphxpanegwitx",
"uphymczbmjalmsct",
"yyxiwnlrogyzwqmg",
"gmqwnahjvvdyhnfa",
"utolskxpuoheugyl",
"mseszdhyzoyavepd",
"ycqknvbuvcjfgmlc",
"sknrxhxbfpvpeorn",
"zqxqjetooqcodwml",
"sesylkpvbndrdhsy",
"fryuxvjnsvnjrxlw",
"mfxusewqurscujnu",
"mbitdjjtgzchvkfv",
"ozwlyxtaalxofovd",
"wdqcduaykxbunpie",
"rlnhykxiraileysk",
"wgoqfrygttlamobg",
"kflxzgxvcblkpsbz",
"tmkisflhativzhde",
"owsdrfgkaamogjzd",
"gaupjkvkzavhfnes",
"wknkurddcknbdleg",
"lltviwincmbtduap",
"qwzvspgbcksyzzmb",
"ydzzkumecryfjgnk",
"jzvmwgjutxoysaam",
"icrwpyhxllbardkr",
"jdopyntshmvltrve",
"afgkigxcuvmdbqou",
"mfzzudntmvuyhjzt",
"duxhgtwafcgrpihc",
"tsnhrkvponudumeb",
"sqtvnbeiigdzbjgv",
"eczmkqwvnsrracuo",
"mhehsgqwiczaiaxv",
"kaudmfvifovrimpd",
"lupikgivechdbwfr",
"mwaaysrndiutuiqx",
"aacuiiwgaannunmm",
"tjqjbftaqitukwzp",
"lrcqyskykbjpaekn",
"lirrvofbcqpjzxmr",
"jurorvzpplyelfml",
"qonbllojmloykjqe",
"sllkzqujfnbauuqp",
"auexjwsvphvikali",
"usuelbssqmbrkxyc",
"wyuokkfjexikptvv",
"wmfedauwjgbrgytl",
"sfwvtlzzebxzmuvw",
"rdhqxuechjsjcvaf",
"kpavhqkukugocsxu",
"ovnjtumxowbxduts",
"zgerpjufauptxgat",
"pevvnzjfwhjxdoxq",
"pmmfwxajgfziszcs",
"difmeqvaghuitjhs",
"icpwjbzcmlcterwm",
"ngqpvhajttxuegyh",
"mosjlqswdngwqsmi",
"frlvgpxrjolgodlu",
"eazwgrpcxjgoszeg",
"bbtsthgkjrpkiiyk",
"tjonoglufuvsvabe",
"xhkbcrofytmbzrtk",
"kqftfzdmpbxjynps",
"kmeqpocbnikdtfyv",
"qjjymgqxhnjwxxhp",
"dmgicrhgbngdtmjt",
"zdxrhdhbdutlawnc",
"afvoekuhdboxghvx",
"hiipezngkqcnihty",
"bbmqgheidenweeov",
"suprgwxgxwfsgjnx",
"adeagikyamgqphrj",
"zzifqinoeqaorjxg",
"adhgppljizpaxzld",
"lvxyieypvvuqjiyc",
"nljoakatwwwoovzn",
"fcrkfxclcacshhmx",
"ownnxqtdhqbgthch",
"lmfylrcdmdkgpwnj",
"hlwjfbvlswbzpbjr",
"mkofhdtljdetcyvp",
"synyxhifbetzarpo",
"agnggugngadrcxoc",
"uhttadmdmhidpyjw",
"ohfwjfhunalbubpr",
"pzkkkkwrlvxiuysn",
"kmidbxmyzkjrwjhu",
"egtitdydwjxmajnw",
"civoeoiuwtwgbqqs",
"dfptsguzfinqoslk",
"tdfvkreormspprer",
"zvnvbrmthatzztwi",
"ffkyddccrrfikjde",
"hrrmraevdnztiwff",
"qaeygykcpbtjwjbr",
"purwhitkmrtybslh",
"qzziznlswjaussel",
"dfcxkvdpqccdqqxj",
"tuotforulrrytgyn",
"gmtgfofgucjywkev",
"wkyoxudvdkbgpwhd",
"qbvktvfvipftztnn",
"otckgmojziezmojb",
"inxhvzbtgkjxflay",
"qvxapbiatuudseno",
"krpvqosbesnjntut",
"oqeukkgjsfuqkjbb",
"prcjnyymnqwqksiz",
"vuortvjxgckresko",
"orqlyobvkuwgathr",
"qnpyxlnazyfuijox",
"zwlblfkoklqmqzkw",
"hmwurwtpwnrcsanl",
"jzvxohuakopuzgpf",
"sfcpnxrviphhvxmx",
"qtwdeadudtqhbely",
"dbmkmloasqphnlgj",
"olylnjtkxgrubmtk",
"nxsdbqjuvwrrdbpq",
"wbabpirnpcsmpipw",
"hjnkyiuxpqrlvims",
"enzpntcjnxdpuqch",
"vvvqhlstzcizyimn",
"triozhqndbttglhv",
"fukvgteitwaagpzx",
"uhcvukfbmrvskpen",
"tizcyupztftzxdmt",
"vtkpnbpdzsaluczz",
"wodfoyhoekidxttm",
"otqocljrmwfqbxzu",
"linfbsnfvixlwykn",
"vxsluutrwskslnye",
"zbshygtwugixjvsi",
"zdcqwxvwytmzhvoo",
"wrseozkkcyctrmei",
"fblgtvogvkpqzxiy",
"opueqnuyngegbtnf",
"qxbovietpacqqxok",
"zacrdrrkohfygddn",
"gbnnvjqmkdupwzpq",
"qgrgmsxeotozvcak",
"hnppukzvzfmlokid",
"dzbheurndscrrtcl",
"wbgdkadtszebbrcw",
"fdmzppzphhpzyuiz",
"bukomunhrjrypohj",
"ohodhelegxootqbj",
"rsplgzarlrknqjyh",
"punjjwpsxnhpzgvu",
"djdfahypfjvpvibm",
"mlgrqsmhaozatsvy",
"xwktrgyuhqiquxgn",
"wvfaoolwtkbrisvf",
"plttjdmguxjwmeqr",
"zlvvbwvlhauyjykw",
"cigwkbyjhmepikej",
"masmylenrusgtyxs",
"hviqzufwyetyznze",
"nzqfuhrooswxxhus",
"pdbdetaqcrqzzwxf",
"oehmvziiqwkzhzib",
"icgpyrukiokmytoy",
"ooixfvwtiafnwkce",
"rvnmgqggpjopkihs",
"wywualssrmaqigqk",
"pdbvflnwfswsrirl",
"jeaezptokkccpbuj",
"mbdwjntysntsaaby",
"ldlgcawkzcwuxzpz",
"lwktbgrzswbsweht",
"ecspepmzarzmgpjm",
"qmfyvulkmkxjncai",
"izftypvwngiukrns",
"zgmnyjfeqffbooww",
"nyrkhggnprhedows",
"yykzzrjmlevgffah",
"mavaemfxhlfejfki",
"cmegmfjbkvpncqwf",
"zxidlodrezztcrij",
"fseasudpgvgnysjv",
"fupcimjupywzpqzp",
"iqhgokavirrcvyys",
"wjmkcareucnmfhui",
"nftflsqnkgjaexhq",
"mgklahzlcbapntgw",
"kfbmeavfxtppnrxn",
"nuhyvhknlufdynvn",
"nviogjxbluwrcoec",
"tyozixxxaqiuvoys",
"kgwlvmvgtsvxojpr",
"moeektyhyonfdhrb",
"kahvevmmfsmiiqex",
"xcywnqzcdqtvhiwd",
"fnievhiyltbvtvem",
"jlmndqufirwgtdxd",
"muypbfttoeelsnbs",
"rypxzbnujitfwkou",
"ubmmjbznskildeoj",
"ofnmizdeicrmkjxp",
"rekvectjbmdnfcib",
"yohrojuvdexbctdh",
"gwfnfdeibynzjmhz",
"jfznhfcqdwlpjull",
"scrinzycfhwkmmso",
"mskutzossrwoqqsi",
"rygoebkzgyzushhr",
"jpjqiycflqkexemx",
"arbufysjqmgaapnl",
"dbjerflevtgweeoj",
"snybnnjlmwjvhois",
"fszuzplntraprmbj",
"mkvaatolvuggikvg",
"zpuzuqygoxesnuyc",
"wnpxvmxvllxalulm",
"eivuuafkvudeouwy",
"rvzckdyixetfuehr",
"qgmnicdoqhveahyx",
"miawwngyymshjmpj",
"pvckyoncpqeqkbmx",
"llninfenrfjqxurv",
"kzbjnlgsqjfuzqtp",
"rveqcmxomvpjcwte",
"bzotkawzbopkosnx",
"ktqvpiribpypaymu",
"wvlzkivbukhnvram",
"uohntlcoguvjqqdo",
"ajlsiksjrcnzepkt",
"xsqatbldqcykwusd",
"ihbivgzrwpmowkop",
"vfayesfojmibkjpb",
"uaqbnijtrhvqxjtb",
"hhovshsfmvkvymba",
"jerwmyxrfeyvxcgg",
"hncafjwrlvdcupma",
"qyvigggxfylbbrzt",
"hiiixcyohmvnkpgk",
"mmitpwopgxuftdfu",
"iaxderqpceboixoa",
"zodfmjhuzhnsqfcb",
"sthtcbadrclrazsi",
"bkkkkcwegvypbrio",
"wmpcofuvzemunlhj",
"gqwebiifvqoeynro",
"juupusqdsvxcpsgv",
"rbhdfhthxelolyse",
"kjimpwnjfrqlqhhz",
"rcuigrjzarzpjgfq",
"htxcejfyzhydinks",
"sxucpdxhvqjxxjwf",
"omsznfcimbcwaxal",
"gufmtdlhgrsvcosb",
"bssshaqujtmluerz",
"uukotwjkstgwijtr",
"kbqkneobbrdogrxk",
"ljqopjcjmelgrakz",
"rwtfnvnzryujwkfb",
"dedjjbrndqnilbeh",
"nzinsxnpptzagwlb",
"lwqanydfirhnhkxy",
"hrjuzfumbvfccxno",
"okismsadkbseumnp",
"sfkmiaiwlktxqvwa",
"hauwpjjwowbunbjj",
"nowkofejwvutcnui",
"bqzzppwoslaeixro",
"urpfgufwbtzenkpj",
"xgeszvuqwxeykhef",
"yxoldvkyuikwqyeq",
"onbbhxrnmohzskgg",
"qcikuxakrqeugpoa",
"lnudcqbtyzhlpers",
"nxduvwfrgzaailgl",
"xniuwvxufzxjjrwz",
"ljwithcqmgvntjdj",
"awkftfagrfzywkhs",
"uedtpzxyubeveuek",
"bhcqdwidbjkqqhzl",
"iyneqjdmlhowwzxx",
"kvshzltcrrururty",
"zgfpiwajegwezupo",
"tkrvyanujjwmyyri",
"ercsefuihcmoaiep",
"ienjrxpmetinvbos",
"jnwfutjbgenlipzq",
"bgohjmrptfuamzbz",
"rtsyamajrhxbcncw",
"tfjdssnmztvbnscs",
"bgaychdlmchngqlp",
"kfjljiobynhwfkjo",
"owtdxzcpqleftbvn",
"ltjtimxwstvzwzjj",
"wbrvjjjajuombokf",
"zblpbpuaqbkvsxye",
"gwgdtbpnlhyqspdi",
"abipqjihjqfofmkx",
"nlqymnuvjpvvgova",
"avngotmhodpoufzn",
"qmdyivtzitnrjuae",
"xfwjmqtqdljuerxi",
"csuellnlcyqaaamq",
"slqyrcurcyuoxquo",
"dcjmxyzbzpohzprl",
"uqfnmjwniyqgsowb",
"rbmxpqoblyxdocqc",
"ebjclrdbqjhladem",
"ainnfhxnsgwqnmyo",
"eyytjjwhvodtzquf",
"iabjgmbbhilrcyyp",
"pqfnehkivuelyccc",
"xgjbyhfgmtseiimt",
"jwxyqhdbjiqqqeyy",
"gxsbrncqkmvaryln",
"vhjisxjkinaejytk",
"seexagcdmaedpcvh",
"lvudfgrcpjxzdpvd",
"fxtegyrqjzhmqean",
"dnoiseraqcoossmc",
"nwrhmwwbykvwmgep",
"udmzskejvizmtlce",
"hbzvqhvudfdlegaa",
"cghmlfqejbxewskv",
"bntcmjqfwomtbwsb",
"qezhowyopjdyhzng",
"todzsocdkgfxanbz",
"zgjkssrjlwxuhwbk",
"eibzljqsieriyrzr",
"wamxvzqyycrxotjp",
"epzvfkispwqynadu",
"dwlpfhtrafrxlyie",
"qhgzujhgdruowoug",
"girstvkahaemmxvh",
"baitcrqmxhazyhbl",
"xyanqcchbhkajdmc",
"gfvjmmcgfhvgnfdq",
"tdfdbslwncbnkzyz",
"jojuselkpmnnbcbb",
"hatdslkgxtqpmavj",
"dvelfeddvgjcyxkj",
"gnsofhkfepgwltse",
"mdngnobasfpewlno",
"qssnbcyjgmkyuoga",
"glvcmmjytmprqwvn",
"gwrixumjbcdffsdl",
"lozravlzvfqtsuiq",
"sicaflbqdxbmdlch",
"inwfjkyyqbwpmqlq",
"cuvszfotxywuzhzi",
"igfxyoaacoarlvay",
"ucjfhgdmnjvgvuni",
"rvvkzjsytqgiposh",
"jduinhjjntrmqroz",
"yparkxbgsfnueyll",
"lyeqqeisxzfsqzuj",
"woncskbibjnumydm",
"lltucklragtjmxtl",
"ubiyvmyhlesfxotj",
"uecjseeicldqrqww",
"xxlxkbcthufnjbnm",
"lhqijovvhlffpxga",
"fzdgqpzijitlogjz",
"efzzjqvwphomxdpd",
"jvgzvuyzobeazssc",
"hejfycgxywfjgbfw",
"yhjjmvkqfbnbliks",
"sffvfyywtlntsdsz",
"dwmxqudvxqdenrur",
"asnukgppdemxrzaz",
"nwqfnumblwvdpphx",
"kqsmkkspqvxzuket",
"cpnraovljzqiquaz",
"qrzgrdlyyzbyykhg",
"opoahcbiydyhsmqe",
"hjknnfdauidjeydr",
"hczdjjlygoezadow",
"rtflowzqycimllfv",
"sfsrgrerzlnychhq",
"bpahuvlblcolpjmj",
"albgnjkgmcrlaicl",
"pijyqdhfxpaxzdex",
"eeymiddvcwkpbpux",
"rqwkqoabywgggnln",
"vckbollyhgbgmgwh",
"ylzlgvnuvpynybkm",
"hpmbxtpfosbsjixt",
"ocebeihnhvkhjfqz",
"tvctyxoujdgwayze",
"efvhwxtuhapqxjen",
"rusksgefyidldmpo",
"nkmtjvddfmhirmzz",
"whvtsuadwofzmvrt",
"iiwjqvsdxudhdzzk",
"gucirgxaxgcassyo",
"rmhfasfzexeykwmr",
"hynlxcvsbgosjbis",
"huregszrcaocueen",
"pifezpoolrnbdqtv",
"unatnixzvdbqeyox",
"xtawlpduxgacchfe",
"bdvdbflqfphndduf",
"xtdsnjnmzccfptyt",
"nkhsdkhqtzqbphhg",
"aqcubmfkczlaxiyb",
"moziflxpsfubucmv",
"srdgnnjtfehiimqx",
"pwfalehdfyykrohf",
"sysxssmvewyfjrve",
"brsemdzosgqvvlxe",
"bimbjoshuvflkiat",
"hkgjasmljkpkwwku",
"sbnmwjvodygobpqc",
"bbbqycejueruihhd",
"corawswvlvneipyc",
"gcyhknmwsczcxedh",
"kppakbffdhntmcqp",
"ynulzwkfaemkcefp",
"pyroowjekeurlbii",
"iwksighrswdcnmxf",
"glokrdmugreygnsg",
"xkmvvumnfzckryop",
"aesviofpufygschi",
"csloawlirnegsssq",
"fkqdqqmlzuxbkzbc",
"uzlhzcfenxdfjdzp",
"poaaidrktteusvyf",
"zrlyfzmjzfvivcfr",
"qwjulskbniitgqtx",
"gjeszjksbfsuejki",
"vczdejdbfixbduaq",
"knjdrjthitjxluth",
"jweydeginrnicirl",
"bottrfgccqhyycsl",
"eiquffofoadmbuhk",
"lbqfutmzoksscswf",
"xfmdvnvfcnzjprba",
"uvugkjbkhlaoxmyx",
"wadlgtpczgvcaqqv",
"inzrszbtossflsxk",
"dbzbtashaartczrj",
"qbjiqpccefcfkvod",
"hluujmokjywotvzy",
"thwlliksfztcmwzh",
"arahybspdaqdexrq",
"nuojrmsgyipdvwyx",
"hnajdwjwmzattvst",
"sulcgaxezkprjbgu",
"rjowuugwdpkjtypw",
"oeugzwuhnrgiaqga",
"wvxnyymwftfoswij",
"pqxklzkjpcqscvde",
"tuymjzknntekglqj",
"odteewktugcwlhln",
"exsptotlfecmgehc",
"eeswfcijtvzgrqel",
"vjhrkiwmunuiwqau",
"zhlixepkeijoemne",
"pavfsmwesuvebzdd",
"jzovbklnngfdmyws",
"nbajyohtzfeoiixz",
"ciozmhrsjzrwxvhz",
"gwucrxieqbaqfjuv",
"uayrxrltnohexawc",
"flmrbhwsfbcquffm",
"gjyabmngkitawlxc",
"rwwtggvaygfbovhg",
"xquiegaisynictjq",
"oudzwuhexrwwdbyy",
"lengxmguyrwhrebb",
"uklxpglldbgqsjls",
"dbmvlfeyguydfsxq",
"zspdwdqcrmtmdtsc",
"mqfnzwbfqlauvrgc",
"amcrkzptgacywvhv",
"ndxmskrwrqysrndf",
"mwjyhsufeqhwisju",
"srlrukoaenyevykt",
"tnpjtpwawrxbikct",
"geczalxmgxejulcv",
"tvkcbqdhmuwcxqci",
"tiovluvwezwwgaox",
"zrjhtbgajkjqzmfo",
"vcrywduwsklepirs",
"lofequdigsszuioy",
"wxsdzomkjqymlzat",
"iabaczqtrfbmypuy",
"ibdlmudbajikcncr",
"rqcvkzsbwmavdwnv",
"ypxoyjelhllhbeog",
"fdnszbkezyjbttbg",
"uxnhrldastpdjkdz",
"xfrjbehtxnlyzcka",
"omjyfhbibqwgcpbv",
"eguucnoxaoprszmp",
"xfpypldgcmcllyzz",
"aypnmgqjxjqceelv",
"mgzharymejlafvgf",
"tzowgwsubbaigdok",
"ilsehjqpcjwmylxc",
"pfmouwntfhfnmrwk",
"csgokybgdqwnduwp",
"eaxwvxvvwbrovypz",
"nmluqvobbbmdiwwb",
"lnkminvfjjzqbmio",
"mjiiqzycqdhfietz",
"towlrzriicyraevq",
"obiloewdvbrsfwjo",
"lmeooaajlthsfltw",
"ichygipzpykkesrw",
"gfysloxmqdsfskvt",
"saqzntehjldvwtsx",
"pqddoemaufpfcaew",
"mjrxvbvwcreaybwe",
"ngfbrwfqnxqosoai",
"nesyewxreiqvhald",
"kqhqdlquywotcyfy",
"liliptyoqujensfi",
"nsahsaxvaepzneqq",
"zaickulfjajhctye",
"gxjzahtgbgbabtht",
"koxbuopaqhlsyhrp",
"jhzejdjidqqtjnwe",
"dekrkdvprfqpcqki",
"linwlombdqtdeyop",
"dvckqqbnigdcmwmx",
"yaxygbjpzkvnnebv",
"rlzkdkgaagmcpxah",
"cfzuyxivtknirqvt",
"obivkajhsjnrxxhn",
"lmjhayymgpseuynn",
"bbjyewkwadaipyju",
"lmzyhwomfypoftuu",
"gtzhqlgltvatxack",
"jfflcfaqqkrrltgq",
"txoummmnzfrlrmcg",
"ohemsbfuqqpucups",
"imsfvowcbieotlok",
"tcnsnccdszxfcyde",
"qkcdtkwuaquajazz",
"arcfnhmdjezdbqku",
"srnocgyqrlcvlhkb",
"mppbzvfmcdirbyfw",
"xiuarktilpldwgwd",
"ypufwmhrvzqmexpc",
"itpdnsfkwgrdujmj",
"cmpxnodtsswkyxkr",
"wayyxtjklfrmvbfp",
"mfaxphcnjczhbbwy",
"sjxhgwdnqcofbdra",
"pnxmujuylqccjvjm",
"ivamtjbvairwjqwl",
"deijtmzgpfxrclss",
"bzkqcaqagsynlaer",
"tycefobvxcvwaulz",
"ctbhnywezxkdsswf",
"urrxxebxrthtjvib",
"fpfelcigwqwdjucv",
"ngfcyyqpqulwcphb",
"rltkzsiipkpzlgpw",
"qfdsymzwhqqdkykc",
"balrhhxipoqzmihj",
"rnwalxgigswxomga",
"ghqnxeogckshphgr",
"lyyaentdizaumnla",
"exriodwfzosbeoib",
"speswfggibijfejk",
"yxmxgfhvmshqszrq",
"hcqhngvahzgawjga",
"qmhlsrfpesmeksur",
"eviafjejygakodla",
"kvcfeiqhynqadbzv",
"fusvyhowslfzqttg",
"girqmvwmcvntrwau",
"yuavizroykfkdekz",
"jmcwohvmzvowrhxf",
"kzimlcpavapynfue",
"wjudcdtrewfabppq",
"yqpteuxqgbmqfgxh",
"xdgiszbuhdognniu",
"jsguxfwhpftlcjoh",
"whakkvspssgjzxre",
"ggvnvjurlyhhijgm",
"krvbhjybnpemeptr",
"pqedgfojyjybfbzr",
"jzhcrsgmnkwwtpdo",
"yyscxoxwofslncmp",
"gzjhnxytmyntzths",
"iteigbnqbtpvqumi",
"zjevfzusnjukqpfw",
"xippcyhkfuounxqk",
"mcnhrcfonfdgpkyh",
"pinkcyuhjkexbmzj",
"lotxrswlxbxlxufs",
"fmqajrtoabpckbnu",
"wfkwsgmcffdgaqxg",
"qfrsiwnohoyfbidr",
"czfqbsbmiuyusaqs",
"ieknnjeecucghpoo",
"cevdgqnugupvmsge",
"gjkajcyjnxdrtuvr",
"udzhrargnujxiclq",
"zqqrhhmjwermjssg",
"ggdivtmgoqajydzz",
"wnpfsgtxowkjiivl",
"afbhqawjbotxnqpd",
"xjpkifkhfjeqifdn",
"oyfggzsstfhvticp",
"kercaetahymeawxy",
"khphblhcgmbupmzt",
"iggoqtqpvaebtiol",
"ofknifysuasshoya",
"qxuewroccsbogrbv",
"apsbnbkiopopytgu",
"zyahfroovfjlythh",
"bxhjwfgeuxlviydq",
"uvbhdtvaypasaswa",
"qamcjzrmesqgqdiz",
"hjnjyzrxntiycyel",
"wkcrwqwniczwdxgq",
"hibxlvkqakusswkx",
"mzjyuenepwdgrkty",
"tvywsoqslfsulses",
"jqwcwuuisrclircv",
"xanwaoebfrzhurct",
"ykriratovsvxxasf",
"qyebvtqqxbjuuwuo",
"telrvlwvriylnder",
"acksrrptgnhkeiaa",
"yemwfjhiqlzsvdxf",
"banrornfkcymmkcc",
"ytbhxvaeiigjpcgm",
"crepyazgxquposkn",
"xlqwdrytzwnxzwzv",
"xtrbfbwopxscftps",
"kwbytzukgseeyjla",
"qtfdvavvjogybxjg",
"ytbmvmrcxwfkgvzw",
"nbscbdskdeocnfzr",
"sqquwjbdxsxhcseg",
"ewqxhigqcgszfsuw",
"cvkyfcyfmubzwsee",
"dcoawetekigxgygd",
"ohgqnqhfimyuqhvi",
"otisopzzpvnhctte",
"bauieohjejamzien",
"ewnnopzkujbvhwce",
"aeyqlskpaehagdiv",
"pncudvivwnnqspxy",
"ytugesilgveokxcg",
"zoidxeelqdjesxpr",
"ducjccsuaygfchzj",
"smhgllqqqcjfubfc",
"nlbyyywergronmir",
"prdawpbjhrzsbsvj",
"nmgzhnjhlpcplmui",
"eflaogtjghdjmxxz",
"qolvpngucbkprrdc",
"ixywxcienveltgho",
"mwnpqtocagenkxut",
"iskrfbwxonkguywx",
"ouhtbvcaczqzmpua",
"srewprgddfgmdbao",
"dyufrltacelchlvu",
"czmzcbrkecixuwzz",
"dtbeojcztzauofuk",
"prrgoehpqhngfgmw",
"baolzvfrrevxsyke",
"zqadgxshwiarkzwh",
"vsackherluvurqqj",
"surbpxdulvcvgjbd",
"wqxytarcxzgxhvtx",
"vbcubqvejcfsgrac",
"zqnjfeapshjowzja",
"hekvbhtainkvbynx",
"knnugxoktxpvoxnh",
"knoaalcefpgtvlwm",
"qoakaunowmsuvkus",
"ypkvlzcduzlezqcb",
"ujhcagawtyepyogh",
"wsilcrxncnffaxjf",
"gbbycjuscquaycrk",
"aduojapeaqwivnly",
"ceafyxrakviagcjy",
"nntajnghicgnrlst",
"vdodpeherjmmvbje",
"wyyhrnegblwvdobn",
"xlfurpghkpbzhhif",
"xyppnjiljvirmqjo",
"kglzqahipnddanpi",
"omjateouxikwxowr",
"ocifnoopfglmndcx",
"emudcukfbadyijev",
"ooktviixetfddfmh",
"wtvrhloyjewdeycg",
"cgjncqykgutfjhvb",
"nkwvpswppeffmwad",
"hqbcmfhzkxmnrivg",
"mdskbvzguxvieilr",
"anjcvqpavhdloaqh",
"erksespdevjylenq",
"fadxwbmisazyegup",
"iyuiffjmcaahowhj",
"ygkdezmynmltodbv",
"fytneukxqkjattvh",
"woerxfadbfrvdcnz",
"iwsljvkyfastccoa",
"movylhjranlorofe",
"drdmicdaiwukemep",
"knfgtsmuhfcvvshg",
"ibstpbevqmdlhajn",
"tstwsswswrxlzrqs",
"estyydmzothggudf",
"jezogwvymvikszwa",
"izmqcwdyggibliet",
"nzpxbegurwnwrnca",
"kzkojelnvkwfublh",
"xqcssgozuxfqtiwi",
"tcdoigumjrgvczfv",
"ikcjyubjmylkwlwq",
"kqfivwystpqzvhan",
"bzukgvyoqewniivj",
"iduapzclhhyfladn",
"fbpyzxdfmkrtfaeg",
"yzsmlbnftftgwadz"
]
def part1():
def contains_three_vowels(x):
n = 0
for c in x:
if c in "aeiou":
n += 1
return n >= 3
def contains_dubble(x):
for i in range(len(x) - 1):
if x[i] == x[i + 1]:
return True
return False
def contains_forbidden(x):
forbidden = ["ab", "cd", "pq", "xy"]
for i in range(len(x) - 1):
if x[i] + x[i + 1] in forbidden:
return True
return False
n = 0
for x in strings:
if contains_three_vowels(x) and contains_dubble(x) and not contains_forbidden(x):
n += 1
print("Number of nice strings: {}".format(n))
def part2():
def contains_pairs(x):
for i in range(len(x) - 3):
if x.find(x[i] + x[i + 1], i + 2) >= 0:
return True
return False
def contains_dubble(x):
for i in range(len(x) - 2):
if x[i] == x[i + 2]:
return True
return False
n = 0
for x in strings:
if contains_pairs(x) and contains_dubble(x):
n += 1
print("Number of nice strings: {}".format(n))
part1()
part2()
|
strings = ['sszojmmrrkwuftyv', 'isaljhemltsdzlum', 'fujcyucsrxgatisb', 'qiqqlmcgnhzparyg', 'oijbmduquhfactbc', 'jqzuvtggpdqcekgk', 'zwqadogmpjmmxijf', 'uilzxjythsqhwndh', 'gtssqejjknzkkpvw', 'wrggegukhhatygfi', 'vhtcgqzerxonhsye', 'tedlwzdjfppbmtdx', 'iuvrelxiapllaxbg', 'feybgiimfthtplui', 'qxmmcnirvkzfrjwd', 'vfarmltinsriqxpu', 'oanqfyqirkraesfq', 'xilodxfuxphuiiii', 'yukhnchvjkfwcbiq', 'bdaibcbzeuxqplop', 'ivegnnpbiyxqsion', 'ybahkbzpditgwdgt', 'dmebdomwabxgtctu', 'ibtvimgfaeonknoh', 'jsqraroxudetmfyw', 'dqdbcwtpintfcvuz', 'tiyphjunlxddenpj', 'fgqwjgntxagidhah', 'nwenhxmakxqkeehg', 'zdoheaxqpcnlhnen', 'tfetfqojqcdzlpbm', 'qpnxkuldeiituggg', 'xwttlbdwxohahwar', 'hjkwzadmtrkegzye', 'koksqrqcfwcaxeof', 'wulwmrptktliyxeq', 'gyufbedqhhyqgqzj', 'txpunzodohikzlmj', 'jloqfuejfkemcrvu', 'amnflshcheuddqtc', 'pdvcsduggcogbiia', 'yrioavgfmeafjpcz', 'uyhbtmbutozzqfvq', 'mwhgfwsgyuwcdzik', 'auqylgxhmullxpaa', 'lgelzivplaeoivzh', 'uyvcepielfcmswoa', 'qhirixgwkkccuzlp', 'zoonniyosmkeejfg', 'iayfetpixkedyana', 'ictqeyzyqswdskiy', 'ejsgqteafvmorwxe', 'lhaiqrlqqwfbrqdx', 'ydjyboqwhfpqfydc', 'dwhttezyanrnbybv', 'edgzkqeqkyojowvr', 'rmjfdwsqamjqehdq', 'ozminkgnkwqctrxz', 'bztjhxpjthchhfcd', 'vrtioawyxkivrpiq', 'dpbcsznkpkaaclyy', 'vpoypksymdwttpvz', 'hhdlruwclartkyap', 'bqkrcbrksbzcggbo', 'jerbbbnxlwfvlaiw', 'dwkasufidwjrjfbf', 'kkfxtjhbnmqbmfwf', 'vmnfziwqxmioukmj', 'rqxvcultipkecdtu', 'fhmfdibhtjzkiqsd', 'hdpjbuzzbyafqrpd', 'emszboysjuvwwvts', 'msyigmwcuybfiooq', 'druyksfnbluvnwoh', 'fvgstvynnfbvxhsx', 'bmzalvducnqtuune', 'lzwkzfzttsvpllei', 'olmplpvjamynfyfd', 'padcwfkhystsvyfb', 'wjhbvxkwtbfqdilb', 'hruaqjwphonnterf', 'bufjobjtvxtzjpmj', 'oiedrjvmlbtwyyuy', 'sgiemafwfztwsyju', 'nsoqqfudrtwszyqf', 'vonbxquiiwxnazyl', 'yvnmjxtptujwqudn', 'rrnybqhvrcgwvrkq', 'taktoxzgotzxntfu', 'quffzywzpxyaepxa', 'rfvjebfiddcfgmwv', 'iaeozntougqwnzoh', 'scdqyrhoqmljhoil', 'bfmqticltmfhxwld', 'brbuktbyqlyfpsdl', 'oidnyhjkeqenjlhd', 'kujsaiqojopvrygg', 'vebzobmdbzvjnjtk', 'uunoygzqjopwgmbg', 'piljqxgicjzgifso', 'ikgptwcjzywswqnw', 'pujqsixoisvhdvwi', 'trtuxbgigogfsbbk', 'mplstsqclhhdyaqk', 'gzcwflvmstogdpvo', 'tfjywbkmimyyqcjd', 'gijutvhruqcsiznq', 'ibxkhjvzzxgavkha', 'btnxeqvznkxjsgmq', 'tjgofgauxaelmjoq', 'sokshvyhlkxerjrv', 'ltogbivktqmtezta', 'uduwytzvqvfluyuf', 'msuckpthtgzhdxan', 'fqmcglidvhvpirzr', 'gwztkqpcwnutvfga', 'bsjfgsrntdhlpqbx', 'xloczbqybxmiopwt', 'orvevzyjliomkkgu', 'mzjbhmfjjvaziget', 'tlsdxuhwdmghdyjb', 'atoecyjhwmznaewi', 'pyxpyvvipbqibiox', 'ajbfmpqqobfsmesj', 'siknbzefjblnohgd', 'eqfhgewbblwdfkmc', 'opylbscrotckkrbk', 'lbwxbofgjkzdxkle', 'ceixfjstaptdomvm', 'hnkrqxifjmmjktie', 'aqykzeuzvvetoygd', 'fouahjimfcisxima', 'prkzhutbqsyrhjzx', 'qqwliakathnsbzne', 'sayhgqtlcqqidqhj', 'ygduolbysehdudra', 'zricvxhdzznuxuce', 'ucvzakslykpgsixd', 'udirhgcttmyspgsb', 'yuwzppjzfsjhhdzi', 'gtqergjiuwookwre', 'xvxexbjyjkxovvwf', 'mlpaqhnnkqxrmwmm', 'ezuqbrjozwuqafhb', 'mcarusdthcbsonoq', 'weeguqeheeiigrue', 'pngtfugozxofaqxv', 'copphvbjcmfspenv', 'jiyahihykjjkdaya', 'gdqnmesvptuyrfwp', 'vbdscfywqmfxbohh', 'crtrfuxyjypzubrg', 'seihvevtxywxhflp', 'fvvpmgttnapklwou', 'qmqaqsajmqwhetpk', 'zetxvrgjmblxvakr', 'kpvwblrizaabmnhz', 'mwpvvzaaicntrkcp', 'clqyjiegtdsswqfm', 'ymrcnqgcpldgfwtm', 'nzyqpdenetncgnwq', 'cmkzevgacnmdkqro', 'kzfdsnamjqbeirhi', 'kpxrvgvvxapqlued', 'rzskbnfobevzrtqu', 'vjoahbfwtydugzap', 'ykbbldkoijlvicbl', 'mfdmroiztsgjlasb', 'quoigfyxwtwprmdr', 'ekxjqafwudgwfqjm', 'obtvyjkiycxfcdpb', 'lhoihfnbuqelthof', 'eydwzitgxryktddt', 'rxsihfybacnpoyny', 'bsncccxlplqgygtw', 'rvmlaudsifnzhcqh', 'huxwsyjyebckcsnn', 'gtuqzyihwhqvjtes', 'zreeyomtngvztveq', 'nwddzjingsarhkxb', 'nuqxqtctpoldrlsh', 'wkvnrwqgjooovhpf', 'kwgueyiyffudtbyg', 'tpkzapnjxefqnmew', 'ludwccvkihagvxal', 'lfdtzhfadvabghna', 'njqmlsnrkcfhtvbb', 'cajzbqleghhnlgap', 'vmitdcozzvqvzatp', 'eelzefwqwjiywbcz', 'uyztcuptfqvymjpi', 'aorhnrpkjqqtgnfo', 'lfrxfdrduoeqmwwp', 'vszpjvbctblplinh', 'zexhadgpqfifcqrz', 'ueirfnshekpemqua', 'qfremlntihbwabtb', 'nwznunammfexltjc', 'zkyieokaaogjehwt', 'vlrxgkpclzeslqkq', 'xrqrwfsuacywczhs', 'olghlnfjdiwgdbqc', 'difnlxnedpqcsrdf', 'dgpuhiisybjpidsj', 'vlwmwrikmitmoxbt', 'sazpcmcnviynoktm', 'pratafauetiknhln', 'ilgteekhzwlsfwcn', 'ywvwhrwhkaubvkbl', 'qlaxivzwxyhvrxcf', 'hbtlwjdriizqvjfb', 'nrmsononytuwslsa', 'mpxqgdthpoipyhjc', 'mcdiwmiqeidwcglk', 'vfbaeavmjjemfrmo', 'qzcbzmisnynzibrc', 'shzmpgxhehhcejhb', 'wirtjadsqzydtyxd', 'qjlrnjfokkqvnpue', 'dxawdvjntlbxtuqc', 'wttfmnrievfestog', 'eamjfvsjhvzzaobg', 'pbvfcwzjgxahlrag', 'omvmjkqqnobvnzkn', 'lcwmeibxhhlxnkzv', 'uiaeroqfbvlazegs', 'twniyldyuonfyzqw', 'wgjkmsbwgfotdabi', 'hnomamxoxvrzvtew', 'ycrcfavikkrxxfgw', 'isieyodknagzhaxy', 'mgzdqwikzullzyco', 'mumezgtxjrrejtrs', 'nwmwjcgrqiwgfqel', 'wjgxmebfmyjnxyyp', 'durpspyljdykvzxf', 'zuslbrpooyetgafh', 'kuzrhcjwbdouhyme', 'wyxuvbciodscbvfm', 'kbnpvuqwmxwfqtqe', 'zddzercqogdpxmft', 'sigrdchxtgavzzjh', 'lznjolnorbuddgcs', 'ycnqabxlcajagwbt', 'bnaudeaexahdgxsj', 'rlnykxvoctfwanms', 'jngyetkoplrstfzt', 'tdpxknwacksotdub', 'yutqgssfoptvizgr', 'lzmqnxeqjfnsxmsa', 'iqpgfsfmukovsdgu', 'qywreehbidowtjyz', 'iozamtgusdctvnkw', 'ielmujhtmynlwcfd', 'hzxnhtbnmmejlkyf', 'ftbslbzmiqkzebtd', 'bcwdqgiiizmohack', 'dqhfkzeddjzbdlxu', 'mxopokqffisxosci', 'vciatxhtuechbylk', 'khtkhcvelidjdena', 'blatarwzfqcapkdt', 'elamngegnczctcck', 'xeicefdbwrxhuxuf', 'sawvdhjoeahlgcdr', 'kmdcimzsfkdfpnir', 'axjayzqlosrduajb', 'mfhzreuzzumvoggr', 'iqlbkbhrkptquldb', 'xcvztvlshiefuhgb', 'pkvwyqmyoazocrio', 'ajsxkdnerbmhyxaj', 'tudibgsbnpnizvsi', 'cxuiydkgdccrqvkh', 'cyztpjesdzmbcpot', 'nnazphxpanegwitx', 'uphymczbmjalmsct', 'yyxiwnlrogyzwqmg', 'gmqwnahjvvdyhnfa', 'utolskxpuoheugyl', 'mseszdhyzoyavepd', 'ycqknvbuvcjfgmlc', 'sknrxhxbfpvpeorn', 'zqxqjetooqcodwml', 'sesylkpvbndrdhsy', 'fryuxvjnsvnjrxlw', 'mfxusewqurscujnu', 'mbitdjjtgzchvkfv', 'ozwlyxtaalxofovd', 'wdqcduaykxbunpie', 'rlnhykxiraileysk', 'wgoqfrygttlamobg', 'kflxzgxvcblkpsbz', 'tmkisflhativzhde', 'owsdrfgkaamogjzd', 'gaupjkvkzavhfnes', 'wknkurddcknbdleg', 'lltviwincmbtduap', 'qwzvspgbcksyzzmb', 'ydzzkumecryfjgnk', 'jzvmwgjutxoysaam', 'icrwpyhxllbardkr', 'jdopyntshmvltrve', 'afgkigxcuvmdbqou', 'mfzzudntmvuyhjzt', 'duxhgtwafcgrpihc', 'tsnhrkvponudumeb', 'sqtvnbeiigdzbjgv', 'eczmkqwvnsrracuo', 'mhehsgqwiczaiaxv', 'kaudmfvifovrimpd', 'lupikgivechdbwfr', 'mwaaysrndiutuiqx', 'aacuiiwgaannunmm', 'tjqjbftaqitukwzp', 'lrcqyskykbjpaekn', 'lirrvofbcqpjzxmr', 'jurorvzpplyelfml', 'qonbllojmloykjqe', 'sllkzqujfnbauuqp', 'auexjwsvphvikali', 'usuelbssqmbrkxyc', 'wyuokkfjexikptvv', 'wmfedauwjgbrgytl', 'sfwvtlzzebxzmuvw', 'rdhqxuechjsjcvaf', 'kpavhqkukugocsxu', 'ovnjtumxowbxduts', 'zgerpjufauptxgat', 'pevvnzjfwhjxdoxq', 'pmmfwxajgfziszcs', 'difmeqvaghuitjhs', 'icpwjbzcmlcterwm', 'ngqpvhajttxuegyh', 'mosjlqswdngwqsmi', 'frlvgpxrjolgodlu', 'eazwgrpcxjgoszeg', 'bbtsthgkjrpkiiyk', 'tjonoglufuvsvabe', 'xhkbcrofytmbzrtk', 'kqftfzdmpbxjynps', 'kmeqpocbnikdtfyv', 'qjjymgqxhnjwxxhp', 'dmgicrhgbngdtmjt', 'zdxrhdhbdutlawnc', 'afvoekuhdboxghvx', 'hiipezngkqcnihty', 'bbmqgheidenweeov', 'suprgwxgxwfsgjnx', 'adeagikyamgqphrj', 'zzifqinoeqaorjxg', 'adhgppljizpaxzld', 'lvxyieypvvuqjiyc', 'nljoakatwwwoovzn', 'fcrkfxclcacshhmx', 'ownnxqtdhqbgthch', 'lmfylrcdmdkgpwnj', 'hlwjfbvlswbzpbjr', 'mkofhdtljdetcyvp', 'synyxhifbetzarpo', 'agnggugngadrcxoc', 'uhttadmdmhidpyjw', 'ohfwjfhunalbubpr', 'pzkkkkwrlvxiuysn', 'kmidbxmyzkjrwjhu', 'egtitdydwjxmajnw', 'civoeoiuwtwgbqqs', 'dfptsguzfinqoslk', 'tdfvkreormspprer', 'zvnvbrmthatzztwi', 'ffkyddccrrfikjde', 'hrrmraevdnztiwff', 'qaeygykcpbtjwjbr', 'purwhitkmrtybslh', 'qzziznlswjaussel', 'dfcxkvdpqccdqqxj', 'tuotforulrrytgyn', 'gmtgfofgucjywkev', 'wkyoxudvdkbgpwhd', 'qbvktvfvipftztnn', 'otckgmojziezmojb', 'inxhvzbtgkjxflay', 'qvxapbiatuudseno', 'krpvqosbesnjntut', 'oqeukkgjsfuqkjbb', 'prcjnyymnqwqksiz', 'vuortvjxgckresko', 'orqlyobvkuwgathr', 'qnpyxlnazyfuijox', 'zwlblfkoklqmqzkw', 'hmwurwtpwnrcsanl', 'jzvxohuakopuzgpf', 'sfcpnxrviphhvxmx', 'qtwdeadudtqhbely', 'dbmkmloasqphnlgj', 'olylnjtkxgrubmtk', 'nxsdbqjuvwrrdbpq', 'wbabpirnpcsmpipw', 'hjnkyiuxpqrlvims', 'enzpntcjnxdpuqch', 'vvvqhlstzcizyimn', 'triozhqndbttglhv', 'fukvgteitwaagpzx', 'uhcvukfbmrvskpen', 'tizcyupztftzxdmt', 'vtkpnbpdzsaluczz', 'wodfoyhoekidxttm', 'otqocljrmwfqbxzu', 'linfbsnfvixlwykn', 'vxsluutrwskslnye', 'zbshygtwugixjvsi', 'zdcqwxvwytmzhvoo', 'wrseozkkcyctrmei', 'fblgtvogvkpqzxiy', 'opueqnuyngegbtnf', 'qxbovietpacqqxok', 'zacrdrrkohfygddn', 'gbnnvjqmkdupwzpq', 'qgrgmsxeotozvcak', 'hnppukzvzfmlokid', 'dzbheurndscrrtcl', 'wbgdkadtszebbrcw', 'fdmzppzphhpzyuiz', 'bukomunhrjrypohj', 'ohodhelegxootqbj', 'rsplgzarlrknqjyh', 'punjjwpsxnhpzgvu', 'djdfahypfjvpvibm', 'mlgrqsmhaozatsvy', 'xwktrgyuhqiquxgn', 'wvfaoolwtkbrisvf', 'plttjdmguxjwmeqr', 'zlvvbwvlhauyjykw', 'cigwkbyjhmepikej', 'masmylenrusgtyxs', 'hviqzufwyetyznze', 'nzqfuhrooswxxhus', 'pdbdetaqcrqzzwxf', 'oehmvziiqwkzhzib', 'icgpyrukiokmytoy', 'ooixfvwtiafnwkce', 'rvnmgqggpjopkihs', 'wywualssrmaqigqk', 'pdbvflnwfswsrirl', 'jeaezptokkccpbuj', 'mbdwjntysntsaaby', 'ldlgcawkzcwuxzpz', 'lwktbgrzswbsweht', 'ecspepmzarzmgpjm', 'qmfyvulkmkxjncai', 'izftypvwngiukrns', 'zgmnyjfeqffbooww', 'nyrkhggnprhedows', 'yykzzrjmlevgffah', 'mavaemfxhlfejfki', 'cmegmfjbkvpncqwf', 'zxidlodrezztcrij', 'fseasudpgvgnysjv', 'fupcimjupywzpqzp', 'iqhgokavirrcvyys', 'wjmkcareucnmfhui', 'nftflsqnkgjaexhq', 'mgklahzlcbapntgw', 'kfbmeavfxtppnrxn', 'nuhyvhknlufdynvn', 'nviogjxbluwrcoec', 'tyozixxxaqiuvoys', 'kgwlvmvgtsvxojpr', 'moeektyhyonfdhrb', 'kahvevmmfsmiiqex', 'xcywnqzcdqtvhiwd', 'fnievhiyltbvtvem', 'jlmndqufirwgtdxd', 'muypbfttoeelsnbs', 'rypxzbnujitfwkou', 'ubmmjbznskildeoj', 'ofnmizdeicrmkjxp', 'rekvectjbmdnfcib', 'yohrojuvdexbctdh', 'gwfnfdeibynzjmhz', 'jfznhfcqdwlpjull', 'scrinzycfhwkmmso', 'mskutzossrwoqqsi', 'rygoebkzgyzushhr', 'jpjqiycflqkexemx', 'arbufysjqmgaapnl', 'dbjerflevtgweeoj', 'snybnnjlmwjvhois', 'fszuzplntraprmbj', 'mkvaatolvuggikvg', 'zpuzuqygoxesnuyc', 'wnpxvmxvllxalulm', 'eivuuafkvudeouwy', 'rvzckdyixetfuehr', 'qgmnicdoqhveahyx', 'miawwngyymshjmpj', 'pvckyoncpqeqkbmx', 'llninfenrfjqxurv', 'kzbjnlgsqjfuzqtp', 'rveqcmxomvpjcwte', 'bzotkawzbopkosnx', 'ktqvpiribpypaymu', 'wvlzkivbukhnvram', 'uohntlcoguvjqqdo', 'ajlsiksjrcnzepkt', 'xsqatbldqcykwusd', 'ihbivgzrwpmowkop', 'vfayesfojmibkjpb', 'uaqbnijtrhvqxjtb', 'hhovshsfmvkvymba', 'jerwmyxrfeyvxcgg', 'hncafjwrlvdcupma', 'qyvigggxfylbbrzt', 'hiiixcyohmvnkpgk', 'mmitpwopgxuftdfu', 'iaxderqpceboixoa', 'zodfmjhuzhnsqfcb', 'sthtcbadrclrazsi', 'bkkkkcwegvypbrio', 'wmpcofuvzemunlhj', 'gqwebiifvqoeynro', 'juupusqdsvxcpsgv', 'rbhdfhthxelolyse', 'kjimpwnjfrqlqhhz', 'rcuigrjzarzpjgfq', 'htxcejfyzhydinks', 'sxucpdxhvqjxxjwf', 'omsznfcimbcwaxal', 'gufmtdlhgrsvcosb', 'bssshaqujtmluerz', 'uukotwjkstgwijtr', 'kbqkneobbrdogrxk', 'ljqopjcjmelgrakz', 'rwtfnvnzryujwkfb', 'dedjjbrndqnilbeh', 'nzinsxnpptzagwlb', 'lwqanydfirhnhkxy', 'hrjuzfumbvfccxno', 'okismsadkbseumnp', 'sfkmiaiwlktxqvwa', 'hauwpjjwowbunbjj', 'nowkofejwvutcnui', 'bqzzppwoslaeixro', 'urpfgufwbtzenkpj', 'xgeszvuqwxeykhef', 'yxoldvkyuikwqyeq', 'onbbhxrnmohzskgg', 'qcikuxakrqeugpoa', 'lnudcqbtyzhlpers', 'nxduvwfrgzaailgl', 'xniuwvxufzxjjrwz', 'ljwithcqmgvntjdj', 'awkftfagrfzywkhs', 'uedtpzxyubeveuek', 'bhcqdwidbjkqqhzl', 'iyneqjdmlhowwzxx', 'kvshzltcrrururty', 'zgfpiwajegwezupo', 'tkrvyanujjwmyyri', 'ercsefuihcmoaiep', 'ienjrxpmetinvbos', 'jnwfutjbgenlipzq', 'bgohjmrptfuamzbz', 'rtsyamajrhxbcncw', 'tfjdssnmztvbnscs', 'bgaychdlmchngqlp', 'kfjljiobynhwfkjo', 'owtdxzcpqleftbvn', 'ltjtimxwstvzwzjj', 'wbrvjjjajuombokf', 'zblpbpuaqbkvsxye', 'gwgdtbpnlhyqspdi', 'abipqjihjqfofmkx', 'nlqymnuvjpvvgova', 'avngotmhodpoufzn', 'qmdyivtzitnrjuae', 'xfwjmqtqdljuerxi', 'csuellnlcyqaaamq', 'slqyrcurcyuoxquo', 'dcjmxyzbzpohzprl', 'uqfnmjwniyqgsowb', 'rbmxpqoblyxdocqc', 'ebjclrdbqjhladem', 'ainnfhxnsgwqnmyo', 'eyytjjwhvodtzquf', 'iabjgmbbhilrcyyp', 'pqfnehkivuelyccc', 'xgjbyhfgmtseiimt', 'jwxyqhdbjiqqqeyy', 'gxsbrncqkmvaryln', 'vhjisxjkinaejytk', 'seexagcdmaedpcvh', 'lvudfgrcpjxzdpvd', 'fxtegyrqjzhmqean', 'dnoiseraqcoossmc', 'nwrhmwwbykvwmgep', 'udmzskejvizmtlce', 'hbzvqhvudfdlegaa', 'cghmlfqejbxewskv', 'bntcmjqfwomtbwsb', 'qezhowyopjdyhzng', 'todzsocdkgfxanbz', 'zgjkssrjlwxuhwbk', 'eibzljqsieriyrzr', 'wamxvzqyycrxotjp', 'epzvfkispwqynadu', 'dwlpfhtrafrxlyie', 'qhgzujhgdruowoug', 'girstvkahaemmxvh', 'baitcrqmxhazyhbl', 'xyanqcchbhkajdmc', 'gfvjmmcgfhvgnfdq', 'tdfdbslwncbnkzyz', 'jojuselkpmnnbcbb', 'hatdslkgxtqpmavj', 'dvelfeddvgjcyxkj', 'gnsofhkfepgwltse', 'mdngnobasfpewlno', 'qssnbcyjgmkyuoga', 'glvcmmjytmprqwvn', 'gwrixumjbcdffsdl', 'lozravlzvfqtsuiq', 'sicaflbqdxbmdlch', 'inwfjkyyqbwpmqlq', 'cuvszfotxywuzhzi', 'igfxyoaacoarlvay', 'ucjfhgdmnjvgvuni', 'rvvkzjsytqgiposh', 'jduinhjjntrmqroz', 'yparkxbgsfnueyll', 'lyeqqeisxzfsqzuj', 'woncskbibjnumydm', 'lltucklragtjmxtl', 'ubiyvmyhlesfxotj', 'uecjseeicldqrqww', 'xxlxkbcthufnjbnm', 'lhqijovvhlffpxga', 'fzdgqpzijitlogjz', 'efzzjqvwphomxdpd', 'jvgzvuyzobeazssc', 'hejfycgxywfjgbfw', 'yhjjmvkqfbnbliks', 'sffvfyywtlntsdsz', 'dwmxqudvxqdenrur', 'asnukgppdemxrzaz', 'nwqfnumblwvdpphx', 'kqsmkkspqvxzuket', 'cpnraovljzqiquaz', 'qrzgrdlyyzbyykhg', 'opoahcbiydyhsmqe', 'hjknnfdauidjeydr', 'hczdjjlygoezadow', 'rtflowzqycimllfv', 'sfsrgrerzlnychhq', 'bpahuvlblcolpjmj', 'albgnjkgmcrlaicl', 'pijyqdhfxpaxzdex', 'eeymiddvcwkpbpux', 'rqwkqoabywgggnln', 'vckbollyhgbgmgwh', 'ylzlgvnuvpynybkm', 'hpmbxtpfosbsjixt', 'ocebeihnhvkhjfqz', 'tvctyxoujdgwayze', 'efvhwxtuhapqxjen', 'rusksgefyidldmpo', 'nkmtjvddfmhirmzz', 'whvtsuadwofzmvrt', 'iiwjqvsdxudhdzzk', 'gucirgxaxgcassyo', 'rmhfasfzexeykwmr', 'hynlxcvsbgosjbis', 'huregszrcaocueen', 'pifezpoolrnbdqtv', 'unatnixzvdbqeyox', 'xtawlpduxgacchfe', 'bdvdbflqfphndduf', 'xtdsnjnmzccfptyt', 'nkhsdkhqtzqbphhg', 'aqcubmfkczlaxiyb', 'moziflxpsfubucmv', 'srdgnnjtfehiimqx', 'pwfalehdfyykrohf', 'sysxssmvewyfjrve', 'brsemdzosgqvvlxe', 'bimbjoshuvflkiat', 'hkgjasmljkpkwwku', 'sbnmwjvodygobpqc', 'bbbqycejueruihhd', 'corawswvlvneipyc', 'gcyhknmwsczcxedh', 'kppakbffdhntmcqp', 'ynulzwkfaemkcefp', 'pyroowjekeurlbii', 'iwksighrswdcnmxf', 'glokrdmugreygnsg', 'xkmvvumnfzckryop', 'aesviofpufygschi', 'csloawlirnegsssq', 'fkqdqqmlzuxbkzbc', 'uzlhzcfenxdfjdzp', 'poaaidrktteusvyf', 'zrlyfzmjzfvivcfr', 'qwjulskbniitgqtx', 'gjeszjksbfsuejki', 'vczdejdbfixbduaq', 'knjdrjthitjxluth', 'jweydeginrnicirl', 'bottrfgccqhyycsl', 'eiquffofoadmbuhk', 'lbqfutmzoksscswf', 'xfmdvnvfcnzjprba', 'uvugkjbkhlaoxmyx', 'wadlgtpczgvcaqqv', 'inzrszbtossflsxk', 'dbzbtashaartczrj', 'qbjiqpccefcfkvod', 'hluujmokjywotvzy', 'thwlliksfztcmwzh', 'arahybspdaqdexrq', 'nuojrmsgyipdvwyx', 'hnajdwjwmzattvst', 'sulcgaxezkprjbgu', 'rjowuugwdpkjtypw', 'oeugzwuhnrgiaqga', 'wvxnyymwftfoswij', 'pqxklzkjpcqscvde', 'tuymjzknntekglqj', 'odteewktugcwlhln', 'exsptotlfecmgehc', 'eeswfcijtvzgrqel', 'vjhrkiwmunuiwqau', 'zhlixepkeijoemne', 'pavfsmwesuvebzdd', 'jzovbklnngfdmyws', 'nbajyohtzfeoiixz', 'ciozmhrsjzrwxvhz', 'gwucrxieqbaqfjuv', 'uayrxrltnohexawc', 'flmrbhwsfbcquffm', 'gjyabmngkitawlxc', 'rwwtggvaygfbovhg', 'xquiegaisynictjq', 'oudzwuhexrwwdbyy', 'lengxmguyrwhrebb', 'uklxpglldbgqsjls', 'dbmvlfeyguydfsxq', 'zspdwdqcrmtmdtsc', 'mqfnzwbfqlauvrgc', 'amcrkzptgacywvhv', 'ndxmskrwrqysrndf', 'mwjyhsufeqhwisju', 'srlrukoaenyevykt', 'tnpjtpwawrxbikct', 'geczalxmgxejulcv', 'tvkcbqdhmuwcxqci', 'tiovluvwezwwgaox', 'zrjhtbgajkjqzmfo', 'vcrywduwsklepirs', 'lofequdigsszuioy', 'wxsdzomkjqymlzat', 'iabaczqtrfbmypuy', 'ibdlmudbajikcncr', 'rqcvkzsbwmavdwnv', 'ypxoyjelhllhbeog', 'fdnszbkezyjbttbg', 'uxnhrldastpdjkdz', 'xfrjbehtxnlyzcka', 'omjyfhbibqwgcpbv', 'eguucnoxaoprszmp', 'xfpypldgcmcllyzz', 'aypnmgqjxjqceelv', 'mgzharymejlafvgf', 'tzowgwsubbaigdok', 'ilsehjqpcjwmylxc', 'pfmouwntfhfnmrwk', 'csgokybgdqwnduwp', 'eaxwvxvvwbrovypz', 'nmluqvobbbmdiwwb', 'lnkminvfjjzqbmio', 'mjiiqzycqdhfietz', 'towlrzriicyraevq', 'obiloewdvbrsfwjo', 'lmeooaajlthsfltw', 'ichygipzpykkesrw', 'gfysloxmqdsfskvt', 'saqzntehjldvwtsx', 'pqddoemaufpfcaew', 'mjrxvbvwcreaybwe', 'ngfbrwfqnxqosoai', 'nesyewxreiqvhald', 'kqhqdlquywotcyfy', 'liliptyoqujensfi', 'nsahsaxvaepzneqq', 'zaickulfjajhctye', 'gxjzahtgbgbabtht', 'koxbuopaqhlsyhrp', 'jhzejdjidqqtjnwe', 'dekrkdvprfqpcqki', 'linwlombdqtdeyop', 'dvckqqbnigdcmwmx', 'yaxygbjpzkvnnebv', 'rlzkdkgaagmcpxah', 'cfzuyxivtknirqvt', 'obivkajhsjnrxxhn', 'lmjhayymgpseuynn', 'bbjyewkwadaipyju', 'lmzyhwomfypoftuu', 'gtzhqlgltvatxack', 'jfflcfaqqkrrltgq', 'txoummmnzfrlrmcg', 'ohemsbfuqqpucups', 'imsfvowcbieotlok', 'tcnsnccdszxfcyde', 'qkcdtkwuaquajazz', 'arcfnhmdjezdbqku', 'srnocgyqrlcvlhkb', 'mppbzvfmcdirbyfw', 'xiuarktilpldwgwd', 'ypufwmhrvzqmexpc', 'itpdnsfkwgrdujmj', 'cmpxnodtsswkyxkr', 'wayyxtjklfrmvbfp', 'mfaxphcnjczhbbwy', 'sjxhgwdnqcofbdra', 'pnxmujuylqccjvjm', 'ivamtjbvairwjqwl', 'deijtmzgpfxrclss', 'bzkqcaqagsynlaer', 'tycefobvxcvwaulz', 'ctbhnywezxkdsswf', 'urrxxebxrthtjvib', 'fpfelcigwqwdjucv', 'ngfcyyqpqulwcphb', 'rltkzsiipkpzlgpw', 'qfdsymzwhqqdkykc', 'balrhhxipoqzmihj', 'rnwalxgigswxomga', 'ghqnxeogckshphgr', 'lyyaentdizaumnla', 'exriodwfzosbeoib', 'speswfggibijfejk', 'yxmxgfhvmshqszrq', 'hcqhngvahzgawjga', 'qmhlsrfpesmeksur', 'eviafjejygakodla', 'kvcfeiqhynqadbzv', 'fusvyhowslfzqttg', 'girqmvwmcvntrwau', 'yuavizroykfkdekz', 'jmcwohvmzvowrhxf', 'kzimlcpavapynfue', 'wjudcdtrewfabppq', 'yqpteuxqgbmqfgxh', 'xdgiszbuhdognniu', 'jsguxfwhpftlcjoh', 'whakkvspssgjzxre', 'ggvnvjurlyhhijgm', 'krvbhjybnpemeptr', 'pqedgfojyjybfbzr', 'jzhcrsgmnkwwtpdo', 'yyscxoxwofslncmp', 'gzjhnxytmyntzths', 'iteigbnqbtpvqumi', 'zjevfzusnjukqpfw', 'xippcyhkfuounxqk', 'mcnhrcfonfdgpkyh', 'pinkcyuhjkexbmzj', 'lotxrswlxbxlxufs', 'fmqajrtoabpckbnu', 'wfkwsgmcffdgaqxg', 'qfrsiwnohoyfbidr', 'czfqbsbmiuyusaqs', 'ieknnjeecucghpoo', 'cevdgqnugupvmsge', 'gjkajcyjnxdrtuvr', 'udzhrargnujxiclq', 'zqqrhhmjwermjssg', 'ggdivtmgoqajydzz', 'wnpfsgtxowkjiivl', 'afbhqawjbotxnqpd', 'xjpkifkhfjeqifdn', 'oyfggzsstfhvticp', 'kercaetahymeawxy', 'khphblhcgmbupmzt', 'iggoqtqpvaebtiol', 'ofknifysuasshoya', 'qxuewroccsbogrbv', 'apsbnbkiopopytgu', 'zyahfroovfjlythh', 'bxhjwfgeuxlviydq', 'uvbhdtvaypasaswa', 'qamcjzrmesqgqdiz', 'hjnjyzrxntiycyel', 'wkcrwqwniczwdxgq', 'hibxlvkqakusswkx', 'mzjyuenepwdgrkty', 'tvywsoqslfsulses', 'jqwcwuuisrclircv', 'xanwaoebfrzhurct', 'ykriratovsvxxasf', 'qyebvtqqxbjuuwuo', 'telrvlwvriylnder', 'acksrrptgnhkeiaa', 'yemwfjhiqlzsvdxf', 'banrornfkcymmkcc', 'ytbhxvaeiigjpcgm', 'crepyazgxquposkn', 'xlqwdrytzwnxzwzv', 'xtrbfbwopxscftps', 'kwbytzukgseeyjla', 'qtfdvavvjogybxjg', 'ytbmvmrcxwfkgvzw', 'nbscbdskdeocnfzr', 'sqquwjbdxsxhcseg', 'ewqxhigqcgszfsuw', 'cvkyfcyfmubzwsee', 'dcoawetekigxgygd', 'ohgqnqhfimyuqhvi', 'otisopzzpvnhctte', 'bauieohjejamzien', 'ewnnopzkujbvhwce', 'aeyqlskpaehagdiv', 'pncudvivwnnqspxy', 'ytugesilgveokxcg', 'zoidxeelqdjesxpr', 'ducjccsuaygfchzj', 'smhgllqqqcjfubfc', 'nlbyyywergronmir', 'prdawpbjhrzsbsvj', 'nmgzhnjhlpcplmui', 'eflaogtjghdjmxxz', 'qolvpngucbkprrdc', 'ixywxcienveltgho', 'mwnpqtocagenkxut', 'iskrfbwxonkguywx', 'ouhtbvcaczqzmpua', 'srewprgddfgmdbao', 'dyufrltacelchlvu', 'czmzcbrkecixuwzz', 'dtbeojcztzauofuk', 'prrgoehpqhngfgmw', 'baolzvfrrevxsyke', 'zqadgxshwiarkzwh', 'vsackherluvurqqj', 'surbpxdulvcvgjbd', 'wqxytarcxzgxhvtx', 'vbcubqvejcfsgrac', 'zqnjfeapshjowzja', 'hekvbhtainkvbynx', 'knnugxoktxpvoxnh', 'knoaalcefpgtvlwm', 'qoakaunowmsuvkus', 'ypkvlzcduzlezqcb', 'ujhcagawtyepyogh', 'wsilcrxncnffaxjf', 'gbbycjuscquaycrk', 'aduojapeaqwivnly', 'ceafyxrakviagcjy', 'nntajnghicgnrlst', 'vdodpeherjmmvbje', 'wyyhrnegblwvdobn', 'xlfurpghkpbzhhif', 'xyppnjiljvirmqjo', 'kglzqahipnddanpi', 'omjateouxikwxowr', 'ocifnoopfglmndcx', 'emudcukfbadyijev', 'ooktviixetfddfmh', 'wtvrhloyjewdeycg', 'cgjncqykgutfjhvb', 'nkwvpswppeffmwad', 'hqbcmfhzkxmnrivg', 'mdskbvzguxvieilr', 'anjcvqpavhdloaqh', 'erksespdevjylenq', 'fadxwbmisazyegup', 'iyuiffjmcaahowhj', 'ygkdezmynmltodbv', 'fytneukxqkjattvh', 'woerxfadbfrvdcnz', 'iwsljvkyfastccoa', 'movylhjranlorofe', 'drdmicdaiwukemep', 'knfgtsmuhfcvvshg', 'ibstpbevqmdlhajn', 'tstwsswswrxlzrqs', 'estyydmzothggudf', 'jezogwvymvikszwa', 'izmqcwdyggibliet', 'nzpxbegurwnwrnca', 'kzkojelnvkwfublh', 'xqcssgozuxfqtiwi', 'tcdoigumjrgvczfv', 'ikcjyubjmylkwlwq', 'kqfivwystpqzvhan', 'bzukgvyoqewniivj', 'iduapzclhhyfladn', 'fbpyzxdfmkrtfaeg', 'yzsmlbnftftgwadz']
def part1():
def contains_three_vowels(x):
n = 0
for c in x:
if c in 'aeiou':
n += 1
return n >= 3
def contains_dubble(x):
for i in range(len(x) - 1):
if x[i] == x[i + 1]:
return True
return False
def contains_forbidden(x):
forbidden = ['ab', 'cd', 'pq', 'xy']
for i in range(len(x) - 1):
if x[i] + x[i + 1] in forbidden:
return True
return False
n = 0
for x in strings:
if contains_three_vowels(x) and contains_dubble(x) and (not contains_forbidden(x)):
n += 1
print('Number of nice strings: {}'.format(n))
def part2():
def contains_pairs(x):
for i in range(len(x) - 3):
if x.find(x[i] + x[i + 1], i + 2) >= 0:
return True
return False
def contains_dubble(x):
for i in range(len(x) - 2):
if x[i] == x[i + 2]:
return True
return False
n = 0
for x in strings:
if contains_pairs(x) and contains_dubble(x):
n += 1
print('Number of nice strings: {}'.format(n))
part1()
part2()
|
"""
Time Complexity = O(log(N))
Space Complexity = O(1)
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part
of the result is returned.
Example:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
"""
|
"""
Time Complexity = O(log(N))
Space Complexity = O(1)
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part
of the result is returned.
Example:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
"""
|
minha_matriz1 = [[1], [2], [3]]
minha_matriz2 = [[1, 2, 3], [4, 5, 6]]
def imprime_matriz(matriz):
for i in matriz:
linha = ''
for j in i:
linha += str(j)
print(" ".join(linha), end="")
print()
# imprime_matriz(minha_matriz1)
# imprime_matriz(minha_matriz2)
|
minha_matriz1 = [[1], [2], [3]]
minha_matriz2 = [[1, 2, 3], [4, 5, 6]]
def imprime_matriz(matriz):
for i in matriz:
linha = ''
for j in i:
linha += str(j)
print(' '.join(linha), end='')
print()
|
def get_column(game, col_num):
''' Get the columns '''
col = col_num
result = []
for i in range(0, 3):
temp = game[i]
result.append(temp[col])
return result
def print_odd_cubes_to_number(number):
''' Print odds and their cubes '''
if number < 1:
print('ERROR: number must be at least 1')
else:
for i in range(1, number + 1):
if i % 2 != 0:
print(i, '*', i, '*', i, '=', i ** 3)
def print_hundred(nums):
''' Rewrite with while-loop '''
total = 0
i = 0
while total <= 100 and i < len(nums):
total = nums[i] + total
print(nums[i])
i = i + 1
def my_enumerate(items):
''' Like enumerate() '''
temp = []
for i in range(0, len(items)):
temp_1 = (i, items[i])
temp.append(temp_1)
return temp
def num_rushes(slope_height, rush_height_gain, back_sliding):
''' Use the template '''
current_height = 0
rushes = 0
while current_height < slope_height:
current_height = current_height + rush_height_gain
rushes = rushes + 1
if current_height >= slope_height:
break
else:
current_height = current_height - back_sliding
return rushes
def rumbletron(strings):
''' Reserve and capitalize '''
temp = []
for i in range(0, len(strings)):
string = strings[i]
string = string[::-1]
string = string.upper()
temp.append(string)
return temp
|
def get_column(game, col_num):
""" Get the columns """
col = col_num
result = []
for i in range(0, 3):
temp = game[i]
result.append(temp[col])
return result
def print_odd_cubes_to_number(number):
""" Print odds and their cubes """
if number < 1:
print('ERROR: number must be at least 1')
else:
for i in range(1, number + 1):
if i % 2 != 0:
print(i, '*', i, '*', i, '=', i ** 3)
def print_hundred(nums):
""" Rewrite with while-loop """
total = 0
i = 0
while total <= 100 and i < len(nums):
total = nums[i] + total
print(nums[i])
i = i + 1
def my_enumerate(items):
""" Like enumerate() """
temp = []
for i in range(0, len(items)):
temp_1 = (i, items[i])
temp.append(temp_1)
return temp
def num_rushes(slope_height, rush_height_gain, back_sliding):
""" Use the template """
current_height = 0
rushes = 0
while current_height < slope_height:
current_height = current_height + rush_height_gain
rushes = rushes + 1
if current_height >= slope_height:
break
else:
current_height = current_height - back_sliding
return rushes
def rumbletron(strings):
""" Reserve and capitalize """
temp = []
for i in range(0, len(strings)):
string = strings[i]
string = string[::-1]
string = string.upper()
temp.append(string)
return temp
|
class Transformer(object):
mappings = {}
value_mappings_functions = {}
def __init__(self, initial_data):
self.initial_data = initial_data
def transform_dict(self, obj: dict):
result = {}
for k, v in obj.items():
if k in self.mappings.keys():
if k in self.value_mappings_functions.keys():
result[self.mappings.get(k)] = self.value_mappings_functions[k](v)
else:
result[self.mappings.get(k)] = v
return result
def transform(self):
if type(self.initial_data) == list:
return [self.transform_dict(i) for i in self.initial_data]
return self.transform_dict(self.initial_data)
|
class Transformer(object):
mappings = {}
value_mappings_functions = {}
def __init__(self, initial_data):
self.initial_data = initial_data
def transform_dict(self, obj: dict):
result = {}
for (k, v) in obj.items():
if k in self.mappings.keys():
if k in self.value_mappings_functions.keys():
result[self.mappings.get(k)] = self.value_mappings_functions[k](v)
else:
result[self.mappings.get(k)] = v
return result
def transform(self):
if type(self.initial_data) == list:
return [self.transform_dict(i) for i in self.initial_data]
return self.transform_dict(self.initial_data)
|
# Main driver file for user input and displaying
# Also checks legal moves and keep a move log
class GameState():
def __init__(self):
# Initial board state
# Board is 8x8 2d list with each element having 2 characters
# First character represents the color: w = white & b = black
# Second character represents the type: R = Rook, K = King, etc.
# "--" represents a empty space
self.board = [
["bR", "bN", "bB", "bQ", "bK", "bB", "bN", "bR"],
["bp", "bp", "bp", "bp", "bp", "bp", "bp", "bp"],
["--", "--", "--", "--", "--", "--", "--", "--"],
["--", "--", "--", "--", "--", "--", "--", "--"],
["--", "--", "--", "--", "--", "--", "--", "--"],
["--", "--", "--", "--", "--", "--", "--", "--"],
["wp", "wp", "wp", "wp", "wp", "wp", "wp", "wp"],
["wR", "wN", "wB", "wQ", "wK", "wB", "wN", "wR"]
]
self.moveFunctions = {"p" : self.getPawnMoves, "R" : self.getRookMoves, "N" : self.getKnightMoves, "Q" : self.getQueenMoves, "K" : self.getKingMoves, "B" : self.getBishopMoves}
self.whiteToMove = True
self.moveLog = []
self.whiteKingLocation = (7, 4)
self.blackKingLocation = (0, 4)
self.checkMate = False
self.stalemate = False
self.enpassantPossible = ()
self.currentCastlingRight = CastleRights(True, True, True, True)
self.castleRightsLog = [CastleRights(self.currentCastlingRight.wks, self.currentCastlingRight.bks, self.currentCastlingRight.wqs, self.currentCastlingRight.bqs)]
#Takes a move as a parameter and executes it, doesn't work for castling, pawn promotion and en-passant
def makeMove(self, move):
self.board[move.startRow][move.startCol] = "--"
self.board[move.endRow][move.endCol] = move.pieceMoved
self.moveLog.append(move) # Log the move to see history/undo last move
self.whiteToMove = not self.whiteToMove # Switch turn to other player
# Updates King's position if moved
if move.pieceMoved == "wK":
self.whiteKingLocation = (move.endRow, move.endCol)
if move.pieceMoved == "bK":
self.blackKingLocation = (move.endRow, move.endCol)
# Pawn promotion
if move.isPawnPromotion:
self.board[move.endRow][move.endCol] = move.pieceMoved[0] + move.promotionChoice
# En-passant move
if move.isEnpassantMove:
self.board[move.startRow][move.endCol] = "--"
# Update enpassantPossible variable
if move.pieceMoved[1] == "p" and abs(move.startRow - move.endRow) == 2:
self.enpassantPossible = ((move.startRow + move.endRow) // 2, move.startCol)
else:
self.enpassantPossible = ()
# Castle move
if move.isCastlingMove:
if move.endCol - move.startCol == 2: # Kingside castle
self.board[move.endRow][move.endCol-1] = self.board[move.endRow][move.endCol+1] # Moves the rook
self.board[move.endRow][move.endCol+1] = "--"
else: # Queenside castle
self.board[move.endRow][move.endCol+1] = self.board[move.endRow][move.endCol-2]
self.board[move.endRow][move.endCol-2] = "--"
# Updating Castling rights
self.updateCastleRights(move)
self.castleRightsLog.append(CastleRights(self.currentCastlingRight.wks, self.currentCastlingRight.bks, self.currentCastlingRight.wqs, self.currentCastlingRight.bqs))
def undoMove(self):
if len(self.moveLog) != 0:
move = self.moveLog.pop() # Gets last move and removes it from movelog
self.board[move.startRow][move.startCol] = move.pieceMoved
self.board[move.endRow][move.endCol] = move.pieceCaptured
self.whiteToMove = not self.whiteToMove # Switches turn back to other player
# Updates King's position if moved
if move.pieceMoved == "wK":
self.whiteKingLocation = (move.startRow, move.startCol)
elif move.pieceMoved == "bK":
self.blackKingLocation = (move.startRow, move.startCol)
if move.isEnpassantMove:
self.board[move.endRow][move.endCol] = "--"
self.board[move.startRow][move.endCol] = move.pieceCaptured
self.enpassantPossible = (move.endRow, move.endCol)
if move.pieceMoved[1] == "p" and abs(move.startRow - move.endRow) == 2:
self.enpassantPossible = ()
# Undo-ing castling rights
self.castleRightsLog.pop()
self.currentCastlingRight = self.castleRightsLog[-1]
# Undo-ing castle move
if move.isCastlingMove:
if move.endCol - move.startCol == 2: # Kingside castle
self.board[move.endRow][move.endCol+1] = self.board[move.endRow][move.endCol-1]
self.board[move.endRow][move.endCol-1] = "--"
else:
self.board[move.endRow][move.endCol-2] = self.board[move.endRow][move.endCol+1]
self.board[move.endRow][move.endCol+1] = "--"
def updateCastleRights(self, move):
if move.pieceMoved == "wK":
self.currentCastlingRight.wks = False
self.currentCastlingRight.wqs = False
elif move.pieceMoved == "bK":
self.currentCastlingRight.bks = False
self.currentCastlingRight.bqs = False
elif move.pieceMoved == "wR":
if move.startRow == 7:
if move.startCol == 0:
self.currentCastlingRight.wqs = False
elif move.startCol == 7:
self.currentCastlingRight.wks = False
elif move.pieceMoved == "bR":
if move.startRow == 0:
if move.startCol == 0:
self.currentCastlingRight.bqs = False
elif move.startCol == 7:
self.currentCastlingRight.bks = False
# All posible moves when in check
def getValidMoves(self):
tempEnpassantPossible = self.enpassantPossible
tempCastleRights = CastleRights(self.currentCastlingRight.wks, self.currentCastlingRight.bks, self.currentCastlingRight.wqs, self.currentCastlingRight.bqs)
moves = self.getLegalMoves()
if self.whiteToMove:
self.getCastleMoves(self.whiteKingLocation[0], self.whiteKingLocation[1], moves)
else:
self.getCastleMoves(self.blackKingLocation[0], self.blackKingLocation[1], moves)
for i in range(len(moves)-1, -1, -1):
self.makeMove(moves[i])
self.whiteToMove = not self.whiteToMove
if self.inCheck():
moves.remove(moves[i])
self.whiteToMove = not self.whiteToMove
self.undoMove()
if len(moves) == 0: # Either Check Mate of Stalemate
if self.inCheck():
self.checkMate = True
else:
self.stalemate = True
self.enpassantPossible = tempEnpassantPossible
self.currentCastlingRight = tempCastleRights
return moves
# Determine if King is under attack
def inCheck(self):
if self.whiteToMove:
return self.squareUnderAttack(self.whiteKingLocation[0], self.whiteKingLocation[1])
else:
return self.squareUnderAttack(self.blackKingLocation[0], self.blackKingLocation[1])
# Determine if the enemy can attack a certain square
def squareUnderAttack(self, r, c):
self.whiteToMove = not self.whiteToMove # switch to opponent to see their moves
oppMoves = self.getLegalMoves()
self.whiteToMove = not self.whiteToMove
for move in oppMoves:
if move.endRow == r and move.endCol == c:
return True
return False
# All legal moves without being in check
def getLegalMoves(self):
moves = []
for r in range(len(self.board)):
for c in range(len(self.board[r])):
turn = self.board[r][c][0]
if (turn == "w" and self.whiteToMove) or (turn == "b" and not self.whiteToMove):
piece = self.board[r][c][1]
self.moveFunctions[piece](r, c, moves) # Calls the appropriate move function depending on the piece
return moves
#Define all possible moves for each piece
def getPawnMoves(self, r, c, moves):
if self.whiteToMove: # White pawn movement
if self.board[r-1][c] == "--":
moves.append(Move((r, c), (r-1, c), self.board))
if r == 6 and self.board[r-2][c] == "--":
moves.append(Move((r, c), (r-2, c), self.board))
if c-1 >= 0:
if self.board[r-1][c-1][0] == "b":
moves.append(Move((r, c), (r-1, c-1), self.board))
elif (r-1, c-1) == self.enpassantPossible:
moves.append(Move((r, c), (r-1, c-1), self.board, isEnpassantMove=True))
if c+1 <= 7:
if self.board[r-1][c+1][0] == "b":
moves.append(Move((r, c), (r-1, c+1), self.board))
elif (r-1, c+1) == self.enpassantPossible:
moves.append(Move((r, c), (r-1, c+1), self.board, isEnpassantMove=True))
else: # Black pawn movement
if self.board[r+1][c] == "--":
moves.append(Move((r, c), (r+1, c), self.board))
if r == 1 and self.board[r+2][c] == "--":
moves.append(Move((r, c), (r+2, c), self.board))
if c-1 >= 0:
if self.board[r+1][c-1][0] == "w":
moves.append(Move((r, c), (r+1, c-1), self.board))
elif (r+1, c-1) == self.enpassantPossible:
moves.append(Move((r, c), (r+1, c-1), self.board, isEnpassantMove=True))
if c+1 <= 7:
if self.board[r+1][c+1][0] == "w":
moves.append(Move((r, c), (r+1, c+1), self.board))
elif (r+1, c+1) == self.enpassantPossible:
moves.append(Move((r, c), (r+1, c+1), self.board, isEnpassantMove=True))
def getRookMoves(self, r, c, moves):
directions = ((-1, 0), (0, -1), (1, 0), (0, 1))
enemyColor = "b" if self.whiteToMove else "w"
for d in directions:
for i in range(1, 8):
endRow = r + d[0] * i
endCol = c + d[1] * i
if 0 <= endRow < 8 and 0 <= endCol < 8:
endPiece = self.board[endRow][endCol]
if endPiece == "--":
moves.append(Move((r, c), (endRow, endCol), self.board))
elif endPiece[0] == enemyColor:
moves.append(Move((r, c), (endRow, endCol), self.board))
break
else:
break
else:
break
def getBishopMoves(self, r, c, moves):
directions = ((-1, -1), (1, -1), (1, 1), (-1, 1))
enemyColor = "b" if self.whiteToMove else "w"
for d in directions:
for i in range(1, 8):
endRow = r + d[0] * i
endCol = c + d[1] * i
if 0 <= endRow < 8 and 0 <= endCol < 8:
endPiece = self.board[endRow][endCol]
if endPiece == "--":
moves.append(Move((r, c), (endRow, endCol), self.board))
elif endPiece[0] == enemyColor:
moves.append(Move((r, c), (endRow, endCol), self.board))
break
else:
break
else:
break
def getKnightMoves(self, r, c, moves):
knightMoves = ((-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1))
allyColor = "w" if self.whiteToMove else "b"
for m in knightMoves:
endRow = r + m[0]
endCol = c + m[1]
if 0 <= endRow < 8 and 0 <= endCol < 8:
endPiece = self.board[endRow][endCol]
if endPiece[0] != allyColor:
moves.append(Move((r, c), (endRow, endCol), self.board))
def getQueenMoves(self, r, c, moves):
self.getBishopMoves(r, c, moves)
self.getRookMoves(r, c, moves)
def getKingMoves(self, r, c, moves):
kingMoves = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (1, -1), (1, 1), (1, 0), (0, 1))
allyColor = "w" if self.whiteToMove else "b"
for i in range(8):
endRow = r + kingMoves[i][0]
endCol = c + kingMoves[i][1]
if 0 <= endRow < 8 and 0 <= endCol < 8:
endPiece = self.board[endRow][endCol]
if endPiece[0] != allyColor:
moves.append(Move((r, c), (endRow, endCol), self.board))
# Castling handling
def getCastleMoves(self, r, c, moves):
if self.squareUnderAttack(r, c):
return
if (self.whiteToMove and self.currentCastlingRight.wks) or (not self.whiteToMove and self.currentCastlingRight.bks):
self.getKingSideCastleMoves(r, c, moves)
if (self.whiteToMove and self.currentCastlingRight.wqs) or (not self.whiteToMove and self.currentCastlingRight.bqs):
self.getQueenSideCastleMoves(r, c, moves)
def getKingSideCastleMoves(self, r, c, moves):
if self.board[r][c+1] == "--" and self.board[r][c+2] == "--":
if not self.squareUnderAttack(r, c+1) and not self.squareUnderAttack(r, c+2):
moves.append(Move((r, c), (r, c+2), self.board, isCastlingMove=True, KingSide=True))
def getQueenSideCastleMoves(self, r, c, moves):
if self.board[r][c-1] == "--" and self.board[r][c-2] == "--" and self.board[r][c-3] == "--":
if not self.squareUnderAttack(r, c-1) and not self.squareUnderAttack(r, c-2):
moves.append(Move((r, c), (r, c-2), self.board, isCastlingMove=True, KingSide=False))
class CastleRights():
def __init__(self, wks, bks, wqs, bqs):
self.wks = wks
self.bks = bks
self.wqs = wqs
self.bqs = bqs
class Move():
# Mapping keys to values
ranksToRows = {"1" : 7, "2" : 6, "3" : 5, "4" : 4, "5" : 3, "6" : 2, "7" : 1, "8" : 0}
rowsToRanks = {v: k for k, v in ranksToRows.items()}
filesToCols = {"h" : 7, "g" : 6, "f" : 5, "e" : 4, "d" : 3, "c" : 2, "b" : 1, "a" : 0}
colsToFiles = {v: k for k, v in filesToCols.items()}
def __init__(self, startSq, endSq, board, isEnpassantMove=False, isCastlingMove=False, KingSide=False):
self.startRow = startSq[0]
self.startCol = startSq[1]
self.endRow = endSq[0]
self.endCol = endSq[1]
self.pieceMoved = board[self.startRow][self.startCol]
self.pieceCaptured = board[self.endRow][self.endCol]
# Pawn promotion
self.isPawnPromotion = (self.pieceMoved == "wp" and self.endRow == 0) or (self.pieceMoved == "bp" and self.endRow == 7)
self.promotionChoice = "Q"
# En-passant
self.isEnpassantMove = isEnpassantMove
if self.isEnpassantMove:
self.pieceCaptured = "wp" if self.pieceMoved == "bp" else "bp"
self.isCastlingMove = isCastlingMove
self.KingSide = KingSide
self.moveID = self.startRow * 1000 + self.startCol * 100 + self.endRow * 10 + self.endCol
#Overriding equals method
def __eq__(self, other):
if isinstance(other, Move):
return self.moveID == other.moveID
return False
def getChessNotation(self):
#TODO Disambiguating Moves
#TODO Pawn Promotion
#TODO Check/Checkmate
notation = ""
if self.isCastlingMove:
if self.KingSide:
return "0-0"
else:
return "0-0-0"
if not self.pieceMoved[1] == "p":
notation += self.pieceMoved[1]
else:
if self.pieceCaptured == "--":
return self.getRankFile(self.endRow, self.endCol)
else:
notation = self.getRankFile(self.startRow, self.startCol)
return notation[0] + "x" + self.getRankFile(self.endRow, self.endCol)
if self.pieceCaptured == "--":
return notation + self.getRankFile(self.endRow, self.endCol)
else:
return notation + "x" + self.getRankFile(self.endRow, self.endCol)
def getRankFile(self, r, c):
return self.colsToFiles[c] + self.rowsToRanks[r]
|
class Gamestate:
def __init__(self):
self.board = [['bR', 'bN', 'bB', 'bQ', 'bK', 'bB', 'bN', 'bR'], ['bp', 'bp', 'bp', 'bp', 'bp', 'bp', 'bp', 'bp'], ['--', '--', '--', '--', '--', '--', '--', '--'], ['--', '--', '--', '--', '--', '--', '--', '--'], ['--', '--', '--', '--', '--', '--', '--', '--'], ['--', '--', '--', '--', '--', '--', '--', '--'], ['wp', 'wp', 'wp', 'wp', 'wp', 'wp', 'wp', 'wp'], ['wR', 'wN', 'wB', 'wQ', 'wK', 'wB', 'wN', 'wR']]
self.moveFunctions = {'p': self.getPawnMoves, 'R': self.getRookMoves, 'N': self.getKnightMoves, 'Q': self.getQueenMoves, 'K': self.getKingMoves, 'B': self.getBishopMoves}
self.whiteToMove = True
self.moveLog = []
self.whiteKingLocation = (7, 4)
self.blackKingLocation = (0, 4)
self.checkMate = False
self.stalemate = False
self.enpassantPossible = ()
self.currentCastlingRight = castle_rights(True, True, True, True)
self.castleRightsLog = [castle_rights(self.currentCastlingRight.wks, self.currentCastlingRight.bks, self.currentCastlingRight.wqs, self.currentCastlingRight.bqs)]
def make_move(self, move):
self.board[move.startRow][move.startCol] = '--'
self.board[move.endRow][move.endCol] = move.pieceMoved
self.moveLog.append(move)
self.whiteToMove = not self.whiteToMove
if move.pieceMoved == 'wK':
self.whiteKingLocation = (move.endRow, move.endCol)
if move.pieceMoved == 'bK':
self.blackKingLocation = (move.endRow, move.endCol)
if move.isPawnPromotion:
self.board[move.endRow][move.endCol] = move.pieceMoved[0] + move.promotionChoice
if move.isEnpassantMove:
self.board[move.startRow][move.endCol] = '--'
if move.pieceMoved[1] == 'p' and abs(move.startRow - move.endRow) == 2:
self.enpassantPossible = ((move.startRow + move.endRow) // 2, move.startCol)
else:
self.enpassantPossible = ()
if move.isCastlingMove:
if move.endCol - move.startCol == 2:
self.board[move.endRow][move.endCol - 1] = self.board[move.endRow][move.endCol + 1]
self.board[move.endRow][move.endCol + 1] = '--'
else:
self.board[move.endRow][move.endCol + 1] = self.board[move.endRow][move.endCol - 2]
self.board[move.endRow][move.endCol - 2] = '--'
self.updateCastleRights(move)
self.castleRightsLog.append(castle_rights(self.currentCastlingRight.wks, self.currentCastlingRight.bks, self.currentCastlingRight.wqs, self.currentCastlingRight.bqs))
def undo_move(self):
if len(self.moveLog) != 0:
move = self.moveLog.pop()
self.board[move.startRow][move.startCol] = move.pieceMoved
self.board[move.endRow][move.endCol] = move.pieceCaptured
self.whiteToMove = not self.whiteToMove
if move.pieceMoved == 'wK':
self.whiteKingLocation = (move.startRow, move.startCol)
elif move.pieceMoved == 'bK':
self.blackKingLocation = (move.startRow, move.startCol)
if move.isEnpassantMove:
self.board[move.endRow][move.endCol] = '--'
self.board[move.startRow][move.endCol] = move.pieceCaptured
self.enpassantPossible = (move.endRow, move.endCol)
if move.pieceMoved[1] == 'p' and abs(move.startRow - move.endRow) == 2:
self.enpassantPossible = ()
self.castleRightsLog.pop()
self.currentCastlingRight = self.castleRightsLog[-1]
if move.isCastlingMove:
if move.endCol - move.startCol == 2:
self.board[move.endRow][move.endCol + 1] = self.board[move.endRow][move.endCol - 1]
self.board[move.endRow][move.endCol - 1] = '--'
else:
self.board[move.endRow][move.endCol - 2] = self.board[move.endRow][move.endCol + 1]
self.board[move.endRow][move.endCol + 1] = '--'
def update_castle_rights(self, move):
if move.pieceMoved == 'wK':
self.currentCastlingRight.wks = False
self.currentCastlingRight.wqs = False
elif move.pieceMoved == 'bK':
self.currentCastlingRight.bks = False
self.currentCastlingRight.bqs = False
elif move.pieceMoved == 'wR':
if move.startRow == 7:
if move.startCol == 0:
self.currentCastlingRight.wqs = False
elif move.startCol == 7:
self.currentCastlingRight.wks = False
elif move.pieceMoved == 'bR':
if move.startRow == 0:
if move.startCol == 0:
self.currentCastlingRight.bqs = False
elif move.startCol == 7:
self.currentCastlingRight.bks = False
def get_valid_moves(self):
temp_enpassant_possible = self.enpassantPossible
temp_castle_rights = castle_rights(self.currentCastlingRight.wks, self.currentCastlingRight.bks, self.currentCastlingRight.wqs, self.currentCastlingRight.bqs)
moves = self.getLegalMoves()
if self.whiteToMove:
self.getCastleMoves(self.whiteKingLocation[0], self.whiteKingLocation[1], moves)
else:
self.getCastleMoves(self.blackKingLocation[0], self.blackKingLocation[1], moves)
for i in range(len(moves) - 1, -1, -1):
self.makeMove(moves[i])
self.whiteToMove = not self.whiteToMove
if self.inCheck():
moves.remove(moves[i])
self.whiteToMove = not self.whiteToMove
self.undoMove()
if len(moves) == 0:
if self.inCheck():
self.checkMate = True
else:
self.stalemate = True
self.enpassantPossible = tempEnpassantPossible
self.currentCastlingRight = tempCastleRights
return moves
def in_check(self):
if self.whiteToMove:
return self.squareUnderAttack(self.whiteKingLocation[0], self.whiteKingLocation[1])
else:
return self.squareUnderAttack(self.blackKingLocation[0], self.blackKingLocation[1])
def square_under_attack(self, r, c):
self.whiteToMove = not self.whiteToMove
opp_moves = self.getLegalMoves()
self.whiteToMove = not self.whiteToMove
for move in oppMoves:
if move.endRow == r and move.endCol == c:
return True
return False
def get_legal_moves(self):
moves = []
for r in range(len(self.board)):
for c in range(len(self.board[r])):
turn = self.board[r][c][0]
if turn == 'w' and self.whiteToMove or (turn == 'b' and (not self.whiteToMove)):
piece = self.board[r][c][1]
self.moveFunctions[piece](r, c, moves)
return moves
def get_pawn_moves(self, r, c, moves):
if self.whiteToMove:
if self.board[r - 1][c] == '--':
moves.append(move((r, c), (r - 1, c), self.board))
if r == 6 and self.board[r - 2][c] == '--':
moves.append(move((r, c), (r - 2, c), self.board))
if c - 1 >= 0:
if self.board[r - 1][c - 1][0] == 'b':
moves.append(move((r, c), (r - 1, c - 1), self.board))
elif (r - 1, c - 1) == self.enpassantPossible:
moves.append(move((r, c), (r - 1, c - 1), self.board, isEnpassantMove=True))
if c + 1 <= 7:
if self.board[r - 1][c + 1][0] == 'b':
moves.append(move((r, c), (r - 1, c + 1), self.board))
elif (r - 1, c + 1) == self.enpassantPossible:
moves.append(move((r, c), (r - 1, c + 1), self.board, isEnpassantMove=True))
else:
if self.board[r + 1][c] == '--':
moves.append(move((r, c), (r + 1, c), self.board))
if r == 1 and self.board[r + 2][c] == '--':
moves.append(move((r, c), (r + 2, c), self.board))
if c - 1 >= 0:
if self.board[r + 1][c - 1][0] == 'w':
moves.append(move((r, c), (r + 1, c - 1), self.board))
elif (r + 1, c - 1) == self.enpassantPossible:
moves.append(move((r, c), (r + 1, c - 1), self.board, isEnpassantMove=True))
if c + 1 <= 7:
if self.board[r + 1][c + 1][0] == 'w':
moves.append(move((r, c), (r + 1, c + 1), self.board))
elif (r + 1, c + 1) == self.enpassantPossible:
moves.append(move((r, c), (r + 1, c + 1), self.board, isEnpassantMove=True))
def get_rook_moves(self, r, c, moves):
directions = ((-1, 0), (0, -1), (1, 0), (0, 1))
enemy_color = 'b' if self.whiteToMove else 'w'
for d in directions:
for i in range(1, 8):
end_row = r + d[0] * i
end_col = c + d[1] * i
if 0 <= endRow < 8 and 0 <= endCol < 8:
end_piece = self.board[endRow][endCol]
if endPiece == '--':
moves.append(move((r, c), (endRow, endCol), self.board))
elif endPiece[0] == enemyColor:
moves.append(move((r, c), (endRow, endCol), self.board))
break
else:
break
else:
break
def get_bishop_moves(self, r, c, moves):
directions = ((-1, -1), (1, -1), (1, 1), (-1, 1))
enemy_color = 'b' if self.whiteToMove else 'w'
for d in directions:
for i in range(1, 8):
end_row = r + d[0] * i
end_col = c + d[1] * i
if 0 <= endRow < 8 and 0 <= endCol < 8:
end_piece = self.board[endRow][endCol]
if endPiece == '--':
moves.append(move((r, c), (endRow, endCol), self.board))
elif endPiece[0] == enemyColor:
moves.append(move((r, c), (endRow, endCol), self.board))
break
else:
break
else:
break
def get_knight_moves(self, r, c, moves):
knight_moves = ((-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1))
ally_color = 'w' if self.whiteToMove else 'b'
for m in knightMoves:
end_row = r + m[0]
end_col = c + m[1]
if 0 <= endRow < 8 and 0 <= endCol < 8:
end_piece = self.board[endRow][endCol]
if endPiece[0] != allyColor:
moves.append(move((r, c), (endRow, endCol), self.board))
def get_queen_moves(self, r, c, moves):
self.getBishopMoves(r, c, moves)
self.getRookMoves(r, c, moves)
def get_king_moves(self, r, c, moves):
king_moves = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (1, -1), (1, 1), (1, 0), (0, 1))
ally_color = 'w' if self.whiteToMove else 'b'
for i in range(8):
end_row = r + kingMoves[i][0]
end_col = c + kingMoves[i][1]
if 0 <= endRow < 8 and 0 <= endCol < 8:
end_piece = self.board[endRow][endCol]
if endPiece[0] != allyColor:
moves.append(move((r, c), (endRow, endCol), self.board))
def get_castle_moves(self, r, c, moves):
if self.squareUnderAttack(r, c):
return
if self.whiteToMove and self.currentCastlingRight.wks or (not self.whiteToMove and self.currentCastlingRight.bks):
self.getKingSideCastleMoves(r, c, moves)
if self.whiteToMove and self.currentCastlingRight.wqs or (not self.whiteToMove and self.currentCastlingRight.bqs):
self.getQueenSideCastleMoves(r, c, moves)
def get_king_side_castle_moves(self, r, c, moves):
if self.board[r][c + 1] == '--' and self.board[r][c + 2] == '--':
if not self.squareUnderAttack(r, c + 1) and (not self.squareUnderAttack(r, c + 2)):
moves.append(move((r, c), (r, c + 2), self.board, isCastlingMove=True, KingSide=True))
def get_queen_side_castle_moves(self, r, c, moves):
if self.board[r][c - 1] == '--' and self.board[r][c - 2] == '--' and (self.board[r][c - 3] == '--'):
if not self.squareUnderAttack(r, c - 1) and (not self.squareUnderAttack(r, c - 2)):
moves.append(move((r, c), (r, c - 2), self.board, isCastlingMove=True, KingSide=False))
class Castlerights:
def __init__(self, wks, bks, wqs, bqs):
self.wks = wks
self.bks = bks
self.wqs = wqs
self.bqs = bqs
class Move:
ranks_to_rows = {'1': 7, '2': 6, '3': 5, '4': 4, '5': 3, '6': 2, '7': 1, '8': 0}
rows_to_ranks = {v: k for (k, v) in ranksToRows.items()}
files_to_cols = {'h': 7, 'g': 6, 'f': 5, 'e': 4, 'd': 3, 'c': 2, 'b': 1, 'a': 0}
cols_to_files = {v: k for (k, v) in filesToCols.items()}
def __init__(self, startSq, endSq, board, isEnpassantMove=False, isCastlingMove=False, KingSide=False):
self.startRow = startSq[0]
self.startCol = startSq[1]
self.endRow = endSq[0]
self.endCol = endSq[1]
self.pieceMoved = board[self.startRow][self.startCol]
self.pieceCaptured = board[self.endRow][self.endCol]
self.isPawnPromotion = self.pieceMoved == 'wp' and self.endRow == 0 or (self.pieceMoved == 'bp' and self.endRow == 7)
self.promotionChoice = 'Q'
self.isEnpassantMove = isEnpassantMove
if self.isEnpassantMove:
self.pieceCaptured = 'wp' if self.pieceMoved == 'bp' else 'bp'
self.isCastlingMove = isCastlingMove
self.KingSide = KingSide
self.moveID = self.startRow * 1000 + self.startCol * 100 + self.endRow * 10 + self.endCol
def __eq__(self, other):
if isinstance(other, Move):
return self.moveID == other.moveID
return False
def get_chess_notation(self):
notation = ''
if self.isCastlingMove:
if self.KingSide:
return '0-0'
else:
return '0-0-0'
if not self.pieceMoved[1] == 'p':
notation += self.pieceMoved[1]
elif self.pieceCaptured == '--':
return self.getRankFile(self.endRow, self.endCol)
else:
notation = self.getRankFile(self.startRow, self.startCol)
return notation[0] + 'x' + self.getRankFile(self.endRow, self.endCol)
if self.pieceCaptured == '--':
return notation + self.getRankFile(self.endRow, self.endCol)
else:
return notation + 'x' + self.getRankFile(self.endRow, self.endCol)
def get_rank_file(self, r, c):
return self.colsToFiles[c] + self.rowsToRanks[r]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.