content
stringlengths
7
1.05M
reporting_jurisdiction = [ 'AL', 'AK', 'AR', 'AZ', 'CA', 'CI', 'CO', 'MP', 'CT', 'DE', 'DC', 'FM', 'FL', 'GA', 'GU', 'HI', 'HO', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LC', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NZ', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'PH', 'PR', 'MH', 'PW', 'RI', 'SC', 'SD', 'TN', 'TX', 'VI', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY', ] sample_location = ['wwtp', 'upstream'] institution_type = [ 'not institution specific', 'correctional', 'long term care - nursing home', 'long term care - assisted living', 'other long term care', 'short stay acute care hospital', 'long term acute care hospital', 'child day care', 'k12', 'higher ed dorm', 'higher ed other', 'social services shelter', 'other residential building', 'ship', 'airplane', ] wwtp_jurisdictions = [ 'AL', 'AK', 'AS', 'AZ', 'CA', 'CO', 'MP', 'CT', 'DE', 'DC', 'FM', 'FL', 'GA', 'GU', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'PR', 'MH', 'PW', 'RI', 'SC', 'SD', 'TN', 'TX', 'VI', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY', ] yes_no_empty = [ 'yes', 'no' ] sample_type = [ 'grab', '30-hr flow-weighted composite', '29-hr flow-weighted composite', '28-hr flow-weighted composite', '27-hr flow-weighted composite', '26-hr flow-weighted composite', '25-hr flow-weighted composite', '24-hr flow-weighted composite', '23-hr flow-weighted composite', '22-hr flow-weighted composite', '21-hr flow-weighted composite', '20-hr flow-weighted composite', '19-hr flow-weighted composite', '18-hr flow-weighted composite', '17-hr flow-weighted composite', '16-hr flow-weighted composite', '15-hr flow-weighted composite', '14-hr flow-weighted composite', '13-hr flow-weighted composite', '12-hr flow-weighted composite', '11-hr flow-weighted composite', '10-hr flow-weighted composite', '9-hr flow-weighted composite', '8-hr flow-weighted composite', '7-hr flow-weighted composite', '6-hr flow-weighted composite', '5-hr flow-weighted composite', '4-hr flow-weighted composite', '3-hr flow-weighted composite', '2-hr flow-weighted composite', '1-hr flow-weighted composite', '30-hr time-weighted composite', '29-hr time-weighted composite', '28-hr time-weighted composite', '27-hr time-weighted composite', '26-hr time-weighted composite', '25-hr time-weighted composite', '24-hr time-weighted composite', '23-hr time-weighted composite', '22-hr time-weighted composite', '21-hr time-weighted composite', '20-hr time-weighted composite', '19-hr time-weighted composite', '18-hr time-weighted composite', '17-hr time-weighted composite', '16-hr time-weighted composite', '15-hr time-weighted composite', '14-hr time-weighted composite', '13-hr time-weighted composite', '12-hr time-weighted composite', '11-hr time-weighted composite', '10-hr time-weighted composite', '9-hr time-weighted composite', '8-hr time-weighted composite', '7-hr time-weighted composite', '6-hr time-weighted composite', '5-hr time-weighted composite', '4-hr time-weighted composite', '3-hr time-weighted composite', '2-hr time-weighted composite', '1-hr time-weighted composite', '30-hr manual composite', '29-hr manual composite', '28-hr manual composite', '27-hr manual composite', '26-hr manual composite', '25-hr manual composite', '24-hr manual composite', '23-hr manual composite', '22-hr manual composite', '21-hr manual composite', '20-hr manual composite', '19-hr manual composite', '18-hr manual composite', '17-hr manual composite', '16-hr manual composite', '15-hr manual composite', '14-hr manual composite', '13-hr manual composite', '12-hr manual composite', '11-hr manual composite', '10-hr manual composite', '9-hr manual composite', '8-hr manual composite', '7-hr manual composite', '6-hr manual composite', '5-hr manual composite', '4-hr manual composite', '3-hr manual composite', '2-hr manual composite', '1-hr manual composite' ] sample_matrix = [ 'raw wastewater', 'post grit removal', 'primary sludge', 'primary effluent', 'secondary sludge', 'secondary effluent', 'septage', 'holding tank' ] solids_separation = [ 'filtration', 'centrifugation', 'none' ] concentration_method = [ 'membrane filtration with addition of mgcl2', 'membrane filtration with sample acidification', 'membrane filtration with acidification and mgcl2', 'membrane filtration with no amendment', 'membrane filtration with addition of mgcl2, membrane recombined with ' 'separated solids', 'membrane filtration with sample acidification, membrane recombined with ' 'separated solids', 'membrane filtration with acidification and mgcl2, ' 'membrane recombined with separated solids', 'membrane filtration with no amendment,' 'membrane recombined with separated solids', 'peg precipitation', 'ultracentrifugation', 'skimmed milk flocculation', 'beef extract flocculation', 'promega wastewater large volume tna capture kit', 'centricon ultrafiltration', 'amicon ultrafiltration', 'hollow fiber dead end ultrafiltration', 'no liquid concentration, liquid recombined with separated solids', 'innovaprep ultrafiltration', 'none' ] extraction_method = [ 'qiagen allprep powerviral dna/rna kit', 'qiagen allprep powerfecal dna/rna kit', 'qiagen allprep dna/rna kit', 'qiagen rneasy powermicrobiome kit', 'qiagen powerwater kit', 'qiagen rneasy kit', 'promega ht tna kit', 'promega automated tna kit', 'promega manual tna kit', 'promega wastewater large volume tna capture kit', 'nuclisens automated magnetic bead extraction kit', 'nuclisens manual magnetic bead extraction kit', 'phenol chloroform', 'chemagic viral dna/rna 300 kit', 'trizol, zymo mag beads w/ zymo clean and concentrator', '4s method (https://www.protocols.io/view/v-4-direct-wastewater-rna-capture-and-purification-bpdfmi3n)', # noqa 'qiagen qiaamp buffers with epoch columns', 'zymo quick-rna fungal/bacterial miniprep #r2014' ] rec_eff_target_name = [ 'bcov vaccine', 'brsv vaccine', 'murine coronavirus', 'oc43', 'phi6', 'puro', 'ms2 coliphage', 'hep g armored rna' ] rec_eff_spike_matrix = [ 'raw sample', 'raw sample post pasteurization', 'clarified sample', 'sample concentrate', 'lysis buffer', 'dewatered solids', ] pcr_target = [ 'n1', 'n2', 'n3', 'e_sarbeco', 'n_sarbeco', 'rdrp_sarsr', 'niid_2019-ncov_n', 'rdrp gene / ncov_ip2', 'rdrp gene / ncov_ip4', 'taqpath n', 'taqpath s', 'orf1b', 'orf1ab', 'n1 and n2 combined', 'n', 's', 'orf1a', 'ddcov_n', 'ddcov_e', 'ip2 and ip4 combined' ] pcr_type = [ 'qpcr', 'ddpcr', 'qiagen dpcr', 'fluidigm dpcr', 'life technologies dpcr', 'raindance dpcr' ] mic_units = [ 'copies/L wastewater', 'log10 copies/L wastewater', 'copies/g wet sludge', 'log10 copies/g wet sludge', 'copies/g dry sludge', 'log10 copies/g dry sludge' ] hum_frac_target_mic = [ 'pepper mild mottle virus', 'crassphage', 'hf183', 'f+ rna coliphage', 'f+ dna coliphage', ] chem_units = [ 'micrograms/L wastewater', 'log10 micrograms/L wastewater', 'micrograms/g wet sludge', 'log10 micrograms/g wet sludge', 'micrograms/g dry sludge', 'log10 micrograms/g dry sludge' ] hum_frac_target_chem = [ 'caffeine', 'creatinine', 'sucralose', 'ibuprofen' ] mic_chem_units = [ 'copies/L wastewater', 'log10 copies/L wastewater', 'copies/g wet sludge', 'log10 copies/g wet sludge', 'copies/g dry sludge', 'log10 copies/g dry sludge', 'micrograms/L wastewater', 'log10 micrograms/L wastewater', 'micrograms/g wet sludge', 'log10 micrograms/g wet sludge', 'micrograms/g dry sludge', 'log10 micrograms/g dry sludge' ] other_norm_name = [ 'pepper mild mottle virus', 'crassphage', 'hf183', 'caffeine', 'creatinine', 'sucralose', 'ibuprofen', 'f+ rna coliphage', 'f+ dna coliphage', ] quant_stan_type = [ 'dna', 'rna' ] yes_no_not_tested = [ 'yes', 'no', 'not tested' ] num_no_target_control = [ '0', '1', '2', '3', 'more than 3' ] yes_no = [ 'yes', 'no' ]
#!/usr/bin/env python # http://flask.pocoo.org/docs/config/#development-production class Config(object): SECRET_KEY = 'bzNsEap7HGJeOGzAxhNlQCtaRpccRZHgWaOncxAKpCJovJgJbN' SITE_NAME = 'profiler' MEMCACHED_SERVERS = ['localhost:11211'] SYS_ADMINS = ['[email protected]'] class ProductionConfig(Config): DEBUG = False class DevelopmentConfig(Config): '''Use "if app.debug" anywhere in your code, that code will run in development code. ''' DEBUG = True
local = list(input('Introduza os nomes das equipas da casa separados entre espaços: ').split()) golos = list(map(int, input('Introduza os golos marcados em cada jornada separados entre espaços: ').split())) loop = True while loop: for i in golos: if i < 0: print('Os golos marcados devem ser números positivos maiores ou iguais a 0.') golos.clear() golos = list(map(int, input('Introduza os golos marcados em cada jornada separados entre espaços: ').split())) loop = True break else: loop = False percentagem = (local.count('Viseu')*100)/len(local) print('O record de golos num jogo foi de {0} golos, obtido na {1}ª jornada. {2}% dos jogos da temporada foram em casa. A equipa marcou {3} golos na totalidade.'.format(max(golos), golos.index(max(golos))+1, round(percentagem), sum(golos)))
# coding: utf-8 # Try POH # author: Leonarodne @ NEETSDKASU ############################################## def gs(*_): return input().strip() def gi(*_): return int(gs()) def gss(*_): return gs().split() def gis(*_): return list(map(int, gss())) def nmapf(n,f): return list(map(f, range(n))) def ngs(n): return nmapf(n,gs) def ngi(n): return nmapf(n,gi) def ngss(n): return nmapf(n,gss) def ngis(n): return nmapf(n,gis) ############################################## def solve(): minx, miny, *_ = x, y, z, n = gis() da = ngis(n) for i in range(n): d, a = da[i] t = min([a] + list(map(lambda v: abs(v[1]-a), filter(lambda v: v[0]==d, da[i+1:])))) if d == 0: minx = min(minx, t, x - a) else: miny = min(miny, t, y - a) print(minx * miny * z) solve()
class Point(): # each method has at least self argument def getX(self): return self.x # Create instances of class Point point1 = Point() point2 = Point() print(point1) print(point2) print(point1 is point2) point1.x = 5 point2.x = 10 print(point1.getX()) print(point2.getX())
""" Ryan Kirkbride - Love coding weird noises to dance to: https://www.youtube.com/watch?v=Qc_8Pm2t-84 How to: - Run the statements line by line (alt+enter), go to the next one whenever you feel like - The "#### > run block <" blocks should be executed atomically (ctrl+enter) - If you want to fast-forward through the song, just execute the blocks atomically (ctrl+enter) from the beginning, so you don't have to go through every variation of each instrument - Enjoy ! :+1: """ p1 >> pads(dur=8,) + (P*(0,4)) p1 >> pads(dur=8,) + (P*(0,4,4.5)) p1 >> pads(dur=8,) + (P*(0,4,4.5,3.5)) p1 >> pads(dur=8,) + (P*(0,4,4.5,2.5)) p1 >> pads(dur=8,) + (P*(0,4,4.5,0.5)) p1 >> pads(dur=8,room=1,) + (P*(0,4,4.5,0.5)) p1 >> pads(dur=8,room=1,chop=320) + (P*(0,4,4.5,0.5)) p1 >> pads(dur=8,room=1,chop=320,coarse=16) + (P*(0,4,4.5,0.5)) d1 >> play("x ",) d2 >> play("[ii]", amp=linvar([0,1,0],[2,0]),) d2 >> play("[ii]", amp=linvar([0,1,0],[2,0,2]),) d2 >> play("[oo]", amp=linvar([0,1,0],[2,0,2]),) d2 >> play("[oo]", amp=linvar([0,1,0],[2,0,2]),bits=4,) d2 >> play("[oo]", amp=linvar([0,1,0],[2,0,2]),bits=4,rate=4,) d2 >> play("[oo]", amp=linvar([0,1,0],[2,0,2]),bits=4,rate=1,) d2 >> play("[oo]", amp=linvar([0,1,0],[2,0,2]),bits=4,rate=1,crush=4,) d2 >> play("[oo]", amp=linvar([0,1,0],[2,0,2]),bits=4,rate=2,crush=4,) d2 >> play("[oo]", amp=linvar([0,1,0],[2,0,2]),bits=4,rate=2,crush=4,room=0.5,) d2 >> play("[oo]", amp=linvar([0,1,0],[2,0,2]),bits=4,rate=2,crush=4,room=0.5,pan=[-1,1],) d1 >> play("x-",) d1 >> play("xn",) d1 >> play("xn",sample=[0,PRand(5)],) d1 >> play("xn",sample=[0,PRand(7)],) d1 >> play("xn",sample=[0,PRand(7)],).every(6,"stutter",4,dur=3) b1 >> bass(dur=8,) b1 >> bass([0,0.5],dur=4,) b1 >> bass([0,0.5],dur=4,oct=4,) b1 >> bass([0,0.5],dur=4,oct=3,) b1 >> bass([0,0.5],dur=4,oct=3,shape=1,) b1 >> bass([0,0.5],dur=4,oct=3,shape=2,) b1 >> bass([0,0.5],dur=4,oct=3,shape=2,slide=-1,) b1 >> bass([0,0.5],dur=4,oct=3,shape=2,slide=PRand([-1,0,-2,-3]),) b1 >> bass([0,0.5],dur=4,oct=3,shape=2,slide=PRand([-1,0,-2,-3]),coarse=16,) b1 >> bass([0,0.5],dur=4,oct=3,shape=2,slide=PRand([-1,0,-2,-3]),coarse=PRand([4,8,16]),) d3 >> play(" u ") b1 >> bass([0,0.5],dur=4,oct=3,shape=2,slide=PRand([-1,0,-2,-3,-4,2]),coarse=PRand([4,8,16]),) b1 >> bass([0,0.5],dur=4,oct=3,shape=2,slide=PRand([-1,0,-2,-3,-4,2]),coarse=PRand([4,8,16,32]),) b1 >> bass([0,0.5],dur=4,oct=3,shape=2,slide=PRand([-1,0,-2,-3,-4,2]),coarse=PRand([4,8,16,32,0]),) b1 >> bass([0,0.5],dur=4,oct=3,shape=2,slide=PRand([-1,0,-2,-3,-4,2]),coarse=PRand([4,8,16,32,0,64]),) d3 >> play(Pvar([" u "," u u"],8),dur=PDur(var([4,5],8),8),) d3 >> play(Pvar([" u "," u u"],8),dur=PDur(var([4,5],16),8),) d1 >> play("xn",sample=[0,PRand(7)],).every(6,"stutter",4,dur=3).every(8,"amen") Master().lpf = var([0,200],[28,4]) p1 >> pads(dur=8,room=1,chop=320,coarse=16) + (P*(0,4,4.5,[0.5,5])) Root.default = var([0,2],64) Master().lpf = var([0,100],[28,4]) Master().lpf = var([0,1000],[28,4]) Master().lpr = linvar([0.1,1]) b1 >> bass([0,0.5],dur=4,oct=3,shape=2,slide=PRand([-1,0,-2,-3,-4,2]),coarse=PRand([4,8,16,32,0,64,13]),) b1 >> bass([0,0.5],dur=4,oct=3,shape=2,slide=PRand([-1,0,-2,-3,-4,2]),coarse=PRand([4,8,16,32,0,64])*PRand([1,1.5]),) c1 >> play("#",dur=8,) c1 >> play("#",dur=8,bits=4,) c1 >> play("#",dur=8,bits=4,cut=1/2,) c1 >> play("#",dur=8,bits=4,cut=1/2,room=1,) c1 >> play("#",dur=8,bits=4,cut=1/4,room=1,) c1 >> play("#",dur=8,bits=4,cut=1/4,room=1,crush=1,) c1 >> play("#",dur=8,bits=4,cut=1/4,room=1,crush=1,shape=0.5,) c1 >> play("#",dur=8,bits=4,cut=1/4,room=1,crush=1,shape=0.5,pan=[-1,1],) c1 >> play("#",dur=8,bits=4,cut=1/4,room=1,crush=1,shape=0.5,pan=[-1,1],slide=-1,) c1 >> play("#",dur=P[8:12],bits=4,cut=1/4,room=1,crush=1,shape=0.5,pan=[-1,1],slide=-1,) c1.solo() c1 >> play("#",dur=P[8:12],bits=4,cut=1/4,room=1,crush=8,shape=0.5,pan=[-1,1],slide=-1,chop=320,) d2 >> play("[oo]", amp=linvar([0,1,0],[2,0,2]),bits=4,rate=2,crush=4,room=0.5,pan=[-1,1],) d1 >> play("xn",sample=[0,PRand(7)],).every(6,"stutter",4,dur=3).every(8,"amen") c1 >> play("#",dur=P[8:12],bits=4,cut=1/4,room=1,crush=8,shape=0.5,pan=[-1,1],slide=-1,chop=320,rate=2,) c1 >> play("#",dur=P[8:12],bits=4,cut=1/4,room=1,crush=8,shape=0.5,pan=[-1,1],slide=-1,chop=320,rate=PRand(8),) b1 >> bass([0,0.5],dur=4,oct=3,shape=2,slide=PRand([-1,0,-2,-3,-4,2]),coarse=PRand([4,8,16,32,0,64])*PRand([1,1.5]),) d3 >> play(Pvar([" u "," u u"],8),dur=PDur(var([4,5],16),8),) p1 >> pads(dur=8,room=1,chop=320,coarse=16) + (P*(0,4,4.5,[0.5,5])) c1 >> play("#",dur=P[8:12],bits=4,cut=1/4,room=1,crush=8,shape=0.5,pan=[-1,1],slide=-1,chop=320,rate=PRand(8)*10,) c1 >> play("#",dur=P[8:12],bits=4,cut=1/4,room=1,crush=8,shape=0.5,pan=[-1,1],slide=-1,chop=320,rate=PRand(8)+10,) s1 >> saw(PWhite(32),dur=1/4,) s1 >> saw(PWhite(32),dur=1/6,) s1 >> pulse(PWhite(32),dur=1/6,) s1 >> pulse(PWhite(32),dur=1/6,fmod=10,) s1 >> pulse(PWhite(32),dur=1/6,fmod=10,oct=4,) Group(s1, b1).only() s1 >> pulse(PWhite(32)[:8],dur=1/4,fmod=10,oct=4,) d4 >> play("funky",rate=10,) d4 >> play("funky",rate=10,dur=1/4,) d4 >> play("funky",rate=4,dur=1/4,) d4 >> play("funky",rate=4*PRand([1,1.5]),dur=1/4,) d4 >> play("funky",rate=4*PRand([1,1.5,1.25]),dur=1/4,) d4 >> play("funky",rate=4*PRand([1,1.5,1.25]),dur=1/4,pan=PStep(6,P*(-1,1)),) #### > run block < d1 >> play("xn",sample=[0,PRand(7)],).every(6,"stutter",4,dur=3).every(8,"amen") d2 >> play("[oo]", amp=linvar([0,1,0],[2,0,2]),bits=4,rate=2,crush=4,room=0.5,pan=[-1,1],) d3 >> play(Pvar([" u "," u u"],8),dur=PDur(var([4,5],16),8),) b1.stop() #### > run block < s1 >> pulse(PWhite(32)[:8],dur=1/4,fmod=10,oct=3,) s1 >> pulse(PWhite(32)[:8],dur=1/4,fmod=10,oct=3,) + var([0,(0,4)],[12,4]) s1 >> pulse(PWhite(32)[:8],dur=1/4,fmod=10,oct=4,) + var([0,(0,4)],[12,4]) Root.default = 0 c1 >> play("#",dur=P[8:12],bits=4,cut=1/4,room=1,crush=8,shape=0.5,pan=[-1,1],slide=-1,chop=320,rate=PRand(8)+10,) d4 >> play("<funky>< m>",rate=4*PRand([1,1.5,1.25]),dur=1/4,pan=PStep(6,P*(-1,1)),) d4 >> play("<funky>< w>",rate=4*PRand([1,1.5,1.25]),dur=1/4,pan=PStep(6,P*(-1,1)),) d4 >> play("<funky>< (mw)l>",rate=4*PRand([1,1.5,1.25]),dur=1/4,pan=PStep(6,P*(-1,1)),) d4 >> play("<funky>< (ew)l>",rate=4*PRand([1,1.5,1.25]),dur=1/4,pan=PStep(6,P*(-1,1)),) d4 >> play("<funky>< (+t)l>",rate=4*PRand([1,1.5,1.25]),dur=1/4,pan=PStep(6,P*(-1,1)),) d4 >> play("<funky>< (+q)l>",rate=4*PRand([1,1.5,1.25]),dur=1/4,pan=PStep(6,P*(-1,1)),) p1 >> pads(dur=8,room=1,chop=320,coarse=16) + (P*(0,4,4.5,[0.5,5])) s1.every(8,"degrade") s1.stop() d3 >> play("*",sample=2,dur=1/4,amp=PRand(2)[:16],) d3 >> play("*",sample=2,dur=1/4,amp=PRand(2)[:16],pan=[-1,1],) d3 >> play("*",sample=2,dur=1/4,amp=PRand(2)[:16],pan=[-1,0,1],) d3 >> play("*",sample=2,dur=1/4,amp=PRand(2)[:16],pan=[-1,0,1],rate=var([1,2])) d1 >> play("Vn",sample=[0,PRand(7)],).every(6,"stutter",4,dur=3).every(8,"amen") d1 >> play("<Vn>< u >",sample=[0,PRand(7)],).every(6,"stutter",4,dur=3).every(8,"amen") p1 >> pads(dur=8,room=1,chop=320,coarse=16,lpf=linvar([500,1000],24),) + (P*(0,4,4.5,[0.5,5])) p1 >> pads(dur=8,room=1,chop=320,coarse=16,lpf=linvar([500,1000],24),lpr=linvar([0.1,1],14),) + (P*(0,4,4.5,[0.5,5])) p1 >> pads(dur=8,room=1,chop=320,coarse=16,lpf=linvar([500,800],24),lpr=linvar([0.1,1],14),) + (P*(0,4,4.5,[0.5,5])) p1 >> pads(dur=8,room=1,chop=320,coarse=16,lpf=linvar([400,800],24),lpr=linvar([0.1,1],14),) + (P*(0,4,4.5,[0.5,5])) p1 >> pluck(dur=8,room=1,chop=320,coarse=16,lpf=linvar([400,800],24),lpr=linvar([0.1,1],14),) + (P*(0,4,4.5,[0.5,5])) d_all.amplify = var([1,0],[28,4]) p2 >> blip(dur=12,) p2 >> blip(dur=12,fmod=10,) p2 >> blip(dur=12,fmod=4,) p2 >> blip(dur=12,fmod=4,vib=12,) p2 >> blip(dur=12,fmod=4,vib=12,slide=-1,oct=7,) p2 >> blip(dur=12,fmod=4,vib=12,slide=-1,oct=7,pan=P*(-1,0,1),) p2 >> blip(dur=12,fmod=4,vib=12,slide=-1,oct=7,pan=P+(-1,0,1),sus=4,) p2 >> blip(dur=12,fmod=4,vib=12,slide=-1,oct=7,pan=P+(-1,0,1),sus=4,bits=8,crush=8,) p2 >> blip(dur=12,fmod=4,vib=12,slide=-1,oct=7,pan=P+(-1,0,1),sus=4,bits=8,crush=8,) + (0,9) p2 >> blip(dur=12,fmod=4,vib=12,slide=-1,oct=7,pan=P+(-1,0,1),sus=4,bits=8,crush=8,) + (0,2) d_all.stop() # p2 >> blip(dur=12,fmod=4,vib=12,slide=(-1,-2,-3),oct=7,pan=P+(-1,0,1),sus=4,bits=8,crush=8,) + (0,2) # p2 >> blip(dur=12,fmod=4,vib=12,slide=-1,oct=7,pan=P+(-1,0,1),sus=4,bits=8,crush=8,) + (0,2) # DefaultServer.freeAllNodes() d1 >> play("n",dur=1/4,sample=PRand(7),) d1 >> play("n",dur=1/4,sample=PRand(7),pan=PWhite(-1,1),) d1 >> play("n",dur=1/4,sample=PRand(7)+PStep(7,P*(0,1)),pan=PWhite(-1,1),) d2 >> play("(X )( X)O ",) d2 >> play("(X )( X)O ",rate=(0.9,1),pan=(-1,1),) d2 >> play("(X )( X)O ",rate=(0.9,1),pan=(-1,1),).every(6,"stutter") d2 >> play("(X )( X)O ",rate=(0.9,1),pan=(-1,1),).every(6,"stutter",n=4,dur=3) d2 >> play("<s><(X )( X)O >",rate=(0.9,1),pan=(-1,1),).every(6,"stutter",n=4,dur=3) d2 >> play("< s><(X )( X)O >",rate=(0.9,1),pan=(-1,1),).every(6,"stutter",n=4,dur=3) d_all.lpf = 500 d_all.lpf = 0 d3 >> play("[oo]",amp=linvar([0,1],[32,0]),) d4 >> play("#",dur=32,) nextBar(Clock.clear())
# 문제 번호: 13866 문제 이름: 팀 나누기 # 문제 최초 시도: 2019_04_09 # 문제 풀이 완료: 2019_04_09 # 이 코드의 접근법: 구현 Min=987654321 A,B,C,D=map(int,input().split()) if(abs(A+B-C-D)<Min): Min=abs(A+B-C-D) if(abs(A+C-B-D)<Min): Min=abs(A+C-B-D) if(abs(A+D-B-C)<Min): Min=abs(A+D-B-C) print(Min)
# ham cho do dai day con dai nhat thoa man A[i] = A[i-1] + A[i-2] def maxSubLens(A, N): pass N = int(input()) A = [int(item) for item in input().split()] print(len(A))
def getTotalX(a, b): limMax = min(b) #maximum limit limMin = max(a) #minimum limit sizeA = len(a) sizeB = len(b) nums = [] result = 0 aux = limMin while (aux <= limMax): for j in range(0,sizeA): if (j == sizeA - 1) and (aux % a[j] == 0): nums.append(aux) break if aux % a[j] == 0: continue else: break aux += limMin for num in nums: for j in range(0,sizeB): if (j == sizeB -1) and (b[j] % num == 0): result += 1 break if b[j] % num == 0: continue else: break return result a = [3,9,6] b = [36,72] print(getTotalX(a,b))
""" Custom exceptions for dealing with responses from the TAP server """ __all__ = ["TAPQueryException", "TAPUploadException"] class TAPQueryException(Exception): def __init__(self, response, message=None): # Try parsing out an error message. if message is None: try: message = response.text\ .split('<INFO name="QUERY_STATUS" value="ERROR">')[1]\ .split('</INFO>')[0].strip() except: message = "{} code returned".format(response.status_code) super(TAPQueryException, self).__init__(message) self.errors = response return None class TAPUploadException(Exception): def __init__(self, response, message=None): # Try parsing out an error message. if message is None: try: message = response.text\ .split('<b>Message: </b>')[1]\ .split('</li>')[0].strip() except: message = "{} code returned".format(response.status_code) super(TAPUploadException, self).__init__(message) self.errors = response return None
opt = { "optimizer": { "type": "Adam", "kwargs": { "lr": 0.001, }, }, "learning_rate_decay": { "type": "", "kwargs": {}, }, "gradient_clip": { "type": "", "kwargs": {}, }, "gradient_noise_scale": None, "name": None, }
array = [7,5,9,0,3,1,6,2,4,8] def quick_sort(array): if len(array) <= 1: return array pivot = array[0] tail = array[1:] #pivot보다 작은 값은 left_side로, 큰 값은 right_side로 나눔 left_side = [x for x in tail if x <= pivot] right_side = [x for x in tail if x > pivot] #left_side와 right_side를 각각 재귀적으로 quick sorting을 해줌 return quick_sort(left_side) + [pivot] + quick_sort(right_side) print(quick_sort(array))
# hw02_07 money = int(input('請輸入存款金額:(整數)')) print('') yrate = float(input('請輸入年利率:(浮點數)')) # 書上有錯,這裡要填0.1,而不是10 print('') y = int(input('請輸入存款年數:(整數)')) print('單利:%d元%d年的本利和=%12.1f' % (money, y, money + money * yrate * y)) print('複利:%d元%d年的本利和=%12.1f' % (money, y, money * ((1 + yrate) ** y))) ''' 請輸入存款金額:(整數)20000 請輸入年利率:(浮點數)0.1 請輸入存款年數:(整數)3 單利:20000元3年的本利和= 26000.0 複利:20000元3年的本利和= 26620.0 '''
class Protocol(object): def __str__(self): _str = '<================ Constants information ================>\n' for name, value in self.__dict__.items(): print(name, value) _str += '\t{}\t{}\n'.format(name, value) return _str def __len__(self): raise NotImplementedError def __getitem__(self, item): raise NotImplementedError def format_name(self, name): return name def original_name(self, name): return name
class FastTextModel(object): def __init__(self, word_index, raw_word_vectors): pass def save_to_word2vec_format(self, word_vectors, output_path): pass
sexo = str(input('Digite o seu sexo [M/F]: ').strip().upper()[0]) while sexo != 'M' and sexo != 'F': print('''\033[1;31mAlerta! Você não digitou nenhuma das opções. Tente novamente.\033[m''') sexo = input('Digite o seu sexo [M/F]: ').strip().upper() if sexo == 'M': sexo = '\033[1;35mMasculino\033[m' elif sexo == 'F': sexo = '\033[1;35mFeminino\033[m' input('Sexo {} registrado com sucesso.'.format(sexo))
# Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua média. n1 = float(input('Digite a sua nota da prova 1:')) n2 = float(input('Digite a sua nota da sua prova 2:')) m = (n1 + n2) / 2 print('A sua média entre as duas notas equivale a {:.2f}'.format(m)) if m > 6:print('Está aprovado, boas férias') if m < 6:print('Está reprovado, consultar a secretária para fazer a recuperação')
class PhoneDirectory: def __init__(self, maxNumbers): self.nums = set(range(maxNumbers)) def get(self): return self.nums.pop() if self.nums else -1 def check(self, number): return number in self.nums def release(self, number): self.nums.add(number)
#!/usr/bin/env python class TestMyModule: ''' ``Test`` prefix ''' def test_f(self): ''' ``test_`` prefix ''' pass
tests = ( 'parse_token', 'variable_fields', 'template', 'loaders', 'filters', 'default_filters', 'blockextend', 'default_tags', )
standardRnaToProtein = { 'UUU':'F', 'UUC':'F', 'UCU':'S', 'UCC':'S', 'UAU':'Y', 'UAC':'Y', 'UGU':'C', 'UGC':'C', 'UUA':'L', 'UCA':'S', 'UAA':'*', 'UGA':'*', 'UUG':'L', 'UCG':'S', 'UAG':'*', 'UGG':'W', 'CUU':'L', 'CUC':'L', 'CCU':'P', 'CCC':'P', 'CAU':'H', 'CAC':'H', 'CGU':'R', 'CGC':'R', 'CUA':'L', 'CUG':'L', 'CCA':'P', 'CCG':'P', 'CAA':'Q', 'CAG':'Q', 'CGA':'R', 'CGG':'R', 'AUU':'I', 'AUC':'I', 'ACU':'T', 'ACC':'T', 'AAU':'N', 'AAC':'N', 'AGU':'S', 'AGC':'S', 'AUA':'I', 'ACA':'T', 'AAA':'K', 'AGA':'R', 'AUG':'M', 'ACG':'T', 'AAG':'K', 'AGG':'R', 'GUU':'V', 'GUC':'V', 'GCU':'A', 'GCC':'A', 'GAU':'D', 'GAC':'D', 'GGU':'G', 'GGC':'G', 'GUA':'V', 'GUG':'V', 'GCA':'A', 'GCG':'A', 'GAA':'E', 'GAG':'E', 'GGA':'G', 'GGG':'G'} proteinOneToThree = { 'A': 'Ala', 'C': 'Cys', 'D': 'Asp', 'E': 'Glu', 'F': 'Phe', 'G': 'Gly', 'H': 'His', 'I': 'Ile', 'K': 'Lys', 'L': 'Leu', 'M': 'Met', 'N': 'Asn', 'P': 'Pro', 'Q': 'Gln', 'R': 'Arg', 'S': 'Ser', 'T': 'Thr', 'V': 'Val', 'W': 'Trp', 'Y': 'Tyr' }
class Field(object): def __init__(self, default=None, null: bool = False): self.default = default self.null = null self.section = None self.name = None self.value = None self.meta = None def __get__(self, instance, owner): value = self.meta.connector.get_value(section_name=self.section.meta.name, attr_name=self.name) if value is None and self.default is not None: return self.default if value is None and self.null is True: return None return self.cast_value(value) def __set__(self, instance, value): if value is None: if self.null is False: raise ValueError('None value passed into non null Field') else: self.meta.connector.set_value(section_name=self.section.meta.name, attr_name=self.name, value=value) elif self.check_value(value) is True: self.meta.connector.set_value(section_name=self.section.meta.name, attr_name=self.name, value=value) else: raise TypeError('Incorrect type passed into Field') def cast_value(self, value): pass def check_value(self, value): pass def bind(self, section, name, meta): self.section = section self.name = name self.meta = meta class IntegerField(Field): def __init__(self, default: int = None, null: bool = False): super().__init__(default=default, null=null) def cast_value(self, value): return int(value) def check_value(self, value): return isinstance(value, int) class StringField(Field): def __init__(self, default: str = None, null: bool = False): super().__init__(default=default, null=null) def cast_value(self, value): return str(value).strip() def check_value(self, value): return isinstance(value, str) class FloatField(Field): def __init__(self, default: float = None, null: bool = False): super().__init__(default=default, null=null) def cast_value(self, value): return float(value) def check_value(self, value): return isinstance(value, float) class BooleanField(Field): def __init__(self, default: bool = None, null: bool = False): super().__init__(default=default, null=null) def cast_value(self, value): if value == 'True': return True elif value == 'False': return False else: return bool(value) def check_value(self, value): return isinstance(value, bool) class ListField(Field): def __init__(self, var_type: type, default: list = None, null: bool = False): self.type = var_type super().__init__(default, null) if self.type not in [int, str, float, bool]: raise Exception('Unknown base type %s passed into ListField' % str(self.type)) def cast_value(self, value): result = [] for element in value.replace('[', '').replace(']', '').split(','): if self.type == int: result.append(int(element.strip())) elif self.type == str: result.append(element.strip().replace("'", '')) elif self.type == float: result.append(float(element.strip())) elif self.type == bool: if element.strip() == 'True': result.append(True) elif element.strip() == 'False': result.append(False) else: result.append(bool(element.strip())) return result def check_value(self, value): return isinstance(value, list) and all(isinstance(n, self.type) for n in value)
#!/usr/bin/env python3 w, h = 12, 4 matrix = [[0 for iw in range(w)] for ih in range(h)] base_row = [] print("Grund-Zwölftonreihe eingeben") for i in range(12): base_row.append(int(input("\n {0}: ".format(i)))) print(base_row) for i in range(12): matrix[i][0] = 12 - matrix[0][i] print(matrix)
# simple_assignment.py # THIS FILE IS AUTOMATICALLY GENERATED FROM comments.pil. # DO NOT EDIT! foo = 5 print(foo)
NEO4J_TEST_CONNECTION = """MATCH (n) RETURN count(n) as count""" # create NEO4J_CREATE_DOCUMENT_NODE_RETURN_ID = """ CYPHER 3.4 CREATE (node { }) RETURN ID(node) as ID""" NEO4J_CREATE_NODE_SET_PART = "SET node.`{attr_name}` = {{`{attr_name}`}}" NEO4J_CREATE_NODE_SET_PART_MERGE_ATTR = "SET node.`{attr_name}` = (CASE WHEN not exists(node.`{attr_name}`) THEN [{{`{attr_name}`}}] ELSE node.`{attr_name}` + {{`{attr_name}`}} END)" NEO4J_CREATE_NODE_MERGE_CHECK_PART = """WITH CASE WHEN check = 0 THEN (CASE WHEN EXISTS(node.`{attr_name}`) AND node.`{attr_name}` <> {{`{attr_name}`}} THEN 1 ELSE 0 END) ELSE 1 END as check , node""" NEO4J_CREATE_NODE_RETURN_ID = """ CYPHER 3.4 MERGE (node:{label} {{{formal_attributes}}}) WITH 0 as check, node {merge_check_statement} {set_statement} RETURN ID(node) as ID, check """ # args: provType, values NEO4J_CREATE_RELATION_RETURN_ID = """ CYPHER 3.4 MATCH (from{{`meta:identifier`:'{from_identifier}'}}), (to{{`meta:identifier`:'{to_identifier}'}}) MERGE (from)-[r:{relation_type} {{{formal_attributes}}}]->(to) WITH 0 as check, r as node {merge_check_statement} {set_statement} RETURN ID(node) as ID, check """ # args: provType, values # get NEO4J_GET_RECORDS_BY_PROPERTY_DICT = """ CYPHER 3.4 MATCH (d {{{filter_dict}}} )-[r]-(x {{{filter_dict}}}) RETURN DISTINCT r as re //Get all nodes that are alone without connections to other nodes UNION MATCH (a {{{filter_dict}}}) RETURN DISTINCT a as re """ NEO4J_GET_RECORDS_TAIL_BY_FILTER = """ CYPHER 3.4 MATCH (x {{{filter_dict}}})-[r *{depth}]-(y) RETURN DISTINCT y as re UNION MATCH (x {{{filter_dict}}})-[r *{depth}]-(y) WITH REDUCE(output = [], r IN r | output + r) AS flat UNWIND flat as re RETURN DISTINCT re """ NEO4J_GET_BUNDLE_RECORDS = """ CYPHER 3.4 MATCH (x {`meta:identifier`: {`meta:identifier`}})-[r *1]-(y) WHERE ALL (rel in r WHERE rel.`prov:type` = 'prov:bundleAssociation') RETURN DISTINCT y as re UNION //get all relations between the nodes MATCH (origin {`meta:identifier`: {`meta:identifier`}})-[r *1]-(x)-[r_return *1]-(y)-[r_2 *1]-(origin {`meta:identifier`: {`meta:identifier`}}) WHERE ALL (rel in r WHERE rel.`prov:type` = 'prov:bundleAssociation') AND ALL (rel in r_2 WHERE rel.`prov:type` = 'prov:bundleAssociation') WITH REDUCE(output = [], r IN r_return | output + r) AS flat UNWIND flat as re RETURN DISTINCT re //get all mentionof relations UNION MATCH (bundle_1 {`meta:identifier`: {`meta:identifier`}})-[r *1]-(x)-[r_return *1]-(y)-[r_2 *1]-(bundle_2) WHERE ALL (rel in r WHERE rel.`prov:type` = 'prov:bundleAssociation') AND ALL (rel in r_2 WHERE rel.`prov:type` = 'prov:bundleAssociation') AND ALL (rel in r_return WHERE rel.`meta:prov_type` = 'prov:Mention' and startNode(rel) = x) WITH REDUCE(output = [], r IN r_return | output + r) AS flat UNWIND flat as re RETURN DISTINCT re """ NEO4J_GET_RECORD_RETURN_NODE = """ CYPHER 3.4 MATCH (node) WHERE ID(node)={record_id} RETURN node""" NEO4J_GET_RELATION_RETURN_NODE = """ CYPHER 3.4 MATCH ()-[relation]-() WHERE ID(relation)={relation_id} RETURN relation""" # delete NEO4J_DELETE__NODE_BY_ID = """ CYPHER 3.4 MATCH (x) Where ID(x) = {node_id} DETACH DELETE x """ NEO4J_DELETE_NODE_BY_PROPERTIES = """ CYPHER 3.4 MATCH (n {{{filter_dict}}}) DETACH DELETE n""" NEO4J_DELETE_BUNDLE_NODE_BY_ID = """ CYPHER 3.4 MATCH (b) WHERE id(b)=toInt({bundle_id}) DELETE b """ NEO4J_DELETE_RELATION_BY_ID = """ CYPHER 3.4 MATCH ()-[r]-() WHERE id(r) = {relation_id} DELETE r"""
# -*- coding: utf-8 -*- """ Utilities for generating ring crossings. """ def generate_crossings(points, n_rings): """ Generate a rings crossing dictionary from crossings points. :param list points: Points is a list of rings from 0 to N-1. Each list specifies the LED number of each point on the ring that is crossed by another ring. :return dict: A dictionary of (ring_1, led_1) -> (ring_2, led_2) mappings that specify that (ring_1, led_1) crosses to (ring_2, led_2). The mapping is commutative -- so if (r1, l1) -> (r2, l2) then (r2, l2) -> (r1, l1) too. """ assert n_rings == 6, "Crossings only supported for 6 rings." n_ring_crossings = 10 # only valid for n_rings == 6 r, g, b, y, c, m = range(6) # rings named by colour, in order d = {} # sequences sequences = [ [(g, 0), (c, 8), (y, 4), (b, 6), (m, 8), (g, 5), (c, 3), (y, 9), (b, 1), (m, 3)], # ring 0 (red, A) [(r, 0), (m, 2), (y, 1), (b, 9), (c, 2), (r, 5), (m, 7), (y, 6), (b, 4), (c, 7)], # ring 1 (green, B) [(y, 0), (r, 8), (m, 4), (c, 6), (g, 8), (y, 5), (r, 3), (m, 9), (c, 1), (g, 3)], # ring 2 (blue, C) [(b, 0), (g, 2), (m, 1), (c, 9), (r, 2), (b, 5), (g, 7), (m, 6), (c, 4), (r, 7)], # ring 3 (yellow, D) [(m, 0), (b, 8), (g, 4), (r, 6), (y, 8), (m, 5), (b, 3), (g, 9), (r, 1), (y, 3)], # ring 4 (cyan, E) [(c, 0), (y, 2), (g, 1), (r, 9), (b, 2), (c, 5), (y, 7), (g, 6), (r, 4), (b, 7)], # ring 5 (magenta, F) ] # check sequencing inverses are correct for i, crossings in enumerate(sequences): for p_i, other in enumerate(crossings): j, p_j = other assert sequences[j][p_j] == (i, p_i), ( "({}, {}) =!= ({}, {})".format(i, p_i, j, p_j)) # check all crossings present points_used = [[None] * n_ring_crossings for _ in range(n_rings)] for i, crossings in enumerate(sequences): for p_i, other in enumerate(crossings): j, p_j = other points_used[j][p_j] = p_j expected_points_used = [ list(range(n_ring_crossings)) for _ in range(n_rings) ] assert points_used == expected_points_used, ( "Expected all crossings to be used") # crossing points for i, crossings in enumerate(sequences): for p_i, other in enumerate(crossings): j, p_j = other d[(i, points[i][p_i])] = (j, points[j][p_j]) return d def generate_base_crossing_points(c, n_rings): """ Generate a list of crossing points for each ring. :param int c: The number of LEDs in a ring. :return list: Return points as a list of rings from 0 to N-1. Each list specifies the LED number of each point on the ring that is crossed by another ring. """ assert n_rings == 6, "Crossings only supported for 6 rings." c2 = c / 2 # mid point ss = c / 12 # short side sl = ss + (c / 32) # long side ssl = ss + sl # both sides together ring = [ 0, ss, ssl, c2 - ssl, c2 - ss, c2, c2 + ss, c2 + ssl, c - ssl, c - ss, ] crossing_points = [ring[:] for _ in range(n_rings)] return crossing_points
# GENERATED VERSION FILE # TIME: Thu Aug 6 08:41:19 2020 __version__ = '0.7.rc1+82bf68a' short_version = '0.7.rc1' mmskl_home = r'/home/wing_mac/action_recognition/mmskeleton'
class SqlError(Exception): def __init__(self, message="Salary != in (5000, 15000) range"): self.message = message super().__init__(self.message)
# vat.py price = 100 # GBP, no VAT final_price1 = price * 1.2 final_price2 = price + price / 5.0 final_price3 = price * (100 + 20) / 100.0 final_price4 = price + price * 0.2 if __name__ == "__main__": for var, value in sorted(vars().items()): if 'price' in var: print(var, value)
# -*- coding: UTF-8 -*- # config.py にコピーして使用する CONFIG = { "baseUrl": "http://api.example.com/api", "tenantId": "", "appId": "", "appKey": "", "proxy": { "type": "http", "host": "proxygate2.nic.nec.co.jp:8080" } }
def hash_get_func(name, key, redisConnect): result =redisConnect.hget(name, key) return result def hash_set_func(name, key, value,redisConnect): result =redisConnect.hset(name, key,value) return result def hash_mget_func(name, L_key, redisConnect): result =redisConnect.hmget(name, L_key) return result def hash_mset_func(name, L_key,L_value,redisConnect): if (len(L_key) != len(L_value)): return 0 dict_key_value = dict(zip(L_key, L_value)) result =redisConnect.hmset(name, dict_key_value) return result def hash_hexists_func(name, key,redisConnect): result =redisConnect.hexists(name, key) return result def hash_del_func(name, L_key,redisConnect): result = redisConnect.hdel(name, L_key) return result dic_string_commandswitch = {"hash_getcommand":hash_get_func, "hash_setcommand":hash_set_func, "hash_mgetscommand":hash_mget_func, "hash_msetcommand": hash_mset_func, "hash_hexists":hash_hexists_func, "hash_delcommand":hash_del_func} def hash_func(command,redisConnect): ''' 运行hash命令 :return: ''' print('hash_func') hash_command_type = "hash_wrong_command" L_command_words = command.split(' ') if (len(L_command_words) < 2): print("command len is error\n") return if (L_command_words[0] == "hset" and len(L_command_words) == 4): name=L_command_words[1] key=L_command_words[2] value=L_command_words[3] result=hash_set_func(name,key,value,redisConnect) return result elif (L_command_words[0] == "hget" and len(L_command_words) == 3): name = L_command_words[1] key = L_command_words[2] result = hash_get_func(name, key,redisConnect) return result elif (L_command_words[0] == "hmset" and len(L_command_words) % 2 == 0 and len(L_command_words)>=6): name = L_command_words[1] L_key=L_command_words[2:len(L_command_words):2] L_value=L_command_words[3:len(L_command_words):2] result = hash_mset_func(name, L_key,L_value, redisConnect) return result elif (L_command_words[0] == "hmget" and len(L_command_words) >= 3): name = L_command_words[1] L_key = L_command_words[1:] result = hash_mget_func(name, L_key,redisConnect) return result elif (L_command_words[0] == "hexists" and len(L_command_words) == 3): name = L_command_words[1] key = L_command_words[2] result = hash_hexists_func(name, key, redisConnect) return result elif (L_command_words[0] == "hdel" and len(L_command_words) >= 3): name = L_command_words[1] L_key = L_command_words[1:] result = hash_del_func(name, L_key, redisConnect) return result
class Solution: def numberOfMatches(self, n: int) -> int: count = 0 while n >= 2: count += n // 2 print(count) if n % 2: n = n // 2 + 1 else: n = n // 2 return count
"""This module contains the set of Ostorlab exceptions.""" class OstorlabError(Exception): """Ostorlab base error that all the exceptions inherit from."""
#!/usr/bin/env python class HmiMessage(object): def __init__(self): pass class CloseMessage(HmiMessage): def __init__(self): super(CloseMessage, self).__init__() class HmiModbusMessage(HmiMessage): def __init__(self, ip, mb_table): super(HmiModbusMessage, self).__init__() self.ip = ip self.mb_table = mb_table class ReadMessage(HmiModbusMessage): def __init__(self, ip, mb_table, starting_addr, quantity=1): super(ReadMessage, self).__init__(ip, mb_table) self.starting_addr = starting_addr self.quantity = quantity class ReadMessageResult(object): def __init__(self, value): self.value = value class WriteMessage(HmiModbusMessage): def __init__(self, ip, mb_table, starting_addr, quantity, values): super(WriteMessage, self).__init__(ip, mb_table) self.starting_addr = starting_addr self.quantity = quantity self.values = values class SuccessHmiMessage(HmiMessage): def __init__(self): super(SuccessHmiMessage, self).__init__() class FailedHmiMessage(HmiMessage): def __init__(self): super(FailedHmiMessage, self).__init__()
N = int(input()) G = [int(x) for x in input().split()] trueG = list(range(N)) for i in range(N): for j in range(N): G[j] = (G[j] + (-1 if j % 2 else 1)) % N if G == trueG: print('Yes') break else: print('No')
class APIException(Exception): def __init__(self): self.message = '!200 response from api' class OpenConvException(Exception): def __init__(self): self.message = 'Error while opening conv non 200 response' class OpenConvServerException(Exception): def __init__(self): self.message = 'Get error response on opening conv'
class Inference(object): def __init__(self, file_path, file_name, class_name, class_function, variable_name, variable_type, inference_variable_path, is_external_package = False, line_no = 0): self.file_path = file_path self.file_name = file_name self.class_name = class_name self.class_function = class_function self.origin_module = None #O modulo que pertence ao tipo que estamos tentando inferir self.inference_fullname = f"{file_name}::{class_name}::{self.class_function}" self.variable_name = variable_name self.variable_type = variable_type self.inference_variable_path = inference_variable_path self.inferred_module_name = None #o módulo que pertence o tipo inferido self.is_external_package = is_external_package self.line_no = line_no # self.inferred_full_name = def get_tuple_representation(self): return (self.inference_fullname, self.variable_name, self.variable_type) def set_origin_module(self, module): self.origin_module = module def set_inferred_module_name(self, module): self.inferred_module_name = module def get_key(self): return self.inference_fullname + self.variable_name + self.variable_type def get_detailed_inference(self): return { "file_path" : self.file_path, "file_name": self.file_name, "class_name": self.class_name, "class_function": self.class_function, "origin_module" : self.origin_module, "variable_name": self.variable_name, "variable_inferred_type": self.variable_type, "variable_inferred_path" : self.inference_variable_path, "inferred_module_name" : self.inferred_module_name }
name = input('Введите имя: ') id = int(input('Введите номер заказа: ')) result = 'Здравствуйте {0}, ваш номер заказа: {1}, спасибо за покупку!!'.format(name, id) print(result)
n = list(map(int, input().split())) if (n[1] % 2 == 0): print("possible") else: print("impossible")
# vim: fileencoding=utf-8 a = """bbbbbb aaaaaaaaaa """ b = '''aaaaa dfdfd3''' print(a) print('--------------') print(b) print('=================') print(str(1)) print(int('1')) print('=================') print('3' in b) print('=================') m1 = 'I am {}'.format('Yujiii') print(m1) m2 = '{2}-{2} {0} {1}'.format('aa', 'bb', 'cc') print(m2) m3 = '{aa} AND {bb}'.format(bb='なんだって', aa=1) print(m3) m4 = '|{2:7s}|{1:7s}|{0:7s}|'.format('aaa', 'bbbccccccccccZ', 'cccbbb') print(m4) m5 = '|{2:7.2f}|{1:7.2f}|{0:7.3f}|'.format(1.2, 3.3, 5.5) print(m5) print('=================') aa = ['1', '2', 'bb'] print(','.join(aa)) print('=================') name = 'Yuji' m6 = 'あいうえお %s' % name print(m6) # リストやタプルを文字列展開する場合 print('list is %s' % ['aaaa', 1, 2]) # http://qiita.com/tomotaka_ito/items/594ee1396cf982ba9887 print('divmod: %s' % (divmod(5, 2),)) print('aaa is %(a)s' % dict(a='AAA')) print('|%7s|%7s|%7s|' % ('one', 'two', 'three')) print('|%7d|%7d|%7d|' % (1, 2, 3)) print('|%7.2f|%7.2f|%7.4f|' % (1.1, 2.22, 3.333)) print('|%-7s|%-7s|%-7s|' % ('one', 'two', 'three')) print('=================') str = 'abcdefghijklmnopqrstuvwxyz' print(len(str)) print(str[:23]) print(str[0:]) print(str[:]) print(str[::2]) # 添字が偶数番目の取り出し(先頭から一つ飛ばし) print(str[1::2]) # 添字書き数番目の取り出し print(str[::-1]) # 逆順取り出し print('=================') # バイト列の変換 str = '日本語' str_enc = str.encode('utf-8') str_dec = str_enc.decode('utf-8') print(str) print(str_enc) print(str_dec)
''' In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1. Two nodes of a binary tree are cousins if they have the same depth, but have different parents. We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree. Return true if and only if the nodes corresponding to the values x and y are cousins. Input: root = [1,2,3,4], x = 4, y = 3 Output: false ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def adjacent(self, root, node1, node2): if not root: return False value = False if (root.right and root.left): value = ((root.left.val == node1 and root.right.val == node2) or (root.left.val == node2 and root.right.val == node1)) return (value or self.adjacent(root.left, node1, node2) or self.adjacent(root.right, node1, node2)) def _level(self, root, node, level): if not root: return 0 if root.val == node: return level left_level = self._level(root.left, node, level+1) if left_level != 0: return left_level return self._level(root.right, node, level+1) def isCousins(self, root, x, y): """ :type root: TreeNode :type x: int :type y: int :rtype: bool """ if ((self._level(root, x, 1) == self._level(root, y, 1)) and not self.adjacent(root, x, y)): return True return False
""" Model parameters. """ sys_params = { 'food_growth_rate': [3], 'maximum_food_per_site': [10], 'reproduction_probability': [1.0], 'agent_lifespan': [35], 'reproduction_food_threshold': [6], # When the agents start reproducing 'hunger_threshold': [15], # When the agents start eating 'reproduction_food': [1] # How much food is needed for reproducing }
# The arduino accepts commands in 1/10 millimeters UNIT = 10 class Line: def __init__(self, x1, y1, x2, y2): self.x1 = float(x1) self.y1 = float(y1) self.x2 = float(x2) self.y2 = float(y2) def __eq__(self, other): return isinstance(other, self.__class__) \ and (self.x1 == other.x1) \ and (self.y1 == other.y1) \ and (self.x2 == other.x2) \ and (self.y2 == other.y2) def __ne__(self, other): return not self.__eq__(other) def instruction(self): return [ 'M {0} {1}'.format(self.x1 * UNIT, self.y1 * UNIT), 'L {0} {1}'.format(self.x2 * UNIT, self.y2 * UNIT) ] class Rect: def __init__(self, x, y, width, height): self.x = float(x) self.y = float(y) self.width = float(width) self.height = float(height) # Translate a rectangle to 4 lines def instruction(self): instructions = [] instructions.append('M ' + str(float(self.x) * UNIT) + ' ' + str(float(self.y) * UNIT)) instructions.append('L ' + str(float(self.x + self.width) * UNIT) + ' ' + str(float(self.y) * UNIT)) instructions.append('L ' + str(float(self.x + self.width) * UNIT) + ' ' + str(float(self.y + self.height) * UNIT)) instructions.append('L ' + str(float(self.x) * UNIT) + ' ' + str(float(self.y + self.height) * UNIT)) instructions.append('L ' + str(float(self.x) * UNIT) + ' ' + str(float(self.y) * UNIT)) return instructions class Polygon: # Example value: points="750,600 629.7,659.4 600,792.9 683.2,900 816.8,900 900,792.9 870.3,659.4 " def __init__(self, points): self.points = points.strip().split() # Add starting point to the back to get the last line self.points.append(self.points[0]) self.points = list(map(lambda x: x.split(','), self.points)) def instruction(self): instructions = [] instructions.append('M ' + str(float(self.points[0][0]) * UNIT) + ' ' + str(float(self.points[0][1]) * UNIT)) for i, point in enumerate(self.points[1:]): instructions.append('L ' + str(float(self.points[i][0]) * UNIT) + ' ' + str(float(self.points[i][1]) * UNIT)) instructions.append('L ' + str(float(self.points[0][0]) * UNIT) + ' ' + str(float(self.points[0][1]) * UNIT)) return instructions
def check_and_apply(queue, rule): r = rule[0].split() l = len(r) if len(queue) >= l: t = queue[-l:] if list(zip(*t)[0]) == r: new_t = rule[1](list(zip(*t)[1])) del queue[-l:] queue.extend(new_t) return True return False rules = [] # k, n, s = fn(k, n) # k: karel_world # n: num_call # s: success # c: condition [True, False] MAX_WHILE = 100 def r_prog(t): stmt = t[3] return [('prog', stmt(0, 0))] rules.append(('DEF run m( stmt m)', r_prog)) def r_stmt(t): stmt = t[0] def fn(k, n): return stmt(k, n) return [('stmt', fn)] rules.append(('while_stmt', r_stmt)) rules.append(('repeat_stmt', r_stmt)) rules.append(('stmt_stmt', r_stmt)) rules.append(('action', r_stmt)) rules.append(('if_stmt', r_stmt)) rules.append(('ifelse_stmt', r_stmt)) def r_stmt_stmt(t): stmt1, stmt2 = t[0], t[1] def fn(k, n): return stmt1(k, n) + stmt2(k, n) return [('stmt_stmt', fn)] rules.append(('stmt stmt', r_stmt_stmt)) def r_if(t): cond, stmt = t[2], t[5] def fn(k, n): return ['if'] + cond(k, n) + stmt(k, n) return [('if_stmt', fn)] rules.append(('IF c( cond c) i( stmt i)', r_if)) def r_ifelse(t): cond, stmt1, stmt2 = t[2], t[5], t[9] def fn(k, n): stmt1_out = stmt1(k, n) stmt2_out = stmt2(k, n) if stmt1_out == stmt2_out: return stmt1_out cond_out = cond(k, n) if cond_out[0] == 'not': else_cond = ['if'] + cond_out[1:] else: else_cond = ['if', 'not'] + cond_out return ['if'] + cond_out + stmt1_out + else_cond + stmt2_out return [('ifelse_stmt', fn)] rules.append(('IFELSE c( cond c) i( stmt i) ELSE e( stmt e)', r_ifelse)) def r_while(t): cond, stmt = t[2], t[5] def fn(k, n): cond_out = cond(k, n) stmt_out = stmt(k, n) while_out = [] for _ in range(MAX_WHILE): while_out.extend(['if'] + cond_out + stmt_out) return while_out return [('while_stmt', fn)] rules.append(('WHILE c( cond c) w( stmt w)', r_while)) def r_repeat(t): cste, stmt = t[1], t[3] def fn(k, n): repeat_out = [] for _ in range(cste()): repeat_out.extend(stmt(k, n)) return repeat_out return [('repeat_stmt', fn)] rules.append(('REPEAT cste r( stmt r)', r_repeat)) def r_cond1(t): cond = t[0] def fn(k, n): return cond(k, n) return [('cond', fn)] rules.append(('cond_without_not', r_cond1)) def r_cond2(t): cond = t[2] def fn(k, n): cond_out = cond(k, n) if cond_out[0] == 'not': cond_out = cond_out[1:] else: cond_out = ['not'] + cond_out return cond_out return [('cond', fn)] rules.append(('not c( cond c)', r_cond2)) def r_cond_without_not1(t): def fn(k, n): return ['frontIsClear'] return [('cond_without_not', fn)] rules.append(('frontIsClear', r_cond_without_not1)) def r_cond_without_not2(t): def fn(k, n): return ['leftIsClear'] return [('cond_without_not', fn)] rules.append(('leftIsClear', r_cond_without_not2)) def r_cond_without_not3(t): def fn(k, n): return ['rightIsClear'] return [('cond_without_not', fn)] rules.append(('rightIsClear', r_cond_without_not3)) def r_cond_without_not4(t): def fn(k, n): return ['markersPresent'] return [('cond_without_not', fn)] rules.append(('markersPresent', r_cond_without_not4)) def r_cond_without_not5(t): def fn(k, n): return ['not', 'markersPresent'] return [('cond_without_not', fn)] rules.append(('noMarkersPresent', r_cond_without_not5)) def r_action1(t): def fn(k, n): return ['move'] return [('action', fn)] rules.append(('move', r_action1)) def r_action2(t): def fn(k, n): return ['turnLeft'] return [('action', fn)] rules.append(('turnLeft', r_action2)) def r_action3(t): def fn(k, n): return ['turnRight'] return [('action', fn)] rules.append(('turnRight', r_action3)) def r_action4(t): def fn(k, n): return ['pickMarker'] return [('action', fn)] rules.append(('pickMarker', r_action4)) def r_action5(t): def fn(k, n): return ['putMarker'] return [('action', fn)] rules.append(('putMarker', r_action5)) def create_r_cste(number): def r_cste(t): return [('cste', lambda: number)] return r_cste for i in range(20): rules.append(('R={}'.format(i), create_r_cste(i))) def parse(program): p_tokens = program.split()[::-1] queue = [] applied = False while len(p_tokens) > 0 or len(queue) != 1: if applied: applied = False else: queue.append((p_tokens.pop(), None)) for rule in rules: applied = check_and_apply(queue, rule) if applied: break if not applied and len(p_tokens) == 0: # error parsing return None, False return queue[0][1], True
_base_ = [ '../_base_/models/faster_rcnn_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_3x.py', '../_base_/default_runtime.py' ] ''' model = dict( neck=dict( type='PAFPN', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=5), test_cfg=dict( rcnn=dict( score_thr=0.05, nms=dict(type='soft_nms', iou_threshold=0.5), max_per_img=100)) ) ''' pretrained = 'https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_tiny_patch4_window7_224.pth' # noqa model = dict( backbone=dict( _delete_=True, type='SwinTransformer', embed_dims=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7, mlp_ratio=4, qkv_bias=True, qk_scale=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0.2, patch_norm=True, out_indices=(0, 1, 2, 3), with_cp=False, convert_weights=True, init_cfg=dict(type='Pretrained', checkpoint=pretrained)), neck=dict(in_channels=[96, 192, 384, 768]))
class Parser: def parse(self, string): """ Returns a dictionary which has a structure like this: - com - arg1 - arg2 ... -argN """ parsedString = {} strArr = string.split() parsedString['com'] = strArr[0] for i in range(1, len(strArr)): parsedString[f'arg{i}'] = strArr[i] return parsedString
""" What? Simplest unit check (as opposed to integration checks) Keep in mind that python sum function accepts any iterables. Reference: https://realpython.com/python-testing/ """ def test_sum_list(): assert sum([1, 2, 3]) == 6, "Should be 6" def test_sum_tuple(): assert sum((1, 2, 2)) == 5, "Should be 6" if __name__ == "__main__": test_sum_list() test_sum_tuple() print("Everything passed")
""" EOS CLI syntax changes """ CLI_SYNTAX = { # Default CLI syntax version # We do trandlation from 4.23.0 syntax to pre-4.23.0 syntax 1: { "aaa authorization serial-console": "aaa authorization console", "area not-so-stubby lsa type-7 convert type-5": "area nssa translate type7 always", "arp aging timeout": "arp timeout", "bfd default": "bfd all-interfaces", "dynamic peer max": "bgp listen limit", "class-map type copp": "class-map type control-plane", "clear arp": "clear ip arp", "clear ip nat flow translation": "clear ip nat translation", "clear ospfv3 ipv6 force-spf": "clear ipv6 ospf force-spf", "system control-plane": "control-plane", "metric default": "default-metric", "dot1x reauthorization request limit ": "dot1x max-reauth-req", "enable password": "enable secret", "delete startup-config": "erase startup-config", "errdisable detect cause link-change": "errdisable detect cause link-flap", "ip community-list regexp": "ip community-list expanded", "ip dhcp relay all-subnets": "ip dhcp smart-relay", "ip dhcp relay all-subnets default": "ip dhcp smart-relay global", "dns domain": "ip domain-name", "ip extcommunity-list regexp": "ip extcommunity-list expanded", "ip extcommunity-list": "ip extcommunity-list standard", "ip http client local-interface": "ip http client source-interface", "query-max-response-time": "ip igmp query-max-response-time", "ip igmp snooping vlan fast-leave": "ip igmp snooping vlan immediate-leave", "ip igmp snooping vlan multicast-router": "ip igmp snooping vlan mrouter", "ip igmp snooping vlan member": "ip igmp snooping vlan static", # disabled next command because of ambiguity # 'default-peer': 'ip msdp default-peer', # disabled next command because of ambiguity # 'description': 'ip msdp description', "sa-limit": "ip msdp group-limit", # disabled next command because of ambiguity # 'keepalive': 'ip msdp keepalive', "mesh-group": "ip msdp mesh-group", "originator-id local-interface": "ip msdp originator-id", # disabled next command because of ambiguity # 'peer': 'ip msdp peer', "sa filter in": "ip msdp sa-filter in", "sa filter out": "ip msdp sa-filter out", "sa limit": "ip msdp sa-limit", # disabled next command because of ambiguity # 'disabled': 'ip msdp shutdown', "connection retry interval": "ip msdp timer", "ip ospf neighbor bfd": "ip ospf bfd", "router-id output-format hostnames": "ip ospf name-lookup", "ip ospf disabled": "ip ospf shutdown", "anycast-rp": "ip pim anycast-rp", # disabled next command because of ambiguity # 'bfd': 'ip pim bfd', "pim bfd": "ip pim bfd-instance", "pim bsr border": "ip pim bsr-border", "log neighbors": "ip pim log-neighbor-changes", "pim neighbor filter": "ip pim neighbor-filter", "pim hello interval": "ip pim query-interval", "register local-interface": "ip pim register-source", "spt threshold match list": "ip pim spt-threshold group-list", "ssm address range": "ip pim ssm range", "rip v2 multicast disable": "ip rip v2-broadcast", "ipv6 nd ra disabled": "ipv6 nd ra suppress", "ospfv3 ipv6 retransmit-interval": "ipv6 ospf retransmit-interval", "isis lsp tx interval": "isis lsp-interval", # disabled next command because of ambiguity # 'passive': 'passive-interface', "lacp timer": "lacp rate", "link tracking group ": "link state track", "lldp hold-time": "lldp holdtime", "lldp timer reinitialization": "lldp reinit", "lldp tlv transmit": "lldp tlv-select", "neighbor bfd": "neighbor fall-over bfd", "neighbor peer group": "neighbor peer-group", "neighbor rib-in pre-policy retain": "neighbor soft-reconfiguration", "neighbor passive": "neighbor transport connection-mode", "ntp local-interface": "ntp source", "policy-map type copp": "policy-map type control-plane", "policy-map type quality-of-service": "policy-map type qos", "priority-flow-control": "priority-flow-control mode", "pvlan mapping": "private-vlan mapping", "ptp sync-message interval": "ptp sync interval", "redundancy manual switchover": "redundancy force-switchover", "cli vrf ": "routing-context vrf", "logging format sequence-numbers": "service sequence-numbers", "show aaa methods": "show aaa method-lists", "show users detail": "show aaa sessions", "show bfd peers": "show bfd neighbors", "show dot1x all brief": "show dot1x all summary", "show system environment all": "show environment all", "show system environment cooling": "show environment cooling", "show interfaces hardware": "show interfaces capabilities", "show interfaces flow-control": "show interfaces flowcontrol", "show pvlan mapping interfaces": "show interfaces private-vlan mapping", "show interfaces switchport backup-link": "show interfaces switchport backup", "show igmp snooping querier": "show ip igmp snooping querier", "show multicast fib ipv4": "show ip mfib", "show msdp mesh-group": "show ip msdp mesh-group", "show msdp rpf-peer": "show ip msdp rpf-peer", "show ip ospf request queue": "show ip ospf request-list", "show ip ospf retransmission queue": "show ip ospf retransmission-list", "show ip route match tag": "show ip route tag", "show ipv6 bgp match community": "show ipv6 bgp community", "show ipv6 bgp peers": "show ipv6 bgp neighbors", "show ipv6 route match tag": "show ipv6 route tag", "show isis network topology": "show isis topology", "show lacp peer": "show lacp neighbor", "show link tracking group": "show link state group", "show lldp counters": "show lldp traffic", "show bridge mac-address-table aging timeout": "show mac-address-table aging-time", "show policy-map type copp": "show policy-map control-plane", "show policy-map copp": "show policy-map interface control-plane", "show port-channel dense": "show port-channel summary", "show port-channel load-balance": "show port-channel traffic", "show port-security mac-address": "show port-security address", "show ptp local-clock": "show ptp clock", "show ptp masters": "show ptp parent", "show ptp local-clock time properties": "show ptp time-property", "show redundancy status": "show redundancy states", "show users roles": "show role", "show snmp v2-mib chassis": "show snmp chassis", "show snmp v2-mib contact": "show snmp contact", "show snmp notification host": "show snmp host", "show snmp v2-mib location": "show snmp location", "show snmp local-interface": "show snmp source-interface", "show snmp notification": "show snmp trap", "show spanning-tree instance": "show spanning-tree bridge", "show users accounts": "show user-account", "show vlan brief count": "show vlan summary", "snmp trap link-change": "snmp trap link-status", "snmp-server local-interface": "snmp-server source-interface", "spanning-tree transmit active": "spanning-tree bridge assurance", "spanning-tree guard loop default": "spanning-tree loopguard default", "spanning-tree edge-port bpdufilter default": "spanning-tree portfast bpdufilter default", "spanning-tree edge-port bpduguard default": "spanning-tree portfast bpduguard default", "spanning-tree bpdu tx hold-count": "spanning-tree transmit hold-count", "spanning-tree vlan-id": "spanning-tree vlan", "counters per-entry": "statistics per-entry", "switchport backup-link": "switchport backup interface", "switchport port-security mac-address maximum": "switchport port-security maximum", "switchport vlan translation": "switchport vlan mapping", # disabled next command because of ambiguity # 'timers': 'timers basic', "timers lsa rx min interval": "timers lsa arrival", "timers lsa tx delay initial": "timers throttle lsa all", "timers spf delay initial": "timers throttle spf", "username ssh-key": "username sshkey", "vlan internal order": "vlan internal allocation policy", "vrf instance": "vrf definition", # disabled next command because of ambiguity # 'vrf': 'vrf forwarding', "vrrp peer authentication": "vrrp authentication", "vrrp timers delay reload": "vrrp delay reload", "vrrp session description": "vrrp description", "vrrp ipv4": "vrrp ip", "vrrp ipv4 secondary": "vrrp ip secondary", "vrrp priority-level": "vrrp priority", "vrrp disabled": "vrrp shutdown", "vrrp advertisement interval": "vrrp timers advertise", "vrrp tracked-object": "vrrp track", }, # CLI syntax version after EOS 4.23.0 2: { "aaa authorization console": "aaa authorization serial-console", "area nssa translate type7 always": "area not-so-stubby lsa type-7 convert type-5", "arp timeout": "arp aging timeout", "bfd all-interfaces": "bfd default", "bgp listen limit": "dynamic peer max", "class-map type control-plane": "class-map type copp", "clear ip arp": "clear arp", "clear ip nat translation": "clear ip nat flow translation", "clear ipv6 ospf force-spf": "clear ospfv3 ipv6 force-spf", "control-plane": "system control-plane", "default-metric": "metric default", "dot1x max-reauth-req": "dot1x reauthorization request limit ", "enable secret": "enable password", "erase startup-config": "delete startup-config", "errdisable detect cause link-flap": "errdisable detect cause link-change", "ip community-list expanded": "ip community-list regexp", "ip dhcp smart-relay": "ip dhcp relay all-subnets", "ip dhcp smart-relay global": "ip dhcp relay all-subnets default", "ip domain-name": "dns domain", "ip extcommunity-list expanded": "ip extcommunity-list regexp", "ip extcommunity-list standard": "ip extcommunity-list", "ip http client source-interface": "ip http client local-interface", "ip igmp query-max-response-time": "query-max-response-time", "ip igmp snooping vlan immediate-leave": "ip igmp snooping vlan fast-leave", "ip igmp snooping vlan mrouter": "ip igmp snooping vlan multicast-router", "ip igmp snooping vlan static": "ip igmp snooping vlan member", "ip msdp default-peer": "default-peer", "ip msdp description": "description", "ip msdp group-limit": "sa-limit", "ip msdp keepalive": "keepalive", "ip msdp mesh-group": "mesh-group", "ip msdp originator-id": "originator-id local-interface", "ip msdp peer": "peer", "ip msdp sa-filter in": "sa filter in", "ip msdp sa-filter out": "sa filter out", "ip msdp sa-limit": "sa limit", "ip msdp shutdown": "disabled", "ip msdp timer": "connection retry interval", "ip ospf bfd": "ip ospf neighbor bfd", "ip ospf name-lookup": "router-id output-format hostnames", "ip ospf shutdown": "ip ospf disabled", "ip pim anycast-rp": "anycast-rp", "ip pim bfd": "bfd", "ip pim bfd-instance": "pim bfd", "ip pim bsr-border": "pim bsr border", "ip pim log-neighbor-changes": "log neighbors", "ip pim neighbor-filter": "pim neighbor filter", "ip pim query-interval": "pim hello interval", "ip pim register-source": "register local-interface", "ip pim spt-threshold group-list": "spt threshold match list", "ip pim ssm range": "ssm address range", "ip rip v2-broadcast": "rip v2 multicast disable", "ipv6 nd ra suppress": "ipv6 nd ra disabled", "ipv6 ospf retransmit-interval": "ospfv3 ipv6 retransmit-interval", "isis lsp-interval": "isis lsp tx interval", "passive-interface": "passive", "lacp rate": "lacp timer", "link state track": "link tracking group ", "lldp holdtime": "lldp hold-time", "lldp reinit": "lldp timer reinitialization", "lldp tlv-select": "lldp tlv transmit", "neighbor fall-over bfd": "neighbor bfd", "neighbor peer-group": "neighbor peer group", "neighbor soft-reconfiguration": "neighbor rib-in pre-policy retain", "neighbor transport connection-mode": "neighbor passive", "ntp source": "ntp local-interface", "policy-map type control-plane": "policy-map type copp", "policy-map type qos": "policy-map type quality-of-service", "priority-flow-control mode": "priority-flow-control", "private-vlan mapping": "pvlan mapping", "ptp sync interval": "ptp sync-message interval", "redundancy force-switchover": "redundancy manual switchover", "routing-context vrf": "cli vrf ", "service sequence-numbers": "logging format sequence-numbers", "show aaa method-lists": "show aaa methods", "show aaa sessions": "show users detail", "show bfd neighbors": "show bfd peers", "show dot1x all summary": "show dot1x all brief", "show environment all": "show system environment all", "show environment cooling": "show system environment cooling", "show interfaces capabilities": "show interfaces hardware", "show interfaces flowcontrol": "show interfaces flow-control", "show interfaces private-vlan mapping": "show pvlan mapping interfaces", "show interfaces switchport backup": "show interfaces switchport backup-link", "show ip igmp snooping querier": "show igmp snooping querier", "show ip mfib": "show multicast fib ipv4", "show ip msdp mesh-group": "show msdp mesh-group", "show ip msdp rpf-peer": "show msdp rpf-peer", "show ip ospf request-list": "show ip ospf request queue", "show ip ospf retransmission-list": "show ip ospf retransmission queue", "show ip route tag": "show ip route match tag", "show ipv6 bgp community": "show ipv6 bgp match community", "show ipv6 bgp neighbors": "show ipv6 bgp peers", "show ipv6 route tag": "show ipv6 route match tag", "show isis topology": "show isis network topology", "show lacp neighbor": "show lacp peer", "show link state group": "show link tracking group", "show lldp traffic": "show lldp counters", "show mac-address-table aging-time": "show bridge mac-address-table aging timeout", "show policy-map control-plane": "show policy-map type copp", "show policy-map interface control-plane": "show policy-map copp", "show port-channel summary": "show port-channel dense", "show port-channel traffic": "show port-channel load-balance", "show port-security address": "show port-security mac-address", "show ptp clock": "show ptp local-clock", "show ptp parent": "show ptp masters", "show ptp time-property": "show ptp local-clock time properties", "show redundancy states": "show redundancy status", "show role": "show users roles", "show snmp chassis": "show snmp v2-mib chassis", "show snmp contact": "show snmp v2-mib contact", "show snmp host": "show snmp notification host", "show snmp location": "show snmp v2-mib location", "show snmp source-interface": "show snmp local-interface", "show snmp trap": "show snmp notification", "show spanning-tree bridge": "show spanning-tree instance", "show user-account": "show users accounts", "show vlan summary": "show vlan brief count", "snmp trap link-status": "snmp trap link-change", "snmp-server source-interface": "snmp-server local-interface", "spanning-tree bridge assurance": "spanning-tree transmit active", "spanning-tree loopguard default": "spanning-tree guard loop default", "spanning-tree portfast bpdufilter default": "spanning-tree edge-port bpdufilter default", "spanning-tree portfast bpduguard default": "spanning-tree edge-port bpduguard default", "spanning-tree transmit hold-count": "spanning-tree bpdu tx hold-count", "spanning-tree vlan": "spanning-tree vlan-id", "statistics per-entry": "counters per-entry", "switchport backup interface": "switchport backup-link", "switchport port-security maximum": "switchport port-security mac-address maximum", "switchport vlan mapping": "switchport vlan translation", "timers basic": "timers", "timers lsa arrival": "timers lsa rx min interval", "timers throttle lsa all": "timers lsa tx delay initial", "timers throttle spf": "timers spf delay initial", "username sshkey": "username ssh-key", "vlan internal allocation policy": "vlan internal order", "vrf definition": "vrf instance", "vrf forwarding": "vrf", "vrrp authentication": "vrrp peer authentication", "vrrp delay reload": "vrrp timers delay reload", "vrrp description": "vrrp session description", "vrrp ip": "vrrp ipv4", "vrrp ip secondary": "vrrp ipv4 secondary", "vrrp priority": "vrrp priority-level", "vrrp shutdown": "vrrp disabled", "vrrp timers advertise": "vrrp advertisement interval", "vrrp track": "vrrp tracked-object", }, } class CliConverter: """ ClI converter class """ def __init__(self, syntax): """ Object creation :param syntax: syntax dict """ self.syntax = syntax def convert(self, command, version): """ Convert command from version 1 to specified version :param command: str: command :param version: int: version number :return: str: command """ if version not in self.syntax: return command for c in self.syntax[version]: if command.startswith(c): return self.syntax[version][c] + command[len(c) :] return command CONVERTER = CliConverter(CLI_SYNTAX) def cli_convert(command, version): """ Convert command from CLI version 1 to one from CLI of specified version :param command: str: CLI command :param version: int: EOS CLI version number :return: str: command """ return CONVERTER.convert(command, version)
# Copyright (c) 2016-2017 Dustin Doloff # Licensed under Apache License v2.0 load( "@bazel_toolbox//actions:actions.bzl", "generate_templated_file", ) load( "@bazel_toolbox//labels:labels.bzl", "executable_label", ) def _generate_deploy_site_zip_s3_script(ctx): ctx.actions.run( mnemonic = "GeneratingS3DeployScript", arguments = [ "--bucket", ctx.attr.bucket, "--cache-durations", ctx.attr.cache_durations, "--content-types", repr(ctx.attr.content_types), "--path-redirects", repr(ctx.attr.path_redirects), "--deployment-jinja-template", ctx.file._deploy_site_zip_to_s3_template.path, "--generated-file", ctx.outputs.generated_script.path, "--website-zip", ctx.file.zip.path, ], inputs = [ ctx.file.zip, ctx.file._deploy_site_zip_to_s3_template, ], tools = [ctx.executable._s3_website_deploy_script_builder], outputs = [ctx.outputs.generated_script], executable = ctx.executable._s3_website_deploy_script_builder, ) web_internal_generate_deploy_site_zip_s3_script = rule( attrs = { "bucket": attr.string( mandatory = True, ), "zip": attr.label( mandatory = True, allow_single_file = True, ), # Because this should never be called directly, we use string serialization to pass in the # cache values "cache_durations": attr.string(), "content_types": attr.string_dict(), "path_redirects": attr.string_dict( default = {}, ), "_deploy_site_zip_to_s3_template": attr.label( default = Label("//deploy/templates:deploy_site_zip_to_s3.py.jinja2"), executable = True, cfg = "host", allow_single_file = True, ), "_s3_website_deploy_script_builder": executable_label(Label("//deploy:s3_website_deploy_script_builder")), }, implementation = _generate_deploy_site_zip_s3_script, outputs = { "generated_script": "deploy_site_zip_s3_%{name}.py", }, ) def _generate_lambda_function_script(ctx): config = { "function_name": ctx.attr.function_name, "function_handler": ctx.attr.function_handler, "function_role": ctx.attr.function_role, "function_runtime": ctx.attr.function_runtime, "function_zip": ctx.file.bundle.short_path, } region = ctx.attr.region if region != "": config["region"] = region memory = ctx.attr.memory if memory != 0: if memory % 64 != 0: fail("Memory must be a multiple of 64 per Lambda's documentation", str(memory)) else: config["memory"] = memory timeout = ctx.attr.timeout if timeout != 0: if timeout <= 0: fail("Timeout must be positive", str(timeout)) else: config["timeout"] = timeout environment = ctx.attr.environment if environment != {}: config["environment"] = environment generate_templated_file( ctx = ctx, generate_templated_file_script = ctx.executable._generate_templated_file_script, template = ctx.file._deploy_lambda_function_template, config = config, out_file = ctx.outputs.generated_script, ) web_internal_generate_deploy_lambda_function_script = rule( attrs = { "function_name": attr.string( mandatory = True, ), "function_handler": attr.string( mandatory = True, ), "function_role": attr.string( mandatory = True, ), "function_runtime": attr.string( mandatory = True, values = [ "java8", "python27", ], ), "bundle": attr.label( mandatory = True, allow_single_file = True, providers = [ ["java"], ["py"], ], ), "region": attr.string(), "memory": attr.int(), "timeout": attr.int(), "environment": attr.string_dict(), "_deploy_lambda_function_template": attr.label( default = Label("//deploy/templates:deploy_lambda_function_template.py.jinja2"), allow_single_file = True, ), "_generate_templated_file_script": executable_label(Label("@bazel_toolbox//actions:generate_templated_file")), }, implementation = _generate_lambda_function_script, outputs = { "generated_script": "deploy_lambda_function_%{name}.py", }, ) def _generate_wrapper_script(ctx): label_to_target = {value: key for key, value in ctx.attr.label_replacements.items()} arguments = [] for arg in ctx.attr.arguments: arguments.push(label_to_target.get(arg, arg)) ctx.actions.run( mnemonic = "GeneratingWrapperScript", arguments = [ "--executable", ctx.file.binary.path, "--generated-file", ctx.outputs.generated_script.path, ] + ["--arguments"] + arguments, inputs = [ctx.file.binary], executable = ctx.executable._execute_script_wrapper_builder, outputs = [ctx.outputs.generated_script], ) web_internal_generate_wrapper_script = rule( attrs = { "binary": attr.label( executable = True, mandatory = True, cfg = "host", ), "arguments": attr.string_list( mandatory = True, ), "label_replacements": attr.label_keyed_string_dict( allow_files = True, ), "generated_script": attr.output(), "_execute_script_wrapper_builder": executable_label(Label("//deploy:execute_script_wrapper_builder")), }, implementation = _generate_wrapper_script, )
# Projeto: VemPython/exe009 # Autor: rafael # Data: 13/03/18 - 17:02 # Objetivo: TODO Faça um programa que leia um numero inteiro qualquer e mostre na tela a sua tabuada pr = int(input('Informe o valor da tabuada: ')) print('{} x 01 = {}\n' '{} x 02 = {}\n' '{} x 03 = {}\n' '{} x 04 = {}\n' '{} x 05 = {}\n' '{} x 06 = {}\n' '{} x 07 = {}\n' '{} x 08 = {}\n' '{} x 09 = {}\n' '{} x 10 = {}'.format(pr, pr*1, pr, pr*2, pr, pr*3, pr, pr*4, pr, pr*5, pr, pr*6, pr, pr*7, pr, pr*8, pr, pr*9, pr, pr*10))
__all__ = ['__version__', '__author__', '__email__'] __version__ = '1.0.1' __author__ = 'Axel Juraske' __email__ = '[email protected]'
""" #DEFUNCT TROPO TEST response.view="generic.json" def index(): return( dict( tropo=[{"say":{"value":"Welcome to the Biddrive dot com call center. Testing pronunciation. Hello Neal, Paul, Zaki, Barret, Rob, Christy, and Himel."}}] ) ) def result(): return( dict( tropo=[{"hangup":{"value":"Goodbye."}}] ) ) """ def index(): resp = twiml.Response() skip_message = request.vars['skip_message'] message = request.vars['message'] intro = "Hello! Welcome to the bid drive dot com automatic auction validation system." gather = "Please %sdial your 12 digit winner code now."% ('re' if bool(message or skip_message) else '',) if not skip_message: resp.say(message or intro) with resp.gather(numDigits=12, action="handle_key.xml", method="POST") as g: #with is like try finally that automatically closes the file via calling __exit__() for each in range(3): g.say(gather) #g is gather obj g.pause(length=3) return( dict( resp=str(resp) #XML() MOVED TO VIEW #By default web2py escapes string characters passed to view, use XML function to preserve escapable characters (ex < > & etc.) ) ) def handle_key(): """Handle key press from a user.""" # Get the digit pressed by the user digit_pressed = request.post_vars['Digits'] if len(digit_pressed) == 12: resp = twiml.Response() # Dial (310) 555-1212 - connect that number to the incoming caller. #resp.dial("+13105551212") # If the dial fails: with resp.gather(numDigits=1, action="handle_key_check.xml/%s"%digit_pressed, method="POST") as g: #change to csv so operator can say each number separate for each in range(3): g.say("You dialed %s. If this is correct, press 1. Otherwise, press 2 and try again."%(str(list(digit_pressed)).strip('[').strip(']'),)) g.pause(length=3) return dict(resp = str(resp)) # If the caller pressed anything but 1, redirect them to the homepage. redirect(URL('init', 'voice', 'index.xml', vars=dict(message="I'm sorry. It seems you incorrectly dialed your winner code."))) def handle_key_check(): digit_pressed = request.post_vars['Digits'] winner_code = request.args(0) if digit_pressed == '1': resp = twiml.Response() winner_code_exists = db(db.auction_request_winning_offer.winner_code.contains(winner_code)).select().last() #http://goo.gl/GwI1xN if winner_code_exists: winning_offer = db(db.auction_request_offer.id == winner_code_exists.auction_request_offer).select().last() winning_dealer = db(db.dealership_info.owner_id == winning_offer.owner_id).select().last() #time stuff# see if dealer is open now at his location's time. if not open, say schedule today_datetime_for_dealer = datetime.datetime.now(timezone(winning_dealer.time_zone)) weekday_for_dealer = today_datetime_for_dealer.strftime("%A").lower() #extract day of the week #http://goo.gl/dopxlP def twelve_to_24hr(time, am_pm): hour, minute = map(lambda t: int(t),time.split(':')) if am_pm == "AM" and hour == 12: #convert from 12hr to 24hr time. Here 12AM should be 0hr, every other AM is fine hour = 0 elif am_pm == "PM" and hour != 12: #leave 12PM alone, as it is also 12 in 24hr time. Every other PM add 12 to it. Ex. 1PM = 13hr hour+=12 return hour, minute opening_time=winning_dealer['%s_opening_time'%weekday_for_dealer] closing_time=winning_dealer['%s_closing_time'%weekday_for_dealer] is_business_day = closing_time and opening_time #means it has, is, or was open this day is_open_now = True if is_business_day: #if one if false it's closed opening_hour, opening_minute = twelve_to_24hr(*opening_time.split(' ')) #Get schedule for the day of the week at dealer's location. Returns something like ['12:30', 'AM'] for Monday or whatever day it is for dealer... note it could be Tuesday on server's time, but still Monday on dealer's time closing_hour, closing_minute = twelve_to_24hr(*closing_time.split(' ')) #Get schedule for the day of the week at dealer's location. Returns something like ['12:30', 'AM'] for Monday or whatever day it is for dealer... note it could be Tuesday on server's time, but still Monday on dealer's time opening_datetime_for_dealer = today_datetime_for_dealer.replace(hour=opening_hour, minute=opening_minute) closing_datetime_for_dealer = today_datetime_for_dealer.replace(hour=closing_hour, minute=closing_minute) if today_datetime_for_dealer < opening_datetime_for_dealer or closing_datetime_for_dealer < today_datetime_for_dealer: is_open_now = False else: is_open_now = False if not is_open_now: #means they're closed tz_country, tz_zone = winning_dealer.time_zone.split('/') schedule = '' for each_day in days_of_the_week: opening_time = winning_dealer['%s_opening_time'%each_day] closing_time = winning_dealer['%s_closing_time'%each_day] if opening_time and closing_time: schedule+=" %s, %s through %s."%(each_day, opening_time, closing_time) for each in range(3): resp.say("I'm sorry. Your winning dealer is not accepting calls at this time. Please call back at the following days, %s %s time.%s Thank you and have a great day. "%(tz_country, tz_zone, schedule) ) resp.pause(length=3) else: #make vehicle details to pass to dealer and CALL the dealer resp.say("Thank you. I will now connect you to your winning dealer. Please hold for up to 5 minutes.") auction_request = db(db.auction_request.id == winning_offer.auction_request).select().last() color_simple_names = dict(zip(auction_request.colors, auction_request.color_simple_names)) #dict(map(lambda id,name: [id,name], auction_request.colors, auction_request.color_simple_names)) auction_request_vehicle = dict(_color = color_simple_names[winning_offer.exterior_color], _year = auction_request.year, _make = auction_request.make, _model = auction_request.model, _id=auction_request.id) #trim = auction_request.trim_name) winning_dealer_phone_number = "+"+''.join(winning_dealer.phone.split("-"))#http://goo.gl/JhE2V screen_for_machine_url = URL("screen_for_machine.xml", args=[winning_offer.id, winner_code], vars = auction_request_vehicle, scheme=True, host=True)#.split('/')[-1] #url MUST BE absolute, action can be absolute or relative! dialer = resp.dial(callerId = TWILIO_NUMBER_CALLER_ID) #convert init/voice/screen_for_machine.xml?model=... into screen_for_machine.xml?model=... dialer.append(twiml.Number(winning_dealer_phone_number, url = screen_for_machine_url, method="POST")) #allows for interaction (ie. gather) with dealer before he enters the call.. must hang up explicitly if unresponsive or call will connect #TODO figure out a way to play music while ringing #dialer.append(twiml.Conference(winner_code, waitUrl=URL('static','audio/on_hold_music.mp3', scheme=True, host=True) ) ) #room name is first argument resp.say("The call failed, or the remote party hung up. Goodbye.") return dict(resp = str(resp)) else: redirect(URL('init', 'voice', 'index.xml', vars=dict(message="I'm sorry. That code doesn't exist in our database."))) # If the caller pressed 2 or some other key redirect(URL('init', 'voice', 'index.xml', vars=dict(skip_message=True))) def screen_for_machine(): resp = twiml.Response() winning_offer_id = request.args(0) winner_code = request.args(1) if set(['_color', '_year', '_make', '_model', '_id']).issubset(request.vars): #test is list values in list w/o comprehensions #http://goo.gl/mxqfX1 #this will NOT run on self redirect because vehicle vars will not be in url, thus it can proceed to db insertion message = "This is the bid drive dot com automatic auction validation system. Press any key to skip the following message. Congratulations! You are the winning bidder of auction number {_id}, for a {_color} {_year} {_make} {_model}. The buyer initiated this call and is waiting on the line. Please press any key to connect to the buyer now. ".format(**request.vars) hmac_url = URL('voice', 'screen_for_machine.xml', args=[winning_offer_id, winner_code, "screen_complete"], hmac_key=str(winning_offer_id), salt = str(winner_code) ) #need some kinda random number to ensure winner_code is safe... since there is no session to store a uuid, the winner_code is random and private enough with resp.gather(numDigits=1, action=hmac_url, method="POST") as g: #if he pressed something go to a new function. #action would be screen_for_machine.xml/screen_complete for each in range(3): g.say(message) g.pause(length=3) if "screen_complete" in request.args and URL.verify(request, hmac_key=winning_offer_id, salt = winner_code): #HMAC PROTECT HERE!! Can do it manually too http://goo.gl/SLXU3d winning_offer = db(db.auction_request_winning_offer.auction_request_offer == winning_offer_id).select().last() contact_made = winning_offer.update_record(contact_made=True) #collect money winners_piggy = db(db.credits.owner_id==winning_offer.owner_id).select().last() winners_piggy.update_record( credits = winners_piggy.credits - CREDITS_PER_SUCCESS) #remove one credit db.credits_history.insert(change= -CREDITS_PER_SUCCESS, owner_id=winning_offer.owner_id, reason="Success fee", modified_by=winning_offer.owner_id) resp.say("Connecting. ") else: resp.say("Goodbye. ") #IF POUND PRESSED ACTION WILL NOT BE CALLED! resp.hangup() #hang up if no gather return dict(resp=str(resp)) """ def screen_complete(): #IF POOR VOIP PHONE IS BEING CALLED, THE KEY PRESS WILL NOT BE REGISTERED AND THIS ACTION WILL NOT BE CALLED!!! TWILIO PROBABLY REGISTERS IT AS A # PRESS!!! #no need to test gather as any key is good winning_offer_id = request.args(0) winning_offer = db(db.auction_request_offer.id == winning_offer_id).select().last() contact_made = winning_offer.update_record(contact_made=True) resp = twiml.Response() resp.say("Connecting. ") return dict(resp=str(resp)) """
# Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e # mostre quantos Dólares ele pode comprar. reais = float(input('Quantos reais (R$) você tem? ')) print('US$1.00 = R$ 5,67 | 26/12/2021') conv = reais/5.67 print('Você pode comprar US${:.2f} com R${}'.format(conv, reais))
CFNoQuitButton=256 CFPageButton=16 CFQuicktalker=4 CFQuitButton=32 CFReversed=64 CFSndOpenchat=128 CFSpeech=1 CFThought=2 CFTimeout=8 CCNormal = 0 CCNonPlayer = 1 CCSuit = 2 CCToonBuilding = 3 CCSuitBuilding = 4 CCHouseBuilding = 5 CCSpeedChat = 6 NAMETAG_COLORS = { CCNormal: ( # Normal FG BG ((0.3, 0.3, 0.7, 1.0), (0.8, 0.8, 0.8, 0.5), # Name (0.0, 0.0, 0.0, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat # Click FG BG ((0.3, 0.3, 0.7, 1.0), (0.2, 0.2, 0.2, 0.6), # Name (1.0, 0.5, 0.5, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat # Hover FG BG ((0.5, 0.5, 1.0, 1.0), (1.0, 1.0, 1.0, 1.0), # Name (0.0, 0.6, 0.6, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat # Disable FG BG ((0.3, 0.3, 0.7, 1.0), (0.8, 0.8, 0.8, 0.5), # Name (0.0, 0.0, 0.0, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat ), CCNonPlayer: ( # Normal FG BG ((0.8, 0.4, 0.0, 1.0), (0.8, 0.8, 0.8, 0.5), # Name (0.0, 0.0, 0.0, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat # Click FG BG ((0.8, 0.4, 0.0, 1.0), (0.8, 0.8, 0.8, 0.5), # Name (0.0, 0.0, 0.0, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat # Hover FG BG ((0.8, 0.4, 0.0, 1.0), (0.8, 0.8, 0.8, 0.5), # Name (0.0, 0.0, 0.0, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat # Disable FG BG ((0.8, 0.4, 0.0, 1.0), (0.8, 0.8, 0.8, 0.5), # Name (0.0, 0.0, 0.0, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat ), CCSuit: ( # Normal FG BG ((0.2, 0.2, 0.2, 1.0), (0.8, 0.8, 0.8, 0.5), # Name (0.0, 0.0, 0.0, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat # Click FG BG ((0.2, 0.2, 0.2, 1.0), (0.2, 0.2, 0.2, 0.6), # Name (1.0, 0.5, 0.5, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat # Hover FG BG ((0.4, 0.4, 0.4, 1.0), (1.0, 1.0, 1.0, 0.7), # Name (0.0, 0.6, 0.6, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat # Disable FG BG ((0.2, 0.2, 0.2, 1.0), (0.8, 0.8, 0.8, 0.5), # Name (0.0, 0.0, 0.0, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat ), CCSuitBuilding: ( # Normal FG BG ((0.5, 0.5, 0.5, 1.0), (0.8, 0.8, 0.8, 0.5), # Name (0.0, 0.0, 0.0, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat # Click FG BG ((0.5, 0.5, 0.5, 1.0), (0.2, 0.2, 0.2, 0.6), # Name (1.0, 0.5, 0.5, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat # Hover FG BG ((0.7, 0.7, 0.7, 1.0), (1.0, 1.0, 1.0, 0.7), # Name (0.0, 0.6, 0.6, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat # Disable FG BG ((0.5, 0.5, 0.5, 1.0), (0.8, 0.8, 0.8, 0.5), # Name (0.0, 0.0, 0.0, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat ), CCToonBuilding: ( # Normal FG BG ((0.2, 0.6, 0.9, 1.0), (0.8, 0.8, 0.8, 0.5), # Name (0.0, 0.0, 0.0, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat # Click FG BG ((0.2, 0.6, 0.9, 1.0), (0.8, 0.8, 0.8, 0.5), # Name (0.0, 0.0, 0.0, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat # Hover FG BG ((0.2, 0.6, 0.9, 1.0), (0.8, 0.8, 0.8, 0.5), # Name (0.0, 0.0, 0.0, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat # Disable FG BG ((0.2, 0.6, 0.9, 1.0), (0.8, 0.8, 0.8, 0.5), # Name (0.0, 0.0, 0.0, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat ), CCHouseBuilding: ( # Normal FG BG ((0.2, 0.6, 0.9, 1.0), (0.8, 0.8, 0.8, 0.5), # Name (0.0, 0.0, 0.0, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat # Click FG BG ((0.2, 0.2, 0.5, 1.0), (0.2, 0.2, 0.2, 0.6), # Name (1.0, 0.5, 0.5, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat # Hover FG BG ((0.5, 0.5, 1.0, 1.0), (1.0, 1.0, 1.0, 1.0), # Name (0.0, 0.6, 0.6, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat # Disable FG BG ((0.0, 0.6, 0.2, 1.0), (0.8, 0.8, 0.8, 0.5), # Name (0.0, 0.0, 0.0, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat ), CCSpeedChat: ( # Normal FG BG ((0.0, 0.6, 0.2, 1.0), (0.8, 0.8, 0.8, 0.5), # Name (0.0, 0.0, 0.0, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat # Click FG BG ((0.0, 0.5, 0.0, 1.0), (0.5, 0.5, 0.5, 0.6), # Name (1.0, 0.5, 0.5, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat # Hover FG BG ((0.0, 0.7, 0.2, 1.0), (1.0, 1.0, 1.0, 0.7), # Name (0.0, 0.6, 0.6, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat # Disable FG BG ((0.0, 0.6, 0.2, 1.0), (0.8, 0.8, 0.8, 0.5), # Name (0.0, 0.0, 0.0, 1.0), (1.0, 1.0, 1.0, 1.0)), # Chat ) } ARROW_COLORS = { CCSuit: (0.8, 0.4, 0.0, 1.0), } DEFAULT_WORDWRAPS = { CCNormal: 7.5, CCNonPlayer: 7.5, CCSuit: 7.5, CCToonBuilding: 8.5, CCSuitBuilding: 8.5, CCHouseBuilding: 10.0, CCSpeedChat: 7.5 } WTNormal = 0 WTQuickTalker = 1 WTSystem = 2 WTBattleSOS = 3 WTEmote = 4 WTToontownBoardingGroup = 5 WHISPER_COLORS = { WTNormal: ( # Normal FG BG ((0.0, 0.0, 0.0, 1.0), (0.2, 0.6, 0.8, 0.6)), # Click FG BG ((1.0, 0.5, 0.5, 1.0), (1.0, 1.0, 1.0, 0.8)), # Hover FG BG ((0.0, 0.0, 0.0, 1.0), (0.2, 0.7, 0.9, 0.6)), # Disable FG BG ((0.0, 0.0, 0.0, 1.0), (0.2, 0.7, 0.8, 0.6)) ), WTQuickTalker: ( # Normal FG BG ((0.0, 0.0, 0.0, 1.0), (0.2, 0.6, 0.8, 0.6)), # Click FG BG ((1.0, 0.5, 0.5, 1.0), (1.0, 1.0, 1.0, 0.8)), # Hover FG BG ((0.0, 0.0, 0.0, 1.0), (0.2, 0.7, 0.9, 0.6)), # Disable FG BG ((0.0, 0.0, 0.0, 1.0), (0.2, 0.7, 0.8, 0.6)) ), WTSystem: ( # Normal FG BG ((0.0, 0.0, 0.0, 1.0), (0.8, 0.3, 0.6, 0.6)), # Click FG BG ((1.0, 0.5, 0.5, 1.0), (1.0, 1.0, 1.0, 0.8)), # Hover FG BG ((0.0, 0.0, 0.0, 1.0), (0.8, 0.4, 1.0, 0.6)), # Disable FG BG ((0.0, 0.0, 0.0, 1.0), (0.8, 0.3, 0.6, 0.6)) ), WTBattleSOS: ( # Normal FG BG ((0.0, 0.0, 0.0, 1.0), (0.8, 0.3, 0.6, 0.6)), # Click FG BG ((1.0, 0.5, 0.5, 1.0), (1.0, 1.0, 1.0, 0.8)), # Hover FG BG ((0.0, 0.0, 0.0, 1.0), (0.8, 0.4, 0.0, 0.8)), # Disable FG BG ((0.0, 0.0, 0.0, 1.0), (0.8, 0.3, 0.6, 0.6)) ), WTEmote: ( # Normal FG BG ((0.0, 0.0, 0.0, 1.0), (0.9, 0.5, 0.1, 0.6)), # Click FG BG ((1.0, 0.5, 0.5, 1.0), (1.0, 1.0, 1.0, 0.8)), # Hover FG BG ((0.0, 0.0, 0.0, 1.0), (0.9, 0.6, 0.2, 0.6)), # Disable FG BG ((0.0, 0.0, 0.0, 1.0), (0.9, 0.6, 0.1, 0.6)) ), WTToontownBoardingGroup: ( # Normal FG BG ((0.0, 0.0, 0.0, 1.0), (0.9, 0.5, 0.1, 0.6)), # Click FG BG ((1.0, 0.5, 0.5, 1.0), (1.0, 1.0, 1.0, 0.8)), # Hover FG BG ((0.0, 0.0, 0.0, 1.0), (0.9, 0.6, 0.2, 0.6)), # Disable FG BG ((0.0, 0.0, 0.0, 1.0), (0.9, 0.6, 0.1, 0.6)) ) } def getFriendColor(handle): return CCNormal if base.localAvatar.isTrueFriends(handle.doId) else CCSpeedChat
""" File: largest_digit.py Name: ---------------------------------- This file recursively prints the biggest digit in 5 different integers, 12345, 281, 6, -111, -9453 If your implementation is correct, you should see 5, 8, 6, 1, 9 on Console. """ def main(): print(find_largest_digit(12345)) # 5 print(find_largest_digit(281)) # 8 print(find_largest_digit(6)) # 6 print(find_largest_digit(-111)) # 1 print(find_largest_digit(-9453)) # 9 def find_largest_digit(n): """ :param n: :return: the largest digit. """ if n < 0: n *= -1 n_mode = n % 10 return find_largest_digit_help(n, n_mode) def find_largest_digit_help(n, n_max): """ The function will return the largest digit. """ # Set the stopping rule of the recursion algorithm. if n < 10: return n_max n = n // 10 if n > 0: # Explore n_mode = n % 10 if n_mode > n_max: n_max = n_mode # Explore max_ = find_largest_digit_help(n, n_max) return max_ if __name__ == '__main__': main()
def main(): n,k = map(int,input().split()) answer = [1 for _ in range(n)] for _ in range(k): d = int(input()) a = list(map(int,input().split())) for i in range(d): answer[a[i]-1] = 0 print(sum(answer)) if __name__ == "__main__": main()
# ex:ts=4:sw=4:sts=4:et # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- # # Copyright (C) 2006 - 2007 Michael 'Mickey' Lauer # Copyright (C) 2006 - 2007 Richard Purdie # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. class BBUIHelper: def __init__(self): self.needUpdate = False self.running_tasks = {} self.failed_tasks = [] def eventHandler(self, event): if isinstance(event, bb.build.TaskStarted): self.running_tasks[event.pid] = { 'title' : "%s %s" % (event._package, event._task) } self.needUpdate = True if isinstance(event, bb.build.TaskSucceeded): del self.running_tasks[event.pid] self.needUpdate = True if isinstance(event, bb.build.TaskFailed): del self.running_tasks[event.pid] self.failed_tasks.append( { 'title' : "%s %s" % (event._package, event._task)}) self.needUpdate = True # Add runqueue event handling #if isinstance(event, bb.runqueue.runQueueTaskCompleted): # a = 1 #if isinstance(event, bb.runqueue.runQueueTaskStarted): # a = 1 #if isinstance(event, bb.runqueue.runQueueTaskFailed): # a = 1 #if isinstance(event, bb.runqueue.runQueueExitWait): # a = 1 def getTasks(self): self.needUpdate = False return (self.running_tasks, self.failed_tasks)
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} head # @param {integer} val # @return {ListNode} def removeElements(self, head, val): node = head last = None new_head = head while node: if node.val != val: if last: last.next = node last = node else: last = node new_head = node node = node.next if last: last.next = None else: new_head = None return new_head
'''https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ 105. Construct Binary Tree from Preorder and Inorder Traversal Medium 6751 171 Add to List Share Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree. Example 1: Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] Output: [3,9,20,null,null,15,7] Example 2: Input: preorder = [-1], inorder = [-1] Output: [-1] Constraints: 1 <= preorder.length <= 3000 inorder.length == preorder.length -3000 <= preorder[i], inorder[i] <= 3000 preorder and inorder consist of unique values. Each value of inorder also appears in preorder. preorder is guaranteed to be the preorder traversal of the tree. inorder is guaranteed to be the inorder traversal of the tree.''' # # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: if inorder: ind = inorder.index(preorder.pop(0)) root = TreeNode(inorder[ind]) root.left = self.buildTree(preorder, inorder[0:ind]) root.right = self.buildTree(preorder, inorder[ind+1:]) return root
template = { 'template_type': 'attachment', 'value': { 'attachment': { 'type': 'file', 'payload': { 'url': '' } } } } class AttachmentTemplate: def __init__(self, url='', type='file'): self.template = template['value'] self.url = url self.type = type def set_url(self, url=''): self.url = url def set_type(self, type=''): # image / audio / video / file self.type = type def get_message(self): self.template['attachment']['payload']['url'] = self.url self.template['attachment']['type'] = self.type return self.template
"""This problem was asked by Microsoft. Given a string and a pattern, find the starting indices of all occurrences of the pattern in the string. For example, given the string "abracadabra" and the pattern "abr", you should return [0, 7]. """
class _Regex: def __init__(self, s: str): self.s = s def __eq__(self, x): if self.s == None and x.s == None: return True if self.s == None: return False if x.s == None: return False return self.s == x.s def __add__(self, x): if x == empty_set: return self if self == empty_set: return x return self.__class__("(" + self.s + "+" + x.s + ")") def __radd__(self, x): if x == empty_set: return self if self == empty_set: return x return self.__class__("(" + x.s + "+" + self.s + ")") def __mul__(self, x): if x == empty_set or self == empty_set: return empty_set return self.__class__("(" + self.s + x.s + ")") def __rmul__self(self, x): if x == empty_set or self == empty_set: return empty_set return self.__class__("(" + self.s + x.s + ")") def __str__(self): if self.s == None: return "empty_set" return self.s def rep(self): if self.s == None: return None return self.__class__("("+self.s+")*") empty_set = _Regex(None)
#!/usr/bin/env python # -*- encoding: utf-8 -*- __author__ = 'andyguo' DAYU_DB_ROOT_FOLDER_NAME = '.!0x5f3759df_this_is_a_magic_number_used_for_telling_which_atom_is_the_root' DAYU_DB_NAME = 'DAYU_DB_NAME' DAYU_APP_NAME = 'DAYU_APP_NAME' DAYU_CONFIG_STATIC_PATH = 'DAYU_CONFIG_STATIC_PATH'
a=10 #Normal initialization of object to variable a def global_var(): global a #declaring that a variable as a global variable here to access or use that a here a=a+1 # calculation print(a) global_var() #calling the function """ output become 11 """ """ Global variables for Nested functions """ def func_out(): x=10 def func_in(): global x x=20 print(x) func_in() """ output 20 Because here we already declare x=10 to func_out() so there is no need to make that x as global in func_in(). """ #globals() t= 100 def func(): list_of_items = globals() list_of_items["t"] = 15 t = 22 print("Local value of t is:", t) print("The value of t is:", t) func() print("Change in the value of t is:", t)
""" `minion-ci` is a minimalist, decentralized, flexible Continuous Integration Server for hackers. This module contains the exceptions specific to `minion` errors. :copyright: (c) by Timo Furrer :license: MIT, see LICENSE for details """ class MinionError(Exception): """Exception which is raised for minion specific errors.""" pass class MinionMongoError(Exception): """Exception raised for minion specific errors related to mongodb""" pass
def tag_bloco(conteudo, classe='sucesso', inline=False): tag = 'span' if inline else 'div' return f'<{tag} class="{classe}">{conteudo}</{tag}>' def tag_lista(*itens): lista = ''.join(f'<li>{item}</li>' for item in itens) return f'<ul>{lista}</ul>' if __name__ == '__main__': print(tag_bloco('TEXTO VAI AQUI', classe='text', inline=True)) print(tag_bloco('TEXTO VAI AQUI')) print(tag_bloco(tag_lista('Item 1', 'Item 2'), classe='info'))
""" FDS Assignment 2 Group A Name: Shamik S Ghadge Roll no.: SECOA159 Problem Statement: Write a Python program to store marks scored in subject “Fundamental of Data Structure” by N students in the class. Write functions to compute following: a) The average score of class b) Highest score and lowest score of class c) Count of students who were absent for the test d) Display mark with highest frequency """ def calc_average(marks): """ Function which returns the average of the total score of the students. """ add = 0 for mark in marks: add = add + mark total = len(marks) avg = add / total return avg def calc_max_min_marks(marks): """ Function which returns the minimum(excluding 0) and maximum score of the class in the form of a list. """ result = [] marks.sort() min_max = [] min_max[:] = (value for value in marks if value != 0) least_score = min_max[0] highest_score = min_max[-1] result.append(least_score) result.append(highest_score) return result def calc_absent(marks): """ Function which returns the count of absent students. """ absent_count = 0 for mark in marks: if mark == 0: absent_count += 1 return absent_count def calc_highest_frequency(marks): """ Function which returns the score with the highest frequency in the list. """ highest_frequency_mark = 0 marks.sort() frequency = [] cnt = 0 while cnt < len(marks): frequency.append(marks.count(marks[cnt])) cnt += 1 frequency_dict = dict(zip(marks, frequency)) max_value = max(frequency_dict.values()) for mark, value in frequency_dict.items(): if value == max_value: highest_frequency_mark = mark return highest_frequency_mark # The score of all students marks_list = [95, 85, 99, 88, 87, 70, 99, 88, 85, 87, 90, 95, 96, 0, 91, 0, 92, 0, 0, 0, 99, 98, 99, 97, 99, 90, 99] # Calling all the functions. average_marks = calc_average(marks_list) min_marks = calc_max_min_marks(marks_list)[0] max_marks = calc_max_min_marks(marks_list)[1] absent = calc_absent(marks_list) most_frequency_score = calc_highest_frequency(marks_list) # Printing all the values print(average_marks) print(min_marks) print(max_marks) print(absent) print(most_frequency_score)
lista = [1, 10] arquivo = open('teste.txt', 'r') try: texto = arquivo.read() divisao = 10 / 1 numero = lista[1] except ZeroDivisionError: print('Não é possivel realizar a divisão por 0') except ArithmeticError: print('Houve um erro ao realizar uma operação aritimetica.') except IndexError: print('Erro ao acessar um indice invalido da lista.') except BaseException as ex: print('Erro desconhecido. Erro {}'.format(ex)) else: print('Executa quando não ocorre exceção.') finally: print('Sempre executa.') print('Fechando arquivo.') arquivo.close()
# Errors from Identity Provider translates into these errors codes # as an internal abstraction over OpenID Connect errors. OIDC_ERROR_CODES = { 'E0': 'Unknown error from Identity Provider', 'E1': 'User interrupted', 'E3': 'User failed to verify SSN', 'E4': 'User declined terms', # Happens if an internal error happens at our side 'E500': 'Internal Server Error', # Directly translated from Identity Provider's error code. # Happens if an internal error occurs at their side. 'E501': 'Internal Server Error at Identity Provider', # Generic error (fallback error code). # Happens if we could not recognize error from Identity Provider. 'E502': 'Internal Server Error at Identity Provider', # Happens if, for instance, we Identity Provider is offline, # and we could not fetch a token etc. 'E505': 'Failed to communicate with Identity Provider', } # /callback?error_code=E501&error=Internal Serviver
# bubble sort # https://www.w3resource.com/python-exercises/data-structures-and-algorithms/python-search-and-sorting-exercise-4.php # # 时间复杂度: 最优时间复杂度O(n) 当遍历一次的时候发现没有任何元素交换,说明已经是按大小有序的,排序结束 # 最坏时间复杂度O(n^2) # 平均时间复杂度O(n^2) # 稳定性:稳定 # 不需要额外空间 def bubble_sort(alist): """ :param alist: :return: """ length = len(alist) n = 0 n2 = 0 for i in range(length): for j in range(i): n += 1 if alist[j] > alist[i]: n2 += 1 alist[i], alist[j] = alist[j], alist[i] return alist, n, n2 def bubble_sort_2(alist): length = len(alist) n = 0 n2 = 0 for i in range(length): for j in range(i + 1, length): n += 1 if alist[i] > alist[j]: n2 += 1 alist[i], alist[j] = alist[j], alist[i] return alist, n, n2 def bubble_sort_3(alist): length = len(alist) n = 0 n2 = 0 for i in range(length - 1, 0, -1): for j in range(i): n += 1 if alist[j] > alist[j + 1]: n2 += 1 alist[j], alist[j + 1] = alist[j + 1], alist[j] return alist, n, n2 def short_bubble_sort(alist): exchange = True length = len(alist) - 1 while length > 0 and exchange: exchange = False for i in range(length): if alist[i] > alist[i + 1]: exchange = True alist[i], alist[i + 1] = alist[i + 1], alist[i] length = length - 1 return alist # test print(bubble_sort([3, 5, 6, 2, 1, 3, 1, 7, 12])) print(bubble_sort([8, 4, 1, 8, 4, 9, 3, 2])) print(bubble_sort([6, 5, 4, 3, 2])) print(bubble_sort_2([3, 5, 6, 2, 1, 3, 1, 7, 12])) print(bubble_sort_2([8, 4, 1, 8, 4, 9, 3, 2])) print(bubble_sort_2([6, 5, 4, 3, 2])) print(bubble_sort_3([3, 5, 6, 2, 1, 3, 1, 7, 12])) print(bubble_sort_3([8, 4, 1, 8, 4, 9, 3, 2])) print(bubble_sort_3([6, 5, 4, 3, 2]))
z=10 w=-10 while(z<50): if (z>0 and w<0): print(z**2, w**3) z = z+10 w=w+10 # 100 -1000
""" Krema part for Perms, Types, Intents etc... """ class ChannelTypes: """All Channel types in this class.""" GUILD_TEXT: int = 0 # a text channel within a server DM: int = 1 # a direct message between users GUILD_VOICE: int = 2 # a voice channel within a server GROUP_DM: int = 3 # a direct message between multiple users GUILD_CATEGORY: int = 4 # an organizational category that contains up to 50 channels GUILD_NEWS: int = 5 # a channel that users can follow and crosspost into their own server GUILD_STORE: int = 6 # a channel in which game developers can sell their game on Discord GUILD_NEWS_THREAD: int = 10 # a temporary sub-channel within a GUILD_NEWS channel GUILD_PUBLIC_THREAD: int = 11 # a temporary sub-channel within a GUILD_TEXT channel # a temporary sub-channel within a GUILD_TEXT channel that is only viewable by those invited and those with the MANAGE_THREADS permission GUILD_PRIVATE_THREAD: int = 12 GUILD_STAGE_VOICE: int = 13 # a voice channel for hosting events with an audience class Intents: """Intent constants.""" GUILDS: int = 1 << 0 GUILD_MEMBERS: int = 1 << 1 GUILD_BANS: int = 1 << 2 GUILD_EMOJIS_AND_STICKERS: int = 1 << 3 GUILD_INTEGRATIONS: int = 1 << 4 GUILD_WEBHOOKS: int = 1 << 5 GUILD_INVITES: int = 1 << 6 GUILD_VOICE_STATES: int = 1 << 7 GUILD_PRESENCES: int = 1 << 8 GUILD_MESSAGES: int = 1 << 9 GUILD_MESSAGE_REACTIONS: int = 1 << 10 GUILD_MESSAGE_TYPING: int = 1 << 11 DIRECT_MESSAGES: int = 1 << 12 DIRECT_MESSAGE_REACTIONS: int = 1 << 13 DIRECT_MESSAGE_TYPING: int = 1 << 14 def All(self): attrs = [i for i in dir(self) if not i.startswith("__") and i != "All"] result = sum(int(getattr(self, i)) for i in attrs) return result
def downheap(i, size): while 2 * i <= size: k = 2 * i if k < size and a[k] < a[k + 1]: k += 1 if a[i] >= a[k]: break a[i], a[k] = a[k], a[i] i = k def create_heap(a): hsize = len(a) - 1 for i in reversed(range(1, hsize // 2 + 1)): downheap(i, hsize) def heap_sort(a): N = len(a) - 1 for i in range(N): a[1], a[N] = a[N], a[1] downheap(1, N - 1) N -= 1 a = [1, 2, 1, 3, 2, 4, 3, 5, 3, 6, 4, 7, 5, 8, 5, 9, 6, 10, 6, 11, 7, 12, 11, 13] create_heap(a) heap_sort(a) print(a)
x = int(input('Digite primeiro numero: ')) y = int(input('Digite segundo numero: ')) if x > y : print('Primeiro numero e maior que o segundo!!!!') elif x == y : print('Os dois numeros sao iguais!!!!') else: print('Segundo numero e maior que o primeiro!!!!')
# # @lc app=leetcode id=47 lang=python3 # # [47] Permutations II # # @lc code=start class Solution: def permuteUnique(self, nums: List[int]) -> List[List[int]]: if len(nums) == 1: return [nums] last_num = nums[-1] pre_nums = nums[:-1] permutations = [] pre_permutations = self.permuteUnique(pre_nums) # backtracking for p in pre_permutations: for i in range(len(p)): temp = p.copy() temp.insert(i, last_num) if temp not in permutations: # only add unique permutations permutations.append(temp) temp = p + [last_num] if temp not in permutations: # only add unique permutations permutations.append(temp) return permutations # @lc code=end # Accepted # 30/30 cases passed(100 ms) # Your runtime beats 30.49 % of python3 submissions # Your memory usage beats 8.89 % of python3 submissions(13.9 MB)
#!/usr/bin/python3 # -*- coding: utf-8 -*- dosya=open("lagrange.txt") degerler = [] for line in dosya.readlines(): line = line.rstrip('\n').split(' ') degerler.append(line) dosya.close() x = int(input("hangi değerin hesaplanmasını istiyorsunuz: ")) boyut = len(line) boyut2 = len(degerler) sonuc,sonuc1, genelsonuc= 1,1,0 for m in range(boyut2): for i in range(boyut): degerler[m][i] = int(degerler[m][i]) for xi in range(boyut): for n in range(boyut): if n==xi: continue else: sonuc1 = (x - degerler[0][n]) / (degerler[0][xi]-degerler[0][n]) sonuc = sonuc * sonuc1 sonuc = sonuc * degerler[1][xi] genelsonuc = genelsonuc + sonuc sonuc=1 print(genelsonuc)
# Project Euler Problem 0001 # Multiples of 3 and 5 # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. # NOTES: # - natural numbers: -2, -1, 0, 1, 2, ... # Answer: 233168 lower_limit = 0 upper_limit = 1000 x = list(range(lower_limit, upper_limit, 1)) # create list of natural numbers, [lower_limit, upper_limit) y = 0 # define variable to store sum of multiples # print(x) for el in x: if (el % 3 == 0) | (el % 5 == 0): y += el # print(el, y) print(y)
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def insert(root, x): if x < root.val: if root.left is None: root.left = TreeNode(x) else: insert(root.left, x) elif x > root.val: if root.right is None: root.right = TreeNode(x) else: insert(root.right, x) else: return root def inOrderTraversal(root): if root.left: inOrderTraversal(root.left) print(root.val, end=" ") if root.right: inOrderTraversal(root.right) def closestValue(root, target): return closestValueHelper(root, target, float('inf')) def closestValueHelper(root, target, closest): if root is None: return closest if abs(target - closest) > abs(target - root.val): closest = root.val if target < root.val: return closestValueHelper(root.left, target, closest) elif target > root.val: return closestValueHelper(root.right, target, closest) else: return closest def closestValueIter(root, target): curr = root closest = float('inf') while curr is not None: if abs(target - closest) > abs(target - curr.val): closest = curr.val if target < curr.val: curr = curr.left else: curr = curr.right return closest tree = TreeNode(10) insert(tree, 5) insert(tree, 15) insert(tree, 2) insert(tree, 5) insert(tree, 1) insert(tree, 13) insert(tree, 22) insert(tree, 14) inOrderTraversal(tree) print() print(closestValue(tree, 13.7)) # print(closestValueIter(tree, 13.7))
# -*- coding: utf-8 -*- """ mudicom.exceptions ~~~~~~~~~~~~~~~~~~ Module for package specific exceptions """ class InvalidDicom(IOError): """ A DICOM file must have the correct tag to be validated as a DICOM file. Read the DICOM standard for more information. """ pass
""" Exemplo de um módulo python. Contém uma variável chamada minha_variavel, uma função chamada minha_funcao e uma classe chamada MinhaClasse. """ minha_variavel = 0 def minha_funcao(): """ Função examplo """ return minha_variavel class MinhaClasse: """ Classe exemplo. """ def __init__(self): self.variavel = minha_variavel def define_variavel(self, novo_valor): """ Define self.varivael para o novo valor """ self.variavel = novo_valor def pega_variavel(self): return self.variavel
############################################################################### ## Laboratorio de Engenharia de Computadores (LECOM) ## ## Departamento de Ciencia da Computacao (DCC) ## ## Universidade Federal de Minas Gerais (UFMG) ## ## ## ## Events for the actions of the simulator. It defines codes for message ## ## receive, message send and node call (for execution) events. It also ## ## contains an Event Generator to create the events for the simulator. ## ## Events are represented by tuples for performance reasons. ## ## ## ## TODO: ## ## ## ## Author: Eduardo Pinto ([email protected]) ## ############################################################################### class EventCode: MSG_RECV = 0 MSG_SEND = 2 NODE_CALL = 3 class EventGenerator: def create_call_event(time, addr): return (time, EventCode.NODE_CALL, addr) def create_send_event(time, msg): return (time, EventCode.MSG_SEND, msg) def create_recv_event(time, addr, msg): return (time, EventCode.MSG_RECV, addr, msg)
def getName(): return "html" def output(state,information): categories = information.listCategories() selections = state.selected toSave = "" toSave += """ <html> <head> </head> <body> \n """ firstOne = True for category in categories: found = 0 for selection in selections: if information.getCategory(selection) == category: if state.comments[selection] : found += 1 if found == 1: if not firstOne: toSave += "</ul>\n" toSave += "<h2>" + category + "</h2>\n<ul>\n" firstOne = False toSave += "\n<li>\n<h3>"+ selection+"</h3><br/>\n" commentLines = state.comments[selection].split("\n") for line in commentLines : toSave += line+"<br/>\n" toSave += "</li>\n" toSave += "</ul>\n" toSave += "</body>\n" toSave += "</html>\n" return toSave
""" TLS Lite is a free python library that implements SSL v3, TLS v1, and TLS v1.1. TLS Lite supports non-traditional authentication methods such as SRP, shared keys, and cryptoIDs, in addition to X.509 certificates. TLS Lite is pure python, however it can access OpenSSL, cryptlib, pycrypto, and GMPY for faster crypto operations. TLS Lite integrates with httplib, xmlrpclib, poplib, imaplib, smtplib, SocketServer, asyncore, and Twisted. To use, do:: from tlslite.api import * Then use the L{tlslite.TLSConnection.TLSConnection} class with a socket, or use one of the integration classes in L{tlslite.integration}. @version: 0.3.8 """ __version__ = "0.3.8" __all__ = ["api", "basedb", "checker", "constants", "errors", "fileobject", "handshakesettings", "mathtls", "messages", "session", "sessioncache", "sharedkeydb", "tlsconnection", "tlsrecordlayer", "verifierdb", "x509", "x509certchain", "integration", "utils"]
class Solution: def customSortString(self, order: str, str: str) -> str: output = "" strList = list(str) for i in order: cnt = strList.count(i) strList = [c for c in strList if c != i] output += i * cnt return output + "".join(strList)
def rot13_encrypt(text: str) -> str: if type(text) is not str: return False encrypted_text = "" for letter in text.lower(): ascii_code = ord(letter) if ascii_code > 109: # 122 (z) - 13 encrypted_text += chr(ascii_code + 13 - 26) # 26 - ilość liter w ang. else: encrypted_text += chr(ascii_code + 13) return encrypted_text def rot13_decrypt(text: str) -> str: if type(text) is not str: return False encrypted_text = "" for letter in text.lower(): ascii_code = ord(letter) if ascii_code - 13 < 97: encrypted_text += chr(ascii_code - 13 + 26) else: encrypted_text += chr(ascii_code - 13) return encrypted_text encrypted = rot13_encrypt("Python") print(f"Encrypted text is: {encrypted}") decrypted = rot13_decrypt(encrypted) print(f"Decrypted text is: {decrypted}")
print("\n") print("****************************************************") print("|--------------------- PyPong ---------------------|") print("| |") print("| By WMouton | l33th |") print("| Profession: Web Development & Linux Security |") print("| Interests: Blockchain, Cryptocurrency, |") print("| Artificial Intelligence, Hacking |") print("| Email : [email protected] |") print("| Github: github.com/l33th |") print("| |") print("****************************************************")
def pseudo_sort(st): lowerCaseWords = [] pass
class DataStore: def __init__(self, data): self.data = { "image": data["image"], "name": data["name"], "id": data["image"]["full"].split(".")[0], } def setImageUrl(self, imageUrl): self.imageUrl = imageUrl @property def image(self): return ( self.imageUrl + self.data["image"]["group"] + "/" + self.data["image"]["full"] ) @property def sprite(self): return ( self.imageUrl + "sprite/" + self.data["image"]["sprite"], self.data["image"]["x"], self.data["image"]["y"], ) @property def name(self): return self.data["name"] @property def id(self): return self.data["id"] spellToKeyHelper = {0: "Q", 1: "W", 2: "E", 3: "R"} class Champion(DataStore): BASE_URL = "http://ddragon.leagueoflegends.com/cdn/" def __init__(self, data): self.data = { "image": data["image"], "name": data["name"], "id": data["id"], "key": data["key"], "spells": [ {"image": s["image"], "name": s["name"], "id": s["id"]} for s in data["spells"] ] if "spells" in data else [], } self.spellById = None if "spells" in self.data: self.loadSpells() def loadSpells(self): self.spellById = {} self.spellByName = {} self.spellByKey = {} self.spellBySlot = {} for k, s in enumerate(self.data["spells"]): spell = Spell(s) self.spellById[s["id"]] = spell self.spellByName[s["name"]] = spell self.spellByKey[spellToKeyHelper[k]] = spell self.spellBySlot[k + 1] = spell def spell(self, sp): if isinstance(sp, int) or sp.isdigit(): return self.spellBySlot[int(sp)] elif len(sp) == 1: return self.spellByKey[sp] elif sp in self.spellByName: return self.spellByName[sp] elif sp in self.spellById: return self.spellById[sp] def setImageUrl(self, imageUrl): self.imageUrl = imageUrl if not self.spellById == None: for s in self.spellById: self.spellById[s].setImageUrl(imageUrl) @property def key(self): return self.data["key"] class Item(DataStore): pass class Map(DataStore): def __init__(self, data): self.data = {"image": data["image"], "name": data["MapName"]} class Summoner(DataStore): def __init__(self, data): self.data = { "image": data["image"], "name": data["name"], "id": data["id"], "key": data["key"], } @property def key(self): return self.data["key"] class Icon(DataStore): def __init__(self, data): self.data = {"image": data["image"], "name": None} class Spell(DataStore): pass class Rune: def __init__(self, data): self.data = {"icon": data["icon"], "name": data["name"], "id": data["id"]} def setImageUrl(self, imageUrl): self.imageUrl = imageUrl @property def image(self): return self.imageUrl + self.data["icon"] @property def name(self): return self.data["name"] @property def id(self): return self.data["id"]
class Distance: kilometers = 0.0 minutes = 0.0 def __init__(self, kilometers, minutes): self.kilometers = kilometers self.minutes = minutes def toJson(self): return { "kilometers" : self.kilometers, "minutes" : self.minutes }
# problem 8 # Project Euler def productOfNumbers(string,start,LENGTH): adjNumber = string[start:start+LENGTH] product = 1 for n in adjNumber: product *= int(n) return product def adjacentNumbers(string): LENGTH = 13 currentMaxProduct = -1 currentMaxIndex = -1 for i,e in enumerate(string): product = productOfNumbers(string,i,LENGTH) if currentMaxProduct < product: currentMaxProduct = product currentMaxIndex = i #print(currentMaxIndex, string[currentMaxIndex:currentMaxIndex+LENGTH], currentMaxProduct) return currentMaxProduct __author__ = 'Libao Jin' __date__ = 'July 12, 2015' string = '73167176531330624919225119674426574742355349194934\ 96983520312774506326239578318016984801869478851843\ 85861560789112949495459501737958331952853208805511\ 12540698747158523863050715693290963295227443043557\ 66896648950445244523161731856403098711121722383113\ 62229893423380308135336276614282806444486645238749\ 30358907296290491560440772390713810515859307960866\ 70172427121883998797908792274921901699720888093776\ 65727333001053367881220235421809751254540594752243\ 52584907711670556013604839586446706324415722155397\ 53697817977846174064955149290862569321978468622482\ 83972241375657056057490261407972968652414535100474\ 82166370484403199890008895243450658541227588666881\ 16427171479924442928230863465674813919123162824586\ 17866458359124566529476545682848912883142607690042\ 24219022671055626321111109370544217506941658960408\ 07198403850962455444362981230987879927244284909188\ 84580156166097919133875499200524063689912560717606\ 05886116467109405077541002256983155200055935729725\ 71636269561882670428252483600823257530420752963450' #print(string) print(adjacentNumbers(string))
# coding=utf-8 """ Created by jayvee on 2017/6/9. https://github.com/JayveeHe """
#!/usr/bin/env python # -*- coding: utf-8 -*- ######################################################################### # Author: jonyqin # Created Time: Thu 11 Sep 2014 01:53:58 PM CST # File Name: ierror.py # Description:定义错误码含义 ######################################################################### WXBizMsgCrypt_OK = 0 WXBizMsgCrypt_ValidateSignature_Error = -40001 WXBizMsgCrypt_ParseXml_Error = -40002 WXBizMsgCrypt_ComputeSignature_Error = -40003 WXBizMsgCrypt_IllegalAesKey = -40004 WXBizMsgCrypt_ValidateCorpid_Error = -40005 WXBizMsgCrypt_EncryptAES_Error = -40006 WXBizMsgCrypt_DecryptAES_Error = -40007 WXBizMsgCrypt_IllegalBuffer = -40008 WXBizMsgCrypt_EncodeBase64_Error = -40009 WXBizMsgCrypt_DecodeBase64_Error = -40010 WXBizMsgCrypt_GenReturnXml_Error = -40011
name = input("Enter your name: ") if name == "Arya Stark": print("Valar Morghulis") elif name == "Jon Snow": print("You know nothing!") else: print("Carry On!")
# Find the longest Palindromic Substring # Asked in Amazon ,MakeMyTrip, Microsoft, Qualcomm, Visa # Difficulty -> Medium # Algorithm: # We observe that a palindrome mirrors around its center. Therefore, a palindrome can be expanded from its center, and # there are only 2n - 1 such centers. You might be asking why there are 2n - 1 but not nn centers? The reason is the # center of a palindrome can be in between two letters. Such palindromes have even number of letters (such as "abba") # and its center are between the two 'b's. # function to find longest palindrome def longestPalindrome(s: str) -> str: # if the length is 0 or 1 then simply return the string if len(s) < 2: return s start, end = 0, 0 # iterate till the length of string for i in range(len(s)): # expand around center for odd length strings len1 = expandFromCenter(s, i, i) # expand around center for even length strings len2 = expandFromCenter(s, i, i + 1) # find the max of both l = max(len1, len2) # compute the start and end after checking if # it is bigger than the length we already have if l > end - start: start = i - (l - 1) // 2 end = i + l // 2 return s[start:end + 1] # utility function to expand from center def expandFromCenter(s, idx1, idx2): # this loop simply check for palindromic property while idx1 >= 0 and idx2 < len(s) and s[idx1] == s[idx2]: idx1 -= 1 idx2 += 1 return idx2 - idx1 - 1 # driver code string = "abcddcb" print(longestPalindrome(string)) # Time Complexity: O(n^2) # Space Complexity: O(1)
km = int(input('A quantos km/h o veículo cruzou o radar?')) if km > 80: m = float(km-80)*7 print('O veículo está acima do limite permitido, a multa é de :R${}'.format(m)) else: print('O veículo está dentro do limite permitido!')
expected_output = { "process_id": { 65109: { "router_id": "10.4.1.1", "ospf_object": { "Process ID (65109)": { "ipfrr_enabled": "no", "sr_enabled": "yes", "ti_lfa_configured": "yes", "ti_lfa_enabled": "yes (inactive)", }, "Area 8": { "ipfrr_enabled": "yes", "sr_enabled": "yes", "ti_lfa_configured": "yes", "ti_lfa_enabled": "yes", }, "Loopback0": { "ipfrr_enabled": "yes", "sr_enabled": "no", "ti_lfa_configured": "no", "ti_lfa_enabled": "yes (inactive)", }, "GigabitEthernet5": { "ipfrr_enabled": "yes", "sr_enabled": "yes", "ti_lfa_configured": "no", "ti_lfa_enabled": "yes", }, "GigabitEthernet4": { "ipfrr_enabled": "yes", "sr_enabled": "yes", "ti_lfa_configured": "no", "ti_lfa_enabled": "yes", }, "GigabitEthernet3": { "ipfrr_enabled": "yes", "sr_enabled": "yes", "ti_lfa_configured": "no", "ti_lfa_enabled": "yes", }, "GigabitEthernet2": { "ipfrr_enabled": "yes", "sr_enabled": "yes", "ti_lfa_configured": "no", "ti_lfa_enabled": "yes", }, "AS external": { "ipfrr_enabled": "no", "sr_enabled": "yes", "ti_lfa_configured": "yes", "ti_lfa_enabled": "yes (inactive)", }, }, } } }
# # PySNMP MIB module NBS-VLAN-FWD-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NBS-VLAN-FWD-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:17:48 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) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint") InterfaceIndex, nbs = mibBuilder.importSymbols("NBS-CMMC-MIB", "InterfaceIndex", "nbs") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Gauge32, IpAddress, TimeTicks, ModuleIdentity, Integer32, iso, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, Counter64, NotificationType, ObjectIdentity, MibIdentifier, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "IpAddress", "TimeTicks", "ModuleIdentity", "Integer32", "iso", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "Counter64", "NotificationType", "ObjectIdentity", "MibIdentifier", "Bits") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") nbsVlanFwdMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 629, 215)) if mibBuilder.loadTexts: nbsVlanFwdMib.setLastUpdated('201011120000Z') if mibBuilder.loadTexts: nbsVlanFwdMib.setOrganization('NBS') if mibBuilder.loadTexts: nbsVlanFwdMib.setContactInfo('For technical support, please contact your service channel') if mibBuilder.loadTexts: nbsVlanFwdMib.setDescription('MIB for representing VLAN Forwarding information') nbsVlanFwdGrp = ObjectIdentity((1, 3, 6, 1, 4, 1, 629, 215, 1)) if mibBuilder.loadTexts: nbsVlanFwdGrp.setStatus('current') if mibBuilder.loadTexts: nbsVlanFwdGrp.setDescription('VLAN Forwarding Configuration and Capabilities') nbsVlanControlGrp = ObjectIdentity((1, 3, 6, 1, 4, 1, 629, 215, 2)) if mibBuilder.loadTexts: nbsVlanControlGrp.setStatus('current') if mibBuilder.loadTexts: nbsVlanControlGrp.setDescription('VLAN Control Configuration and Capabilities') nbsVlanFwdTableSize = MibScalar((1, 3, 6, 1, 4, 1, 629, 215, 1, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: nbsVlanFwdTableSize.setStatus('current') if mibBuilder.loadTexts: nbsVlanFwdTableSize.setDescription('The number of entries in nbsVlanFwdTable') nbsVlanFwdTable = MibTable((1, 3, 6, 1, 4, 1, 629, 215, 1, 2), ) if mibBuilder.loadTexts: nbsVlanFwdTable.setStatus('current') if mibBuilder.loadTexts: nbsVlanFwdTable.setDescription('VLAN Forwarding information.') nbsVlanFwdEntry = MibTableRow((1, 3, 6, 1, 4, 1, 629, 215, 1, 2, 1), ).setIndexNames((0, "NBS-VLAN-FWD-MIB", "nbsVlanFwdIfIndex")) if mibBuilder.loadTexts: nbsVlanFwdEntry.setStatus('current') if mibBuilder.loadTexts: nbsVlanFwdEntry.setDescription("The VLAN Forwarding port's information") nbsVlanFwdIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 215, 1, 2, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: nbsVlanFwdIfIndex.setStatus('current') if mibBuilder.loadTexts: nbsVlanFwdIfIndex.setDescription('The Mib2 ifIndex of this VLAN Forwarding port') nbsVlanFwdVidList = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 215, 1, 2, 1, 2), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nbsVlanFwdVidList.setStatus('current') if mibBuilder.loadTexts: nbsVlanFwdVidList.setDescription('A list of VLAN ids as a free format text string. A non-empty string indicates that the port only forwards frames to other port(s) having the same VLAN id(s). For example: 1001 specifies one isolated VLAN id.') nbsVlanFwdVid = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 215, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 4095))).setMaxAccess("readwrite") if mibBuilder.loadTexts: nbsVlanFwdVid.setStatus('current') if mibBuilder.loadTexts: nbsVlanFwdVid.setDescription('Specifies the VLAN id to be used when adding a new outer VLAN tag to frames.') nbsVlanFwdPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 215, 1, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 7))).setMaxAccess("readwrite") if mibBuilder.loadTexts: nbsVlanFwdPriority.setStatus('current') if mibBuilder.loadTexts: nbsVlanFwdPriority.setDescription('Specifies the priority to be used when adding a new outer VLAN tag to frames.') nbsVlanFwdEgressTagAction = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 215, 1, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("notSupported", 1), ("add", 2), ("strip", 3), ("retain", 4))).clone('retain')).setMaxAccess("readwrite") if mibBuilder.loadTexts: nbsVlanFwdEgressTagAction.setStatus('current') if mibBuilder.loadTexts: nbsVlanFwdEgressTagAction.setDescription('Specifies what tagging action to perform on outgoing frames from this port: add(2) a new outer VLAN tag to each outgoing frame, using nbsVlanFwdVid and nbsVlanFwdPriority; strip(3) the outer VLAN tag from each outgoing frame; retain(4) tagging as is on each outgoing frame.') nbsVlanFwdEgressTagCapability = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 215, 1, 2, 1, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 1)).setFixedLength(1)).setMaxAccess("readonly") if mibBuilder.loadTexts: nbsVlanFwdEgressTagCapability.setStatus('current') if mibBuilder.loadTexts: nbsVlanFwdEgressTagCapability.setDescription('This bitmask indicates which nbsVlanPortEgressTagAction values are supported: add(2) if bit 2 is set, strip(3) if bit 3 is set, and retain(4) if bit 4 is set.') nbsVlanFwdIngressTagAction = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 215, 1, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("notSupported", 1), ("add", 2), ("strip", 3), ("retain", 4))).clone('retain')).setMaxAccess("readwrite") if mibBuilder.loadTexts: nbsVlanFwdIngressTagAction.setStatus('current') if mibBuilder.loadTexts: nbsVlanFwdIngressTagAction.setDescription('Specifies what tagging action to perform on incoming frames on this port: add(2) a new outer VLAN tag to each incoming frame, using nbsVlanFwdVid and nbsVlanFwdPriority; strip(3) the outer VLAN tag from each incoming frame; retain(4) tagging as is on each incoming frame.') nbsVlanFwdIngressTagCapability = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 215, 1, 2, 1, 8), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 1)).setFixedLength(1)).setMaxAccess("readonly") if mibBuilder.loadTexts: nbsVlanFwdIngressTagCapability.setStatus('current') if mibBuilder.loadTexts: nbsVlanFwdIngressTagCapability.setDescription('This bitmask indicates which nbsVlanPortIngressTagAction values are supported: add(2) if bit 2 is set, strip(3) if bit 3 is set, and retain(4) if bit 4 is set.') nbsVlanControlTableSize = MibScalar((1, 3, 6, 1, 4, 1, 629, 215, 2, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: nbsVlanControlTableSize.setStatus('current') if mibBuilder.loadTexts: nbsVlanControlTableSize.setDescription('The number of entries in nbsVlanControlTable') nbsVlanControlTable = MibTable((1, 3, 6, 1, 4, 1, 629, 215, 2, 2), ) if mibBuilder.loadTexts: nbsVlanControlTable.setStatus('current') if mibBuilder.loadTexts: nbsVlanControlTable.setDescription('VLAN Management information.') nbsVlanControlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 629, 215, 2, 2, 1), ).setIndexNames((0, "NBS-VLAN-FWD-MIB", "nbsVlanControlIfIndex")) if mibBuilder.loadTexts: nbsVlanControlEntry.setStatus('current') if mibBuilder.loadTexts: nbsVlanControlEntry.setDescription("The VLAN entity's management information") nbsVlanControlIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 215, 2, 2, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: nbsVlanControlIfIndex.setStatus('current') if mibBuilder.loadTexts: nbsVlanControlIfIndex.setDescription('The Mib2 ifIndex of this VLAN entity') nbsVlanControlMgmtVid = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 215, 2, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 4095)).clone(4094)).setMaxAccess("readwrite") if mibBuilder.loadTexts: nbsVlanControlMgmtVid.setStatus('current') if mibBuilder.loadTexts: nbsVlanControlMgmtVid.setDescription('Specifies the VLAN id to be used for management traffic.') mibBuilder.exportSymbols("NBS-VLAN-FWD-MIB", nbsVlanFwdEntry=nbsVlanFwdEntry, nbsVlanFwdEgressTagCapability=nbsVlanFwdEgressTagCapability, nbsVlanFwdTable=nbsVlanFwdTable, nbsVlanFwdVidList=nbsVlanFwdVidList, nbsVlanFwdGrp=nbsVlanFwdGrp, nbsVlanFwdIngressTagAction=nbsVlanFwdIngressTagAction, PYSNMP_MODULE_ID=nbsVlanFwdMib, nbsVlanControlTable=nbsVlanControlTable, nbsVlanFwdPriority=nbsVlanFwdPriority, nbsVlanFwdIngressTagCapability=nbsVlanFwdIngressTagCapability, nbsVlanControlTableSize=nbsVlanControlTableSize, nbsVlanFwdEgressTagAction=nbsVlanFwdEgressTagAction, nbsVlanFwdMib=nbsVlanFwdMib, nbsVlanControlGrp=nbsVlanControlGrp, nbsVlanControlEntry=nbsVlanControlEntry, nbsVlanFwdIfIndex=nbsVlanFwdIfIndex, nbsVlanControlIfIndex=nbsVlanControlIfIndex, nbsVlanControlMgmtVid=nbsVlanControlMgmtVid, nbsVlanFwdTableSize=nbsVlanFwdTableSize, nbsVlanFwdVid=nbsVlanFwdVid)
class has_many: def __init__(self, name, _class, primary_key=None, foreign_key=None): self.name = name self._class = _class self.primary_key = primary_key self.foreign_key = foreign_key class belongs_to: def __init__(self, name, _class, primary_key=None, foreign_key=None): self.name = name self._class = _class self.primary_key = primary_key self.foreign_key = foreign_key def only_for_has_many(func): def wrapper(self, *args, **kwrgs): if isinstance(self.relation, has_many): return func(self, *args, **kwrgs) else: print("Only for has_many!!") return wrapper class TableRelation: def __init__(self, base_table_class, relation, base_record_obj): self.base_table_class = base_table_class self.relation = relation self.pk = relation.primary_key self.fk = relation.foreign_key self.table = relation._class self.base_record_obj = base_record_obj @only_for_has_many def all(self): """Applies relation. Only for has_many""" return self.table.where(**{self.fk: self.base_record_obj.primary_key_value()}) @only_for_has_many def where(self, **args): args[self.fk] = self.base_record_obj.primary_key_value() return self.table.where(**args) def create(self, **args): """ Sets the FK to the current objs PK value and creats a record """ if isinstance(self.relation, has_many): args[self.fk] = self.base_record_obj.primary_key_value() return self.table.create(**args) else: print("Only for has_many") def __call__(self): if isinstance(self.relation, has_many): return self.all() elif isinstance(self.relation, belongs_to): """ Eg- Articles and Authors Articles belings_to Authors SELECT * FORM authors WHERE id= fk_value `id` is the primary key of the table to which "articles" belong """ rec = self.table.where(**{self.pk: getattr(self.base_record_obj, self.fk)}) return rec[0] if rec else None
''' UBC Eye Movement Data Analysis Toolkit (EMDAT), Version 3 '''
setup( name='pyroll', description='cli for simulating the rolling of dice', author='Philip Z Nevill', author_email='[email protected]', version='0.1.0', packages=find_packages(include=['pyroll', 'pyroll.*']), )