content stringlengths 7 1.05M |
|---|
class Fencepost():
vertices = [(0.25,0,0),
(0.25,0.75,0),
(1,0.75,0),
(1,0,0),
(0.25,0,1.75),
(0.25,0.75,1.75),
(1,0.75,1.75),
(1,0,1.75), #7
# Back post
(0,0.75,0.575),
(0,1.05,0.575),
(1.25,1.05,0.575),
(1.25,0.75,0.575),
(0,0.75,1.175),
(0,1.05,1.175),
(1.25,1.05,1.175),
(1.25,0.75,1.175) #15
]
faces = [(0,1,2,3),
(0,4,5,1),
(1,5,6,2),
(2,6,7,3),
(3,7,4,0),
(4,5,6,7),
# Back post
(8,9,10,11),
(8,12,13,9),
(9,13,14,10),
(10,14,15,11),
(11,15,12,8),
(12,13,14,15),
]
def load():
return Fencepost() |
################ modules for HSPICE sim ######################
##############################################################
######### varmap definition ####################
##############################################################
### This class is to make combinations of given variables ####
### mostly used for testbench generation #################
### EX: varmap1=HSPICE_varmap.varmap(4) %%num of var=4 #######
### varmap1.get_var('vdd',1.5,1.8,0.2) %%vdd=1.5:0.2:1.8##
### varmap1.get_var('abc', ........ %%do this for 4 var ##
### varmap1.cal_nbigcy() %%end of var input###
### varmap1.combinate %%returns variable comb 1 by 1 ####
##############################################################
class varmap:
#def __init__(self,num_var):
# self.n_smlcycle=1
# self.last=0
# self.smlcy=1
# self.bigcy=0
# self.vv=0
# self.vf=1
# self.size=num_var
# self.map=[None]*self.size
# self.comblist=[None]*self.size
# self.nvar=0
def __init__(self):
self.n_smlcycle=1
self.last=0
self.smlcy=1
self.bigcy=0
self.vv=0
self.vf=1
#self.map=[None]
#self.comblist=[None]
self.nvar=0
def get_var(self,name,start,end,step):
if self.nvar==0:
self.map=[None]
self.comblist=[None]
else:
self.map.append(None)
self.comblist.append(None)
self.map[self.nvar]=list([name])
self.comblist[self.nvar]=list([name])
self.nswp=(end-start)//step+1
for i in range(1,self.nswp+1):
self.map[self.nvar].append(start+step*(i-1))
self.nvar+=1
def cal_nbigcy(self):
self.bias=[1]*(len(self.map))
for j in range(1,len(self.map)+1):
self.n_smlcycle=self.n_smlcycle*(len(self.map[j-1])-1)
self.n_smlcycle=self.n_smlcycle*len(self.map)
def increm(self,inc): #increment bias
self.bias[inc]+=1
if self.bias[inc]>len(self.map[inc])-1:
self.bias[inc]%len(self.map[inc])-1
def check_end(self,vf): #When this is called, it's already last stage of self.map[vf]
self.bias[vf]=1
# if vf==0 and self.bias[0]==len(self.map[0])-1:
# return 0
if self.bias[vf-1]==len(self.map[vf-1])-1: #if previous column is last element
self.check_end(vf-1)
else:
self.bias[vf-1]+=1
return 1
def combinate(self):
# print self.map[self.vv][self.bias[self.vv]]
self.smlcy+=1
if self.vv==len(self.map)-1: #last variable
self.bigcy+=1
for vprint in range(0,len(self.map)):
self.comblist[vprint].append(self.map[vprint][self.bias[vprint]])
#print self.map[vprint][self.bias[vprint]]
if self.bias[self.vv]==len(self.map[self.vv])-1: #last element
if self.smlcy<self.n_smlcycle:
self.check_end(self.vv)
self.vv=(self.vv+1)%len(self.map)
self.combinate()
else:
pass
else:
self.bias[self.vv]+=1
self.vv=(self.vv+1)%len(self.map)
self.combinate()
else:
self.vv=(self.vv+1)%len(self.map)
self.combinate()
##############################################################
######### netmap ########################
##############################################################
### This class is used for replacing lines ################
### detects @@ for line and @ for nets #######################
##############################################################
#-------- EXAMPLE ---------------------------------------#
### netmap1=netmap(2) %input num_var #########################
### netmap1.get_var('ab','NN',1,4,1) %flag MUST be 2 char ####
## netmap2.get_var('bc','DD',2,5,1) %length of var must match#
# !!caution: do get_var in order, except for lateral prints ##
### which is using @W => varibales here, do get_var at last ##
### for line in r_file.readlines():###########################
### netmap1.printline(line,w_file) #######################
##############################################################
class netmap:
#def __init__(self,num_var):
# self.size=num_var
# self.map=[None]*self.size
# self.flag=[None]*self.size
# self.name=[None]*self.size
# self.nnet=[None]*self.size
# self.nn=0
# self.pvar=1
# self.cnta=0
# self.line_nvar=0 # index of last variable for this line
# self.nxtl_var=0 # index of variable of next line
# self.ci_at=100
def __init__(self):
self.nn=0
self.pvar=1
self.cnta=0
self.line_nvar=0 # index of last variable for this line
self.nxtl_var=0 # index of variable of next line
self.ci_at=-5
def get_net(self,flag,netname,start,end,step): #if start==None: want to repeat without incrementation(usually for tab) (end)x(step) is the num of repetition
if self.nn==0:
self.map=[None]
self.flag=[None]
self.name=[None]
self.nnet=[None]
else:
self.map.append(None)
self.name.append(None)
self.flag.append(None)
self.nnet.append(None)
if netname==None:
self.name[self.nn]=0
else:
self.name[self.nn]=1
self.map[self.nn]=list([netname])
self.flag[self.nn]=(flag)
if start!=None and start!='d2o':
self.nnet[self.nn]=int((end-start+step/10)//step+1)
if self.name[self.nn]==1:
for i in range(1,self.nnet[self.nn]+1):
self.map[self.nn].append('')
else:
for i in range(1,self.nnet[self.nn]+1):
self.map[self.nn].append(start+step*(i-1))
elif start=='d2o':
for i in range(0,end):
if step-i>0:
self.map[self.nn].append(1)
else:
self.map[self.nn].append(0)
i+=1
else:
self.map[self.nn]=list([netname])
for i in range(1,step+1):
self.map[self.nn].append(end)
# self.map[self.nn]=[None]*step
# for i in range(1,self.nnet[self.nn]+1):
# self.map[self.nn][i]=None
self.nn+=1
#print self.map
def add_val(self,flag,netname,start,end,step):
varidx=self.flag.index(flag)
if start!=None:
nval=int((end-start+step/10)//step+1)
for i in range(1,nval+1):
self.map[varidx].append(start+step*(i-1))
else:
for i in range(1,step+1):
self.map[varidx].append(end)
def printline(self,line,wrfile):
if line[0:2]=='@@':
#print('self.ci_at=%d'%(self.ci_at))
self.nline=line[3:len(line)]
self.clist=list(self.nline) #character list
#print(self.clist,self.nxtl_var)
for iv in range (1,len(self.map[self.nxtl_var])):
for ci in range(0,len(self.clist)):
if (ci==self.ci_at+1 or ci==self.ci_at+2) and ci!=len(self.clist)-1:
pass
elif self.clist[ci]=='@':
#print self.cnta
self.cnta+=1
self.line_nvar+=1
varidx=self.flag.index(self.clist[ci+1]+self.clist[ci+2])
if self.name[varidx]:
wrfile.write(self.map[varidx][0])
# print(self.map[varidx])
if type(self.map[varidx][self.pvar])==float:
wrfile.write('%e'%(self.map[varidx][self.pvar])) #modify here!!!!
elif type(self.map[varidx][self.pvar])==int:
wrfile.write('%d'%(self.map[varidx][self.pvar]))
self.ci_at=ci
elif ci==len(self.clist)-1: #end of the line
if self.pvar==len(self.map[self.nxtl_var+self.line_nvar-1])-1: #last element
self.pvar=1
self.nxtl_var=self.nxtl_var+self.line_nvar
self.line_nvar=0
self.cnta=0
self.ci_at=-6
#print('printed all var for this line, %d'%(ci))
else:
self.pvar+=1
#self.line_nvar=self.cnta
self.line_nvar=0
#print ('line_nvar= %d'%(self.line_nvar))
self.cnta=0
wrfile.write(self.clist[ci])
else:
wrfile.write(self.clist[ci])
elif line[0:2]=='@W':
#print('found word line')
self.nline=line[3:len(line)]
self.clist=list(self.nline)
for ci in range(0,len(self.clist)):
if (ci==self.ci_at+1 or ci==self.ci_at+2):
pass
elif self.clist[ci]=='@':
varidx=self.flag.index(self.clist[ci+1]+self.clist[ci+2])
for iv in range(1,len(self.map[varidx])):
if self.name[varidx]:
wrfile.write(self.map[varidx][0])
wrfile.write('%d '%(self.map[varidx][iv]))
print ('n is %d, varidx=%d, iv=%d'%(self.map[varidx][iv],varidx,iv))
self.ci_at=ci
else:
wrfile.write(self.clist[ci])
self.ci_at=-5
else:
wrfile.write(line)
##############################################################
######### resmap ########################
##############################################################
### This class is used to deal with results ################
### detects @@ for line and @ for nets #######################
##############################################################
#-------- EXAMPLE ---------------------------------------#
### netmap1=netmap(2) %input num_var #########################
### netmap1.get_var('ab','NN',1,4,1) %flag MUST be 2 char ####
## netmap2.get_var('bc','DD',2,5,1) %length of var must match#
### for line in r_file.readlines():###########################
### netmap1.printline(line,w_file) #######################
###### self.tb[x][y][env[]]###############################
##############################################################
class resmap:
def __init__(self,num_tb,num_words,index): #num_words includes index
self.tb=[None]*num_tb
self.tbi=[None]*num_tb
self.vl=[None]*num_tb
self.vlinit=[None]*num_tb
self.svar=[None]*num_tb
self.index=index
self.nenv=0
self.num_words=num_words
self.vr=[None]*(num_words+index) #one set of variables per plot
self.vidx=[None]*(num_words+index)
self.env=[None]*(num_words+index)
# self.vl=[None]*(num_words+index) #one set of variables per plot
for itb in range(0,len(self.tb)):
# self.tb[itb].vr=[None]*(num_words+index)
self.tbi[itb]=0 #index for counting vars within tb
self.vl[itb]=[None]*(num_words+index)
self.vlinit[itb]=[0]*(num_words+index)
def get_var(self,ntb,var):
self.vr[self.tbi[ntb]]=(var)
# self.vl[ntb][self.tbi[ntb]]=list([None])
self.tbi[ntb]+=1
if self.tbi[ntb]==len(self.vr): #????????
self.tbi[ntb]=0
def add(self,ntb,value):
if self.vlinit[ntb][self.tbi[ntb]]==0: #initialization
self.vl[ntb][self.tbi[ntb]]=[value]
self.vlinit[ntb][self.tbi[ntb]]+=1
else:
self.vl[ntb][self.tbi[ntb]].append(value)
self.tbi[ntb]=(self.tbi[ntb]+1)%len(self.vr)
def plot_env(self,ntb,start,step,xvar,xval): #setting plot environment: if ntb=='all': x axis is in terms of testbench
if ntb=='all':
self.nenv+=1
self.xaxis=[None]*len(self.tb)
for i in range(0,len(self.tb)):
self.xaxis[i]=start+i*step
self.vidx[self.nenv]=self.vr.index(xvar)
#print self.vl[0][self.vidx[self.nenv]]
print('', self.vl[0][self.vidx[self.nenv]])
self.env[self.nenv]=[i for (i,x) in enumerate(self.vl[0][self.vidx[self.nenv]]) if x=='%s'%(xval)]
else:
self.nenv+=1
self.xaxis=[None] #one output
self.xaxis=[start]
self.vidx[self.nenv]=self.vr.index(xvar)
self.env[self.nenv]=[i for (i,x) in enumerate(self.vl[0][self.vidx[self.nenv]]) if x=='%s'%(xval)]
def rst_env(self):
self.vidx[self.nenv]=None
self.env[self.nenv]=0
self.nenv=0
#print self.vl[0][self.vidx[self.nenv]]
def plot_y(self,yvar):
self.yidx=self.vr.index(yvar)
print ('yidx=%d'%(self.yidx))
#print self.vl[0][self.yidx][self.env[self.nenv][0]]
print('', self.vl[0][self.yidx][self.env[self.nenv][0]])
self.yaxis=[None]*len(self.xaxis)
for xx in range(0,len(self.xaxis)):
self.yaxis[xx]=self.vl[xx][self.yidx][self.env[self.nenv][0]]
#plt.plot(self.xaxis,self.yaxis)
#plt.ylabel(self.vr[self.yidx])
def sort(self,var):
varidx=self.vr.index(var)
for k in range(len(self.vl)): #all testbenches
self.svar[k]={} #define dict
for i in range(len(self.vl[0][0])): #all values
self.svar[k][self.vl[k][varidx][i]]=[]
for j in range(len(self.vr)): #all variables
if j!=varidx:
self.svar[k][self.vl[k][varidx][i]].append(self.vl[k][j][i])
# if k==0:
# print self.svar[k]
|
def line_br_int(win, p1, p2):
if p1 == p2:
win.image.setPixel(p1[0], p1[1], win.pen.color().rgb())
return
dx = p2[0] - p1[0]
dy = p2[1] - p1[1]
sx = sign(dx)
sy = sign(dy)
dx = abs(dx)
dy = abs(dy)
x = p1[0]
y = p1[1]
change = False
if dy > dx:
temp = dx
dx = dy
dy = temp
change = True
e = 2 * dy - dx
i = 1
while i <= dx:
win.image.setPixel(x, y, win.pen.color().rgb())
if e >= 0:
if change == 0:
y += sy
else:
x += sx
e -= 2 * dx
if e < 0:
if change == 0:
x += sx
else:
y += sy
e += (2 * dy)
i += 1
|
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ADSBVehicle.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ActuatorControl.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/Altitude.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/AttitudeTarget.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/BatteryStatus.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/CamIMUStamp.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/CommandCode.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/CompanionProcessStatus.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/OnboardComputerStatus.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/DebugValue.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ESCInfo.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ESCInfoItem.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ESCStatus.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ESCStatusItem.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/EstimatorStatus.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ExtendedState.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/FileEntry.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/GlobalPositionTarget.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/GPSRAW.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/GPSRTK.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/HilActuatorControls.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/HilControls.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/HilGPS.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/HilSensor.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/HilStateQuaternion.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/HomePosition.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/LandingTarget.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/LogData.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/LogEntry.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ManualControl.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/Mavlink.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/MountControl.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/OpticalFlowRad.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/OverrideRCIn.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/Param.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ParamValue.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/PlayTuneV2.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/PositionTarget.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/RCIn.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/RCOut.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/RTCM.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/RadioStatus.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/RTKBaseline.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/State.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/StatusText.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/Thrust.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/TimesyncStatus.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/Trajectory.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/VFR_HUD.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/VehicleInfo.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/Vibration.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/Waypoint.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/WaypointList.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/WaypointReached.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/WheelOdomStamped.msg"
services_str = "/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandBool.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandHome.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandInt.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandLong.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandTOL.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandTriggerControl.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandTriggerInterval.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandVtolTransition.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileChecksum.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileClose.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileList.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileMakeDir.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileOpen.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileRead.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileRemove.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileRemoveDir.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileRename.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileTruncate.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileWrite.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/LogRequestData.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/LogRequestEnd.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/LogRequestList.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/MountConfigure.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/MessageInterval.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/ParamGet.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/ParamPull.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/ParamPush.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/ParamSet.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/SetMavFrame.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/SetMode.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/StreamRate.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/VehicleInfoGet.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/WaypointClear.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/WaypointPull.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/WaypointPush.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/WaypointSetCurrent.srv"
pkg_name = "mavros_msgs"
dependencies_str = "geographic_msgs;geometry_msgs;sensor_msgs;std_msgs"
langs = "gencpp;geneus;genlisp;gennodejs;genpy"
dep_include_paths_str = "mavros_msgs;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg;geographic_msgs;/opt/ros/melodic/share/geographic_msgs/cmake/../msg;geometry_msgs;/opt/ros/melodic/share/geometry_msgs/cmake/../msg;sensor_msgs;/opt/ros/melodic/share/sensor_msgs/cmake/../msg;std_msgs;/opt/ros/melodic/share/std_msgs/cmake/../msg;uuid_msgs;/opt/ros/melodic/share/uuid_msgs/cmake/../msg"
PYTHON_EXECUTABLE = "/usr/bin/python2"
package_has_static_sources = '' == 'TRUE'
genmsg_check_deps_script = "/opt/ros/melodic/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py"
|
# *-* coding: utf-8 *-*
class Customer:
def __init__(self, firstname=None, lastname=None, address1=None, postcode=None, city=None, phone=None, email=None,
password=None, confirmed_password=None):
self.firstname = firstname
self.lastname = lastname
self.address1 = address1
self.postcode = postcode
self.city = city
self.phone = phone
self.email = email
self.password = password
self.confirmed_password = confirmed_password
|
class Solution(object):
def longestValidParentheses(self, s):
if len(s) == 0:
return 0
stack = [-1]
result = 0
for idx, ch in enumerate(s):
if ch == "(":
stack.append(idx)
else:
stack.pop()
if len(stack) == 0:
stack.append(idx)
else:
length = idx-stack[-1]
result = max(result, length)
return result
def longestParentheses(string):
if len(string) == 0:
return 0
stk = []
longestLength = 0
for i, ch in enumerate(string):
if ch == '(':
stk.append(i)
elif ch == ')':
if stk:
open_i = stk.pop()
length = i-open_i + 1
if length > longestLength:
longestLength = length
return longestLength
|
# Clase 32. Curso Píldoras Informáticas.
# Control de Flujo. POO9.
# Polimorfismo
class Car():
def desplaza(self):
print("El coche se desplaza sobre sus cuatro ruedas.")
class Moto():
def desplaza(self):
print("La moto se desplaza sobre sus dos ruedas.")
class Furgo():
def desplaza(self):
print("La furgo se desplaza sobre sus seis ruedas.")
print("----Sin Polimorismo----")
VehiculoUno = Moto()
VehiculoUno.desplaza()
VehiculoDos = Furgo()
VehiculoDos.desplaza()
VehiculoTres = Car()
VehiculoTres.desplaza()
print("----Con Polimorismo----")
def desplazaPolif(k):
k.desplaza()
VehiculoCuatro = Furgo()
desplazaPolif(VehiculoCuatro)
VehiculoCinco = Moto()
desplazaPolif(VehiculoCinco)
|
# You are at the zoo, and the meerkats look strange.
# You will receive 3 strings: (tail, body, head).
# Your task is to re-arrange the elements in a list
# so that the animal looks normal again: (head, body, tail).
tail = input()
body = input()
head = input()
lst = [head,body,tail]
print(lst) |
def area(largura, comprimento):
print(f'A área do seu tereno ({largura} x {comprimento}) é de {largura * comprimento}m²')
print(' Controle de Terrenos ')
print('-' * len(' Controle de Terrenos '))
larg = float(input('Largura: m'))
comp = float(input('Comprimento: m'))
area(largura=larg, comprimento=comp)
|
tiles = [
# highway=steps, with route regional (Coastal Trail, Marin, II)
# https://www.openstreetmap.org/way/24655593
# https://www.openstreetmap.org/relation/2260059
[12, 653, 1582],
# highway=steps, no route, but has name, and designation (Levant St Stairway, SF)
# https://www.openstreetmap.org/way/38060491
[13, 1309, 3166]
]
for z, x, y in tiles:
assert_has_feature(
z, x, y, 'roads',
{'highway': 'steps'})
# way 25292070 highway=steps, no route, but has name (Esmeralda, Bernal, SF)
assert_no_matching_feature(
13, 1310, 3167, 'roads',
{'kind': 'path', 'highway': 'steps', 'name': 'Esmeralda Ave.'})
# way 25292070 highway=steps, no route, but has name (Esmeralda, Bernal, SF)
assert_has_feature(
14, 2620, 6334, 'roads',
{'kind': 'path', 'highway': 'steps', 'name': 'Esmeralda Ave.'})
|
# Time: O(h * p^2), p is the number of patterns
# Space: O(p^2)
# bitmask, backtracking, dp
class Solution(object):
def buildWall(self, height, width, bricks):
"""
:type height: int
:type width: int
:type bricks: List[int]
:rtype: int
"""
MOD = 10**9+7
def backtracking(height, width, bricks, total, mask, lookup, patterns):
if mask in lookup:
return
lookup.add(mask)
if total >= width:
if total == width:
patterns.append(mask^(1<<width))
return
for x in bricks:
backtracking(height, width, bricks, total+x, mask|(1<<(total+x)), lookup, patterns)
patterns, lookup = [], set()
backtracking(height, width, bricks, 0, 0, lookup, patterns)
adj = [[j for j, r2 in enumerate(patterns) if not (r1 & r2)] for r1 in patterns]
dp = [[1]*len(patterns), [0]*len(patterns)]
for i in xrange(height-1):
dp[(i+1)%2] = [sum(dp[i%2][k] for k in adj[j]) % MOD for j in xrange(len(patterns))]
return sum(dp[(height-1)%2]) % MOD
# Time: O(p^3 * logh), p is the number of patterns, p may be up to 512
# Space: O(p^3)
# bitmask, backtracking, matrix exponentiation
class Solution_TLE(object):
def buildWall(self, height, width, bricks):
"""
:type height: int
:type width: int
:type bricks: List[int]
:rtype: int
"""
MOD = 10**9+7
def backtracking(height, width, bricks, total, mask, lookup, patterns):
if mask in lookup:
return
lookup.add(mask)
if total >= width:
if total == width:
patterns.append(mask^(1<<width))
return
for x in bricks:
backtracking(height, width, bricks, total+x, mask|(1<<(total+x)), lookup, patterns)
def matrix_mult(A, B):
ZB = zip(*B)
return [[sum(a*b % MOD for a, b in itertools.izip(row, col)) % MOD for col in ZB] for row in A]
def matrix_expo(A, K):
result = [[int(i == j) for j in xrange(len(A))] for i in xrange(len(A))]
while K:
if K % 2:
result = matrix_mult(result, A)
A = matrix_mult(A, A)
K /= 2
return result
patterns, lookup = [], set()
backtracking(height, width, bricks, 0, 0, lookup, patterns)
return reduce(lambda x,y: (x+y)%MOD,
matrix_mult([[1]*len(patterns)],
matrix_expo([[int((mask1 & mask2) == 0)
for mask2 in patterns]
for mask1 in patterns], height-1))[0],
0) # Time: O(p^3 * logh), Space: O(p^2)
|
# Copyright 2018 BlueCat Networks. All rights reserved.
# -*- coding: utf-8 -*-
type = 'api'
sub_pages = [
{
'name' : 'ipam_page',
'title' : u'Cisco_DNA_IPAM_Interface',
'endpoint' : 'ipam/ipam_endpoint',
'description' : u'Gateway workflow to be IPAM interface to integrate with Cisco DNA Centre'
},
]
|
n=int(input())
alpha_code = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:'
NEW_INPUT = 9
NUMERIC = 1
ALPHA = 2
BYTE_CODE = 4
KANJI = 8
TERMINATION = 0
while n:
code = int(input(), 16)
state = NEW_INPUT
ans = ''
p = 38*4
ret_size = 0
while p>0:
if state == TERMINATION:
break
elif state == NEW_INPUT:
p-=4
state = code//(2**p)
code%=2**p
elif state == NUMERIC:
p-=10
size = code//(2**p)
code%=2**p
while size:
if size == 1:
p-=4
data = code//(2**p)
code%=2**p
ret_size+=1
size-=1
ans+='%01d'%data
elif size == 2:
p-=7
data = code//(2**p)
code%=2**p
ret_size+=2
size-=2
ans+='%02d'%data
else:
p-=10
data = code//(2**p)
code%=2**p
ret_size+=3
size-=3
ans+='%03d'%data
state = NEW_INPUT
elif state == ALPHA:
p-=9
size = code//(2**p)
code%=2**p
while size:
if size==1:
p-=6
data = code//(2**p)
code%=2**p
ret_size+=1
size-=1
ans+=alpha_code[data]
else:
p-=11
data = code//(2**p)
code%=2**p
ret_size+=2
size-=2
data1 = alpha_code[data//45]
data2 = alpha_code[data%45]
ans+= data1+data2
state = NEW_INPUT
elif state == BYTE_CODE:
p-=8
size = code//(2**p)
code%=2**p
while size:
p-=8
size-=1
data = code//(2**p)
code%=2**p
ret_size+=1
if data>=0x20 and data<=0x7e:
ans+=chr(data)
else:
ans+='\\'+'%02X'%(data)
state = NEW_INPUT
elif state == KANJI:
p-=8
size = code//(2**p)
code%=2**p
while size:
p-=13
size-=1
data = code//(2**p)
code%=2**p
ret_size+=1
ans+='#'+'%04X'%(data)
state = NEW_INPUT
print(ret_size, ans)
n-=1 |
# Read two rectangles, discern wheter rect1 is inside rect2
class Rectangle:
def __init__(self, *tokens):
self.left, self.top, self.width, self.height = list(map(float, tokens))
def is_inside(self, other_rect):
if type(other_rect) is not Rectangle:
raise TypeError('other_rect is not a Point object.')
inside_horiz = self.left >= other_rect.left and self.width <= other_rect.width
inside_verti = self.top <= other_rect.top and self.height <= other_rect.height
fully_inside = inside_horiz and inside_verti
result = 'Inside' if fully_inside else 'Not inside'
return(result)
rectangle_list = []
for i in range(2):
user_input = input().split()
user_input = map(int, user_input)
cur_rect = Rectangle(*user_input)
rectangle_list.append(cur_rect)
print(rectangle_list[0].is_inside(rectangle_list[1]))
|
#!/usr/bin/python
# This is my shopping list
shoplist = ['apple', 'mango', 'carrot', 'banana']
print('I have', len(shoplist), 'item to purchase.')
print('These items are:', end=' ')
for item in shoplist:
print(item, end = ' ')
print('\nI also have to buy rice.')
shoplist.append('rice')
print('My shopping list is now', shoplist)
print('I will sort my list now')
shoplist.sort()
print('Sorted shopping list is', shoplist)
print('The first item I will buy is', shoplist[0])
olditem = shoplist[0]
del shoplist[0]
print('I bought the', olditem)
print('My shopping list is now', shoplist) |
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
tmp = list(nums[:len(nums) - k])
del nums[:len(nums) - k]
nums.extend(tmp) |
"""
entrada
suelto=>int=>su
ventas departamento 1=>int=>dep1
ventas departamento 2=>int=>dep2
ventas departamento 3=>int=>dep3
salida
sueldo total al final del mes 3 departamentos=>int=> total3dep
"""
su=int(input("ingrese sueldo "))
dep1=int(input("ingrese ventas echas "))
dep2=int(input("ingrese ventas echas "))
dep3=int(input("ingrese ventas echas "))
ventotal=(dep1+dep2+dep3)
print("venta total: "+str(ventotal))
ex33=(ventotal*33)/100
if(dep1>ex33):
dep1=su+su*.20/100
else:
dep1=su
print("los vendedores del departamento 1 recibiran: "+str(dep1))
if(dep2>ex33):
dep2=su+su*.20/100
else:
dep2=su
print("los vendedores del departamento 2 recibiran: "+str(dep2))
if(dep3>ex33):
dep3=su+su*.20/100
else:
dep3=su
print("los vendedores del departamento 3 recibiran: "+str(dep3))
|
"""This module implements the abstract classes/interfaces of all variable pipeline components."""
class AbstractDataLoader:
"""The AbstractDataLoader defines the interface for any kind of IMU data loader."""
def __init__(self, raw_base_path, dataset, subject, run):
"""
Initialization of an AbstractDataLoader
Args:
raw_base_path (str): Base folder for every dataset
dataset (str): Folder containing the dataset
subject (str): Subject identifier
run (str): Run identifier
"""
self.data = {}
self.load(raw_base_path, dataset, subject, run)
def load(self, raw_base_path, dataset, subject, run):
"""
This method is called at instantiation and needs to be implemented by the derived class.
It is expected to find the actual data files based on the given parameters
and store them as a dictionary of IMU objects into self.data
Args:
raw_base_path (str): Base folder for every dataset
dataset (str): Folder containing the dataset
subject (str): Subject identifier
run (str): Run identifier
Returns:
None
"""
pass
def get_data(self):
"""
Get the loaded data.
Returns:
dict[str, IMU]: IMU data from all sensors
"""
return self.data
class AbstractTrajectoryEstimator:
""" The AbstractTrajectoryEstimator defines the interface for each trajectory estimation algorithm."""
def __init__(self, imus):
"""
Initialization of an AbstractTrajectoryEstimator
Args:
imus dict[str, IMU]: Dictionary of IMU objects for each sensor location
"""
self.imus = imus
def estimate(self, interim_base_path, dataset, subject_num, run_num):
"""
This method is expected to be implemented by each trajectory estimation algorithm.
Args:
interim_base_path (str): Base folder where interim data can be stored
dataset (str): Folder containing the dataset
subject_num (int): Subject index
run_num (int): Run index
Returns:
dict[str, DataFrame]: DataFrames containing trajectory information for each foot
"""
pass
class AbstractEventDetector:
"""
The AbstractEventDetector defines the interface for any kind of event detection algorithm.
"""
def __init__(self, imus):
"""
Initialization of an AbstractEventDetector.
Args:
imus (dict[str, IMU]): Dictionary of IMU objects for each sensor location.
"""
self.imus = imus
def detect(self):
"""
This method is expected to be implemented by each event detection algorithm.
Returns:
(dict[str, dict]): dictionaries containing gait event information for each foot.
"""
pass
class AbstractReferenceLoader:
"""
The AbstractReferenceLoader defines the interface for any kind of reference data loader.
"""
def __init__(
self, name, raw_base_path, interim_base_path, dataset, subject, run, overwrite
):
"""
Initialization of an AbstractReferenceLoader.
Args:
mame (str): Identifier used to create caching files
raw_base_path (str): Base folder for every dataset
interim_base_path (str): Base folder where interim data can be stored
dataset (str): Folder containing the dataset
subject (str): Subject identifier
run (str): Run identifier
"""
self.name = name
self.raw_base_path = raw_base_path
self.interim_base_path = interim_base_path
self.dataset = dataset
self.subject = subject
self.run = run
self.overwrite = overwrite
self.data = {"left": {}, "right": {}}
self.load()
def load(self):
"""
This method is called at instantiation and needs to be implemented by the derived class.
It is expected to find the actual data files based on the given parameters
and store reference data for the left and right foot in self.data
Returns:
None
"""
pass
def get_data(self):
"""
Get the loaded reference data.
Returns:
dict[str, DataFrame]: DataFrames with gait parameters for the left and right foot
"""
return self.data
|
graph={
'A':['B','C'],
'B':['A'],
'C':['D','E','F','S'],
'D':['C'],
'E':['C','H'],
'F':['C','G'],
'G':['F','G'],
'H':['E','G'],
'S':['A','C','G']
}
visited=[]
def dfs(graph,node):
if node not in visited:
visited.append(node)
for n in graph[node]:
dfs(graph,n)
dfs(graph,'A')
print(visited)
|
'''
Lec 7
while loop
'''
i=5
while i >=0 :
try:
print(1/(i-3))
except:
pass
i = i - 1
|
'''
'''
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
Test.Summary = 'Testing ATS TCP handshake timeout'
# Skipping this in the normal CI because it requires privilege.
# Comment out to run in your privileged environment
Test.SkipIf(Condition.true("Test requires privilege"))
ts = Test.MakeATSProcess("ts")
Test.ContinueOnFail = True
Test.GetTcpPort("blocked_upstream_port")
Test.GetTcpPort("upstream_port")
server4 = Test.MakeOriginServer("server4")
ts.Disk.records_config.update({
'proxy.config.url_remap.remap_required': 1,
'proxy.config.http.connect_attempts_timeout': 2,
'proxy.config.http.connect_attempts_max_retries': 0,
'proxy.config.http.transaction_no_activity_timeout_out': 5,
'proxy.config.diags.debug.enabled': 0,
'proxy.config.diags.debug.tags': 'http',
})
ts.Disk.remap_config.AddLine('map /blocked http://10.1.1.1:{0}'.format(Test.Variables.blocked_upstream_port))
ts.Disk.remap_config.AddLine('map /not-blocked http://10.1.1.1:{0}'.format(Test.Variables.upstream_port))
ts.Disk.logging_yaml.AddLines(
'''
logging:
formats:
- name: testformat
format: '%<pssc> %<cquc> %<pscert> %<cscert>'
logs:
- mode: ascii
format: testformat
filename: squid
'''.split("\n")
)
# Set up the network name space. Requires privilege
tr = Test.AddTestRun("tr-ns-setup")
tr.Processes.Default.StartBefore(ts)
tr.Processes.Default.TimeOut = 2
tr.Setup.Copy('setupnetns.sh')
tr.Processes.Default.Command = 'echo start; sudo sh -x ./setupnetns.sh {0} {1}'.format(
Test.Variables.blocked_upstream_port, Test.Variables.upstream_port)
# Request to the port that is blocked in the network ns. The SYN should never be responded to
# and the connect timeout should trigger with a 50x return. If the SYN handshake occurs, the
# no activity timeout would trigger, but not before the test timeout expires
tr = Test.AddTestRun("tr-blocking")
tr.Processes.Default.Command = 'curl -i http://127.0.0.1:{0}/blocked {0}'.format(ts.Variables.port)
tr.Processes.Default.TimeOut = 4
tr.Processes.Default.Streams.All = Testers.ContainsExpression(
"HTTP/1.1 502 internal error - server connection terminated", "Connect failed")
tr = Test.AddTestRun("tr-blocking-post")
tr.Processes.Default.Command = 'curl -d "stuff" -i http://127.0.0.1:{0}/blocked {0}'.format(ts.Variables.port)
tr.Processes.Default.TimeOut = 4
tr.Processes.Default.Streams.All = Testers.ContainsExpression(
"HTTP/1.1 502 internal error - server connection terminated", "Connect failed")
# Should not catch the connect timeout. Even though the first bytes are not sent until after the 2 second connect timeout
# But before the no-activity timeout
tr = Test.AddTestRun("tr-delayed")
tr.Setup.Copy('delay-server.sh')
tr.Setup.Copy('case1.sh')
tr.Processes.Default.Command = 'sh ./case1.sh {0} {1}'.format(ts.Variables.port, ts.Variables.upstream_port)
tr.Processes.Default.TimeOut = 7
tr.Processes.Default.Streams.All = Testers.ContainsExpression("HTTP/1.1 200", "Connect succeeded")
# cleanup the network namespace and virtual network
tr = Test.AddTestRun("tr-cleanup")
tr.Processes.Default.Command = 'sudo ip netns del testserver; sudo ip link del veth0 type veth peer name veth1'
tr.Processes.Default.TimeOut = 4
tr = Test.AddTestRun("Wait for the access log to write out")
tr.Processes.Default.StartBefore(server4, ready=When.FileExists(ts.Disk.squid_log))
tr.StillRunningAfter = ts
tr.Processes.Default.Command = 'echo "log file exists"'
tr.Processes.Default.ReturnCode = 0
|
# udacity solution, normaly I would have ordered it, and the traverse it being O(nlogn + N).
# like this is O(2N)
def longest_consecutive_subsequence(input_list):
# Create a dictionary.
# Each element of the input_list would become a "key", and
# the corresponding index in the input_list would become the "value"
element_dict = dict()
# Traverse through the input_list, and populate the dictionary
# Time complexity = O(n)
for index, element in enumerate(input_list):
element_dict[element] = index
# Represents the length of longest subsequence
max_length = -1
# Represents the index of smallest element in the longest subsequence
starts_at = -1
# Traverse again - Time complexity = O(n)
for index, element in enumerate(input_list):
current_starts = index
element_dict[element] = -1 # Mark as visited
current_count = 1 # length of the current subsequence
'''CHECK ONE ELEMENT FORWARD'''
current = element + 1 # `current` is the expected number
# check if the expected number is available (as a key) in the dictionary,
# and it has not been visited yet (i.e., value > 0)
# Time complexity: Constant time for checking a key and retrieving the value = O(1)
while current in element_dict and element_dict[current] > 0:
current_count += 1 # increment the length of subsequence
element_dict[current] = -1 # Mark as visited
current = current + 1
'''CHECK ONE ELEMENT BACKWARD'''
# Time complexity: Constant time for checking a key and retrieving the value = O(1)
current = element - 1 # `current` is the expected number
while current in element_dict and element_dict[current] > 0:
current_starts = element_dict[
current] # index of smallest element in the current subsequence
current_count += 1 # increment the length of subsequence
element_dict[current] = -1
current = current - 1
'''If length of current subsequence >= max length of previously visited subsequence'''
if current_count >= max_length:
if current_count == max_length and current_starts > starts_at:
continue
starts_at = current_starts # index of smallest element in the current (longest so far) subsequence
max_length = current_count # store the length of current (longest so far) subsequence
start_element = input_list[starts_at] # smallest element in the longest subsequence
# return a NEW list starting from `start_element` to `(start_element + max_length)`
return [element for element in range(start_element, start_element + max_length)]
def test_function(test_case):
output = longest_consecutive_subsequence(test_case[0])
if output == test_case[1]:
print("Pass")
else:
print("Fail")
test_case_1 = [[5, 4, 7, 10, 1, 3, 55, 2], [1, 2, 3, 4, 5]]
test_function(test_case_1)
test_case_2 = [[2, 12, 9, 16, 10, 5, 3, 20, 25, 11, 1, 8, 6 ], [8, 9, 10, 11, 12]]
test_function(test_case_2)
test_case_3 = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
test_function(test_case_3) |
# Problem Code: HDIVISR
def highest_divisor(n):
for i in range(10, 0, -1):
if not n % i:
return i
n = int(input())
print(highest_divisor(n))
|
# EJERCICIO 02
# Determina mentalmente (sin programar) el resultado que aparecerá
# por pantalla en las siguientes operaciones con variables:
a = 10
b = -5
c = "Hola "
d = [1, 2, 3]
print(a * 5) #50
print(a - b) #15
print(c + "Mundo") #"Hola Mundo"
print(c * 2) #"Hola" "Hola"
print(d[-1]) #3
print(d[1:]) #2,3
print(d + d) #[1,2,3,1,2,3] |
_settings = None
def set_settings(settings):
global _settings
_settings = settings
def get_settings():
global _settings
return _settings |
# 베르트랑 공준은 임의의 자연수 n에 대하여, n보다 크고, 2n보다 작거나 같은 소수는 적어도 하나 존재한다는 내용을 담고 있다.
#
# 이 명제는 조제프 베르트랑이 1845년에 추측했고, 파프누티 체비쇼프가 1850년에 증명했다.
#
# 예를 들어, 10보다 크고, 20보다 작거나 같은 소수는 4개가 있다. (11, 13, 17, 19) 또, 14보다 크고, 28보다 작거나 같은 소수는 3개가 있다. (17,19, 23)
#
# 자연수 n이 주어졌을 때, n보다 크고, 2n보다 작거나 같은 소수의 개수를 구하는 프로그램을 작성하시오.
# 입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 케이스는 n을 포함하는 한 줄로 이루어져 있다.
#
# 입력의 마지막에는 0이 주어진다.
arr=[True for i in range(250000)]
for i in range(2,500):
j=2
while j*i<250000:
arr[j*i]=False
j+=1
arr[0]=False
arr[1]=False
while True:
ins=int(input())
r=0
for i in range(ins+1,ins*2+1):
if(arr[i]):
r+=1
if(ins==0): break
print(r)
|
# ========================
# Information
# ========================
# Direct Link: https://www.hackerrank.com/challenges/s10-basic-statistics/problem
# Difficulty: Easy
# Max Score: 30
# Language: Python
# ========================
# Solution
# ========================
N = int(input())
NUMBER = list(map(int, input().split()))
# Mean
SUM = 0
for i in NUMBER:
SUM = SUM + i
print(float(SUM / N))
# Median
NUMBER = sorted(NUMBER)
if N % 2 == 0:
A = NUMBER[N//2]
B = NUMBER[N//2 - 1]
print((A+B)/2)
else:
print(NUMBER[N//2])
# Mode
MAX_1 = 0
NUMBER = sorted(NUMBER)
for i in NUMBER:
COUNTER = 0
INDEX = NUMBER.index(i)
for j in range(INDEX, len(NUMBER)):
if i == NUMBER[j]:
COUNTER = COUNTER + 1
if COUNTER > MAX_1:
MAX_1 = COUNTER
if MAX_1 == 1:
MODE = NUMBER[0]
else:
MODE = i
print(MODE)
|
# Module 3 Assignment
# Jordan Phillips
myfile = open("question.txt", "r+")
myquestion = myfile.read()
myresponse = input(myquestion)
myfile.write(myresponse)
myfile.close()
|
favorite_fruits = ['banana', 'orange', 'lemon']
listed_fruits = ['apple', 'banana', 'orange', 'grappe', 'blackberry', 'lemon']
for favorite_fruit in favorite_fruits:
for listed_fruit in listed_fruits:
if listed_fruit == favorite_fruit:
print ("You really like " + listed_fruit)
print ('\n')
for listed_fruit in listed_fruits:
check = False
for favorite_fruit in favorite_fruits:
if favorite_fruit == listed_fruit:
check = True
print ("You reallly like " + listed_fruit)
if check == False:
print ("You really don't like " + listed_fruit)
print ('\n')
for listed_fruit in listed_fruits:
if listed_fruit in favorite_fruits:
print ("You really like " + listed_fruit)
else :
print ("You really don't like " + listed_fruit)
|
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 11 08:47:55 2018
@author: conta
"""
costprice=input()
costprice=int(costprice)
sellprice=input()
sellprice=int(sellprice)
if(costprice<sellprice):
print("Profit")
if(costprice==sellprice):
print("Neither")
if(costprice>sellprice):
print("Loss") |
class script(object):
START_MSG = """
╔┓┏╦━━╦┓╔┓╔━━╗
║┗┛║┗━╣┃║┃║╯╰║
║┏┓║┏━╣┗╣┗╣╰╯║
╚┛┗╩━━╩━╩━╩━━~~~
I'm Baymax
I'm a Simple Yet Powerful bot With Cool Modules. Made by Arosha_Kovida(t.me/Aro_Ediz)
Hit HELP button to find my list of available commands
ᴀʀᴏ|ᴇᴅɪᴢ • ᴘᴜʙʟɪᴄ ᴇᴅɪᴛɪᴏɴ"""
HELP_MSG = """Heya, available commands here!
<code>⚙ /aro </code>[ For download songs ]
Ex: /aro faded
Follow these steps to edit your photos!
<code>⚙ Send me any Image to Edit..</code>
<code>⚙ Select the Corresponding mode that you need</code>
<code>⚙ Your Edited Image will be Uploaded </code>
Enjoy!!!😉👌
ᴀʀᴏ|ᴇᴅɪᴢ • ᴘᴜʙʟɪᴄ ᴇᴅɪᴛɪᴏɴ"""
ABOUT_MSG = """⭕️<b>My Name : The Baymax</b>
⭕️<b>Language :</b> <code>Python3</code>
⭕️<b>Owner :</b> <a href='t.me/Aro_Ediz'>Arosha_Kovida</a>
⭕️<b>Source Code :</b> 👉 <a href='https://github.com/TroJanzHEX/Image-Editor'>Click Here</a>"""
|
numbers = list(map(int, input().split()))
expected = [2, 2, 2, 1.5, 1, 0]
ans = 0
for n, e in zip(numbers, expected):
ans += e * n
print(ans)
|
"""
Wave Gradient
by Ira Greenberg.
Generate a gradient along a sin() wave.
"""
amplitude = 30
fillGap = 2.5
def setup():
size(640, 360)
background(200)
noLoop()
def draw():
frequency = 0
for i in range(-75, height + 75):
# Reset angle to 0, so waves stack properly
angle = 0
# Increasing frequency causes more gaps
frequency += .002
for j in range(0, width + 75):
py = i + sin(radians(angle)) * amplitude
angle += frequency
c = color(abs(py - i) * 255 / amplitude, 255 - abs(py - i)
* 255 / amplitude, j * (255.0 / (width + 50)))
# Hack to fill gaps. Raise value of fillGap if you increase
# frequency
for filler in range(0, int(fillGap)):
set(int(j - filler), int(py) - filler, c)
set(int(j), int(py), c)
set(int(j + filler), int(py) + filler, c)
|
class Student:
def __init__(self):
self.name=input('Enter name')
self.age=int(input('Enter age'))
def display(self):
print(self.name,self.age)
s=Student()
s.display()
|
i4 = Int32Scalar("b4", 2)
i5 = Int32Scalar("b5", 2)
i6 = Int32Scalar("b6", 2)
i7 = Int32Scalar("b7", 0)
i2 = Input("op2", "TENSOR_QUANT8_ASYMM", "{1, 2, 2, 1}") # input 0
i3 = Output("op3", "TENSOR_QUANT8_ASYMM", "{1, 1, 1, 1}") # output 0
i0 = Parameter("op0", "TENSOR_QUANT8_ASYMM", "{1, 2, 2, 1}", [1, 1, 1, 1]) # parameters
i1 = Parameter("op1", "TENSOR_INT32", "{1}", [0]) # parameters
model = Model()
model = model.Conv(i2, i0, i1, i4, i5, i6, i7).To(i3)
|
# -*- coding: utf-8 -*-
translations = {
# Days
'days': {
0: 'sunnuntai',
1: 'maanantai',
2: 'tiistai',
3: 'keskiviikko',
4: 'torstai',
5: 'perjantai',
6: 'lauantai'
},
'days_abbrev': {
0: 'su',
1: 'ma',
2: 'ti',
3: 'ke',
4: 'to',
5: 'pe',
6: 'la'
},
# Months
'months': {
1: 'tammikuu',
2: 'helmikuu',
3: 'maaliskuu',
4: 'huhtikuu',
5: 'toukokuu',
6: 'kesäkuu',
7: 'heinäkuu',
8: 'elokuu',
9: 'syyskuu',
10: 'lokakuu',
11: 'marraskuu',
12: 'joulukuu',
},
'months_abbrev': {
1: 'tammi',
2: 'helmi',
3: 'maalis',
4: 'huhti',
5: 'touko',
6: 'kesä',
7: 'heinä',
8: 'elo',
9: 'syys',
10: 'loka',
11: 'marras',
12: 'joulu',
},
# Units of time
'year': ['{count} vuosi', '{count} vuotta'],
'month': ['{count} kuukausi', '{count} kuukautta'],
'week': ['{count} viikko', '{count} viikkoa'],
'day': ['{count} päivä', '{count} päivää'],
'hour': ['{count} tunti', '{count} tuntia'],
'minute': ['{count} minuutti', '{count} minuuttia'],
'second': ['{count} sekunti', '{count} sekuntia'],
# Relative time
'ago': '{time} sitten',
'from_now': '{time} tästä hetkestä',
'after': '{time} sen jälkeen',
'before': '{time} ennen',
# Date formats
'date_formats': {
'LTS': 'HH.mm.ss',
'LT': 'HH.mm',
'LLLL': 'dddd, Do MMMM[ta] YYYY, [klo] HH.mm',
'LLL': 'Do MMMM[ta] YYYY, [klo] HH.mm',
'LL': 'Do MMMM[ta] YYYY',
'L': 'DD.MM.YYYY',
},
}
|
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2021 plun1331
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
class APIKey(object):
r"""Represents an API Key.
:param key_data: The raw key data from the API.
:type key_data: dict
:param cached: The raw key data from the API.
:type cached: bool
:param hypixel: The raw key data from the API.
:type hypixel: PyPixel.Hypixel.Hypixel"""
def __init__(self, key_data: dict, cached, hypixel):
self.cached = cached
self._hypixel = hypixel
self.key = key_data['key']
self.owner = key_data['owner']
self.ratelimit = key_data['limit']
self.request_past_minute = key_data['queriesInPastMin']
self.total_requests = key_data['totalQueries']
async def get_owner(self):
r"""|coro|
Gets the owner pf the key as a Player object.
:return: The key's owner.
:rtype: PyPixel.Player.Player"""
return await self._hypixel.get_player(self.owner)
|
# ----------------------------------------------------------------
# SUNDIALS Copyright Start
# Copyright (c) 2002-2022, Lawrence Livermore National Security
# and Southern Methodist University.
# All rights reserved.
#
# See the top-level LICENSE and NOTICE files for details.
#
# SPDX-License-Identifier: BSD-3-Clause
# SUNDIALS Copyright End
# ----------------------------------------------------------------
sundials_version = 'v6.1.1'
arkode_version = 'v5.1.1'
cvode_version = 'v6.1.1'
cvodes_version = 'v6.1.1'
ida_version = 'v6.1.1'
idas_version = 'v5.1.1'
kinsol_version = 'v6.1.1'
|
# Time: O(k * (m + n + k)) ~ O(k * (m + n + k^2))
# Space: O(m + n + k^2)
class Solution(object):
def maxNumber(self, nums1, nums2, k):
"""
:type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[int]
"""
def get_max_digits(nums, start, end, max_digits):
max_digits[end] = max_digit(nums, end)
for i in reversed(range(start, end)):
max_digits[i] = delete_digit(max_digits[i + 1])
def max_digit(nums, k):
drop = len(nums) - k
res = []
for num in nums:
while drop and res and res[-1] < num:
res.pop()
drop -= 1
res.append(num)
return res[:k]
def delete_digit(nums):
res = list(nums)
for i in range(len(res)):
if i == len(res) - 1 or res[i] < res[i + 1]:
res = res[:i] + res[i+1:]
break
return res
def merge(a, b):
return [max(a, b).pop(0) for _ in range(len(a)+len(b))]
m, n = len(nums1), len(nums2)
max_digits1, max_digits2 = [[] for _ in range(k + 1)], [[] for _ in range(k + 1)]
get_max_digits(nums1, max(0, k - n), min(k, m), max_digits1)
get_max_digits(nums2, max(0, k - m), min(k, n), max_digits2)
return max(merge(max_digits1[i], max_digits2[k-i]) \
for i in range(max(0, k - n), min(k, m) + 1))
|
# Captain's Quarters (106030800)
blackViking = 3300110
sm.spawnMob(blackViking) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-03-06
Last_modify: 2016-03-06
******************************************
'''
'''
Given a binary tree,
return the zigzag level order traversal of its nodes' values.
(ie, from left to right, then right to left for the next
level and alternate between).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
'''
# 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 zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
q1 = [root]
q2 = []
levels = []
while q1:
level = []
while q1:
cur = q1.pop()
level.append(cur.val)
if cur.left:
q2.append(cur.left)
if cur.right:
q2.append(cur.right)
levels.append(level)
level = []
while q2:
cur = q2.pop()
level.append(cur.val)
if cur.right:
q1.append(cur.right)
if cur.left:
q1.append(cur.left)
if level:
levels.append(level)
return levels
|
"""
Cadaster system in Chicago as of 2014
based on https://nationalmap.gov/small_scale/a_plss.html
"""
'''
Survery Township
The Public Land Survey System (PLSS) forms the foundation of
Cook County's cadastral system for identifying and locating
land records. Tax parcels are identified using township and
section notation, in a modified format. This PLSS feature data
set is intended to correspond to tax pages in the Cook County
Assessor's Tax Map book (current as of tax year 2000 for 66%
of the County and as of tax year 2001 for the remaining 33%
of the County), and should not be used for measurement or
surveyor purposes. In addition, the parcel attributes PINA
(area/township) and PINSA (subarea/section) do not necessarily
correspond to the PLSS township and section polygon in which
a given parcel resides. The PLSS data is modeled as a single
composite network coverage that encompasses townships (area),
sections (subarea), quarter sections, and half quarter section.
'''
# Survey Township https://datacatalog.cookcountyil.gov/resource/iz5k-qtpu.json
'''
PLSS Line
The County's system of tax maps is based on the Illinois
Public Land Survey System (PLSS). In the PLSS, each township
is divided into 36 sections, and each section into four
quarter-sections. A quarter-section is further divided into
two tax map sheets, often called "pages". Each tax map
(1/4 mile by 1/2 mile) represents the east or west half of
one quarter-section, and typically there are eight tax maps
per section.
'''
# PLSS Line https://datacatalog.cookcountyil.gov/resource/yvw8-g53g.json
'''
Section
The PLSS data is modeled as a single composite network
coverage that encompasses townships (area), sections (subarea),
quarter sections, and half quarter section. If an indigenous
people's reserve was present on the tax map, it was digitized
to create subpolygons of the half-quarter section, and those
polygons were attributed with the name of the reserve. Within
this PLSS data set, a half-quarter section is the smallest
polygon unit, except in cases where an Indigenous People's
Reserve line is present.
'''
# Section https://datacatalog.cookcountyil.gov/resource/xhzu-6w77.json
'''
Unincorporated Zoning by Parcel
This is a Cook County Feature class of Unincorporated Zoning
District Boundaries by parcel. This data is provided by the
Cook County Dept. Of Building and Zoning and is maintained by
the Cook County Zoning Board of Appeals.
Only unincorporated district boundaries are available, please
contact specific municipalities for questions regarding
incorporated municipal zoning districts.
'''
# https://datacatalog.cookcountyil.gov/resource/yski-9fq7.json
'''
Unincorporated Zoning districts
This is a Cook County Feature class of Unincorporated Zoning
District Boundaries (Aggregate). This data is provided by the
Cook County Dept. Of Building and Zoning and is maintained by
the Cook County Zoning Board of Appeals.
Only unincorporated district boundaries are available, please
contact specific municipalities for questions regarding
incorporated municipal zoning districts.
'''
# https://datacatalog.cookcountyil.gov/resource/jwue-cxuq.json
'''
Community Areas
'''
# https://data.cityofchicago.org/resource/igwz-8jzy.json
'''
Wards 2015
'''
# https://data.cityofchicago.org/resource/k9yb-bpqx.json
# requests and
# https://www.digitalocean.com/community/tutorials/how-to-use-web-apis-in-python-3
# api_url = '{}orgs/{}/repos'.format(api_url_base, username) |
# zadanie 1
# Wygeneruj liczby podzielne przez 4 i zapisz je do pliku.
plik = open('zadanie_1.txt', 'w')
for i in range(0, 1000, 1):
plik.write(str(i*4)+'\n')
plik.close() |
# File: forescoutcounteract_consts.py
#
# Copyright (c) 2018-2022 Splunk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under
# the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific language governing permissions
# and limitations under the License.
#
#
# Define your constants here
FS_DEX_HOST_ENDPOINT = '/fsapi/niCore/Hosts'
FS_DEX_LIST_ENDPOINT = '/fsapi/niCore/Lists'
FS_DEX_TEST_CONNECTIVITY = \
"""<?xml version="1.0" encoding="UTF-8"?>
<FSAPI TYPE="request" API_VERSION="1.0">
<TRANSACTION TYPE="update">
<OPTIONS CREATE_NEW_HOST="true"/>
<HOST_KEY NAME="ip" VALUE="{host_key_value}"/>
<PROPERTIES></PROPERTIES>
</TRANSACTION>
</FSAPI>"""
FS_DEX_UPDATE_SIMPLE_PROPERTY = \
"""<?xml version='1.0' encoding='utf-8'?>
<FSAPI TYPE="request" API_VERSION="1.0">
<TRANSACTION TYPE="update">
<OPTIONS CREATE_NEW_HOST="{create_host}"/>
<HOST_KEY NAME="{host_key_name}" VALUE="{host_key_value}"/>
<PROPERTIES>
<PROPERTY NAME="{property_name}">
<VALUE>{property_value}</VALUE>
</PROPERTY>
</PROPERTIES>
</TRANSACTION>
</FSAPI>"""
FS_DEX_DELETE_SIMPLE_PROPERTY = \
"""<?xml version='1.0' encoding='utf-8'?>
<FSAPI TYPE="request" API_VERSION="1.0">
<TRANSACTION TYPE="delete">
<HOST_KEY NAME="{host_key_name}" VALUE="{host_key_value}"/>
<PROPERTIES>
<PROPERTY NAME="{property_name}" />
</PROPERTIES>
</TRANSACTION>
</FSAPI>"""
FS_DEX_UPDATE_LIST_PROPERTY = \
"""<?xml version="1.0" encoding="UTF-8"?>
<FSAPI TYPE="request" API_VERSION="2.0">
<TRANSACTION TYPE="{transaction_type}">
<LISTS>
{list_body}
</LISTS>
</TRANSACTION>
</FSAPI>"""
FS_WEB_LOGIN = '/api/login'
FS_WEB_HOSTS = '/api/hosts'
FS_WEB_HOSTFIELDS = '/api/hostfields'
FS_WEB_POLICIES = '/api/policies'
# Error message constants
FS_ERR_CODE_MSG = "Error code unavailable"
FS_ERR_MSG_UNAVAILABLE = "Error message unavailable. Please check the asset configuration and|or action parameters"
FS_PARSE_ERR_MSG = "Unable to parse the error message. Please check the asset configuration and|or action parameters"
# validate integer
ERR_VALID_INT_MSG = "Please provide a valid integer value in the {}"
ERR_NON_NEG_INT_MSG = "Please provide a valid non-negative integer value in the {}"
ERR_POSITIVE_INTEGER_MSG = "Please provide a valid non-zero positive integer value in the {}"
HOST_ID_INT_PARAM = "'host_id' action parameter"
# Timeout
FS_DEFAULT_TIMEOUT = 30
|
def find_secret_message(paragraph):
unique = set()
result = []
for word in (a.strip('.,:!?').lower() for a in paragraph.split()):
if word in unique and word not in result:
result.append(word)
unique.add(word)
return ' '.join(result)
|
class EntityNotFoundException(Exception):
pass
class SessionExpiredException(Exception):
pass
|
def main():
NAME = input("What is your name?: ")
print("Hello "+ str(NAME) + "!")
if __name__ == '__main__':
main() |
#ipaddress validation
def ip_val(ipadd):
l=ipadd.split(".")
if len(l)!=4:
return False
for i in l:
if int(i) not in range(256):
return False
return True
print(ip_val("192.168.0.1"))
print(ip_val("192.168.0.1.1"))
print(ip_val("192.168.258.1"))
|
peso = 0
pesos = []
for temp in range(0, 5):
temp += 1
peso = input("Digite o peso da pessoa Nº {}: " .format(temp))
|
class Solution:
def XXX(self, digits: List[int]) -> List[int]:
digits = [str(i) for i in digits]
s = str(int(''.join(digits))+1)
ans = [int(i) for i in s]
return ans
|
X,Y,x,y=map(int,input().split())
while 1:
d=""
if y>Y:d+="N";y-=1
if y<Y:d+="S";y+=1
if x>X:d+="W";x-=1
if x<X:d+="E";x+=1
print(d)
|
with open("Input.txt", "r") as fp:
lines = fp.readlines()
# remove whitespace characters like `\n` at the end of each line
lines = [x.strip() for x in lines]
# clockwise
# N
# W E
# S
directions = [(1, 0), (0, -1), (-1, 0), (0, 1)]
cur_direction = 0 # East
pos_x, pos_y = (0, 0)
for line in lines:
instr, val = line[:1], int(line[1:])
print(f"{instr}, {val}")
if instr == 'F':
pos_x += directions[cur_direction][0] * val
pos_y += directions[cur_direction][1] * val
if instr == 'E':
pos_x += val
if instr == 'S':
pos_y -= val
if instr == 'W':
pos_x -= val
if instr == 'N':
pos_y += val
if instr == 'R':
if val == 90:
cur_direction = (cur_direction + 1) % 4
elif val == 180:
cur_direction = (cur_direction + 2) % 4
elif val == 270:
cur_direction = (cur_direction + 3) % 4
else:
print(f"UNKNOSN R {val}")
raise Exception
if instr == 'L':
if val == 90:
cur_direction = (cur_direction - 1 + 4) % 4
elif val == 180:
cur_direction = (cur_direction - 2 + 4) % 4
elif val == 270:
cur_direction = (cur_direction - 3 + 4) % 4
else:
print(f"UNKNOSN R {val}")
raise Exception
print(f"pos= {pos_x}, {pos_y}")
print(f"solution1 = {abs(pos_x) + abs(pos_y)}") # 2847
|
# You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other
# items. We want to create the text that should be displayed next to such an item.
#
# Implement a function likes :: [String] -> String, which must take in input array, containing the names of people
# who like an item. It must return the display text as shown in the examples:
#
# likes([]) # must be "no one likes this"
# likes(["Peter"]) # must be "Peter likes this"
# likes(["Jacob", "Alex"]) # must be "Jacob and Alex like this"
# likes(["Max", "John", "Mark"]) # must be "Max, John and Mark like this"
# likes(["Alex", "Jacob", "Mark", "Max"]) # must be "Alex, Jacob and 2 others like this"
# For 4 or more names, the number in and 2 others simply increases.
def likes(names):
if not names:
return "no one likes this"
elif len(names) == 1:
return names[0] + " likes this"
elif len(names) == 2:
return names[0] + " and " + names[1] + " like this"
elif len(names) == 3:
return names[0] + ", " + names[1] + " and " + names[2] + " like this"
else:
return names[0] + ", " + names[1] + " and " + str(len(names)-2) + " others like this"
|
"""
Probably will roll a wxPython front end because web frameworks
hurt my soul, while Qt-esque front ends are only extraordinarily
annoying and repetitive nightmares written in some semblance of
python.
"""
|
class Solution:
def isValid(self, s: str) -> bool:
ans = list()
for x in s:
if x in ['(', '{', '[']:
ans.append(x)
elif x == ')':
if len(ans) < 1:
return False
if ans[-1] == '(':
ans.pop(-1)
else:
return False
elif x == ']':
if len(ans) < 1:
return False
if ans[-1] == '[':
ans.pop(-1)
else:
return False
elif x == '}':
if len(ans) < 1:
return False
if ans[-1] == '{':
ans.pop(-1)
else:
return False
if len(ans) > 0:
return False
return True
|
COMMON = 'http://www.webex.com/schemas/2002/06/common'
SERVICE = 'http://www.webex.com/schemas/2002/06/service'
EP = '%s/ep' % SERVICE
EVENT = '%s/event' % SERVICE
ATTENDEE = '%s/attendee' % SERVICE
HISTORY = '%s/history' % SERVICE
SITE = '%s/site' % SERVICE
PREFIXES = {
'com': COMMON,
'serv': SERVICE,
'ep': EP,
'event': EVENT,
'att': ATTENDEE,
'history': HISTORY,
'site': SITE
}
|
blosum ={
"SW": -3,
"GG": 6,
"EM": -2,
"AN": -2,
"AY": -2,
"WQ": -2,
"VN": -3,
"FK": -3,
"GE": -2,
"ED": 2,
"WP": -4,
"IT": -1,
"FD": -3,
"KV": -2,
"CY": -2,
"GD": -1,
"TN": 0,
"WW": 11,
"SS": 4,
"KC": -3,
"EF": -3,
"NL": -3,
"AK": -1,
"QP": -1,
"FG": -3,
"DS": 0,
"CV": -1,
"VT": 0,
"HP": -2,
"PV": -2,
"IQ": -3,
"FV": -1,
"WT": -2,
"HF": -1,
"PD": -1,
"QR": 1,
"DQ": 0,
"KQ": 1,
"DF": -3,
"VW": -3,
"TC": -1,
"AF": -2,
"TH": -2,
"AQ": -1,
"QT": -1,
"VF": -1,
"FC": -2,
"CR": -3,
"VP": -2,
"HT": -2,
"EL": -3,
"FR": -3,
"IG": -4,
"CQ": -3,
"YV": -1,
"TA": 0,
"TV": 0,
"QV": -2,
"SK": 0,
"KK": 5,
"EN": 0,
"NT": 0,
"AH": -2,
"AC": 0,
"VS": -2,
"QH": 0,
"HS": -1,
"QY": -1,
"PN": -2,
"IY": -1,
"PG": -2,
"FN": -3,
"HN": 1,
"KH": -1,
"NW": -4,
"SY": -2,
"WN": -4,
"DY": -3,
"EQ": 2,
"KY": -2,
"SG": 0,
"YS": -2,
"GR": -2,
"AL": -1,
"AG": 0,
"TK": -1,
"TP": -1,
"MV": 1,
"QL": -2,
"ES": 0,
"HW": -2,
"ID": -3,
"KF": -3,
"NA": -2,
"TI": -1,
"QN": 0,
"KW": -3,
"SC": -1,
"YY": 7,
"GV": -3,
"LV": 1,
"AR": -1,
"MR": -1,
"YL": -1,
"DC": -3,
"PP": 7,
"DH": -1,
"QQ": 5,
"IV": 3,
"PF": -4,
"IA": -1,
"FF": 6,
"KT": -1,
"LT": -1,
"SQ": 0,
"WF": 1,
"DA": -2,
"EY": -2,
"KA": -1,
"QS": 0,
"AD": -2,
"LR": -2,
"TS": 1,
"AV": 0,
"MN": -2,
"QD": 0,
"EP": -1,
"VV": 4,
"DN": 1,
"IS": -2,
"PM": -2,
"HD": -1,
"IL": 2,
"KN": 0,
"LP": -3,
"YI": -1,
"NI": -3,
"TQ": -1,
"QF": -3,
"SM": -1,
"ER": 0,
"QW": -2,
"GN": 0,
"LY": -1,
"LN": -3,
"AS": 1,
"DT": -1,
"ST": 1,
"PS": -1,
"VR": -3,
"DK": -1,
"PH": -2,
"HC": -3,
"QI": -3,
"HH": 8,
"II": 4,
"LW": -2,
"LL": 4,
"DR": -2,
"SI": -2,
"DI": -3,
"EA": -1,
"KI": -3,
"QK": 1,
"TD": -1,
"AW": -3,
"YR": -2,
"MF": 0,
"SP": -1,
"HQ": 0,
"YN": -2,
"IP": -3,
"EC": -4,
"HG": -2,
"PE": -1,
"QM": 0,
"HL": -3,
"LS": -2,
"LH": -3,
"NQ": 0,
"TY": -2,
"KG": -2,
"SE": 0,
"YE": -2,
"WR": -3,
"VM": 1,
"NR": 0,
"GF": -3,
"FY": 3,
"LQ": -2,
"MY": -1,
"AP": -1,
"SN": 1,
"CL": -1,
"LF": 0,
"DW": -4,
"SL": -2,
"PR": -2,
"PK": -1,
"YG": -3,
"CK": -3,
"HK": -1,
"QA": -1,
"IF": 0,
"KD": -1,
"NC": -3,
"LD": -4,
"YK": -2,
"SA": 1,
"WV": -3,
"EI": -3,
"VI": 3,
"QC": -3,
"TG": -2,
"TL": -1,
"LM": 2,
"AT": 0,
"CH": -3,
"PY": -3,
"SH": -1,
"HY": 2,
"EK": 1,
"CG": -3,
"IC": -1,
"QE": 2,
"KR": 2,
"TE": -1,
"LK": -2,
"MW": -1,
"NY": -2,
"NH": 1,
"VE": -2,
"QG": -2,
"YD": -3,
"FQ": -3,
"GY": -3,
"LI": 2,
"MQ": 0,
"RA": -1,
"CD": -3,
"SV": -2,
"DD": 6,
"SD": 0,
"PC": -3,
"CC": 9,
"WK": -3,
"IN": -3,
"KL": -2,
"NK": 0,
"LG": -4,
"MS": -1,
"RC": -3,
"RD": -2,
"VA": 0,
"WI": -3,
"TT": 5,
"FM": 0,
"LE": -3,
"MM": 5,
"RE": 0,
"WH": -2,
"SR": -1,
"EW": -3,
"PQ": -1,
"HA": -2,
"YA": -2,
"EH": 0,
"RF": -3,
"IK": -3,
"NE": 0,
"TM": -1,
"TR": -1,
"MT": -1,
"GS": 0,
"LC": -1,
"RG": -2,
"YM": -1,
"NF": -3,
"YQ": -1,
"NP": -2,
"RH": 0,
"WM": -1,
"CN": -3,
"VL": 1,
"FI": 0,
"GQ": -2,
"LA": -1,
"MI": 1,
"RI": -3,
"WL": -2,
"DG": -1,
"DL": -4,
"IR": -3,
"CM": -1,
"HE": 0,
"YW": 2,
"GP": -2,
"WC": -2,
"MP": -2,
"NS": 1,
"GW": -2,
"MK": -1,
"RK": 2,
"DE": 2,
"KE": 1,
"RL": -2,
"AI": -1,
"VY": -1,
"WA": -3,
"YF": 3,
"TW": -2,
"VH": -3,
"FE": -3,
"ME": -2,
"RM": -1,
"ET": -1,
"HR": 0,
"PI": -3,
"FT": -2,
"CI": -1,
"HI": -3,
"GT": -2,
"IH": -3,
"RN": 0,
"CW": -2,
"WG": -2,
"NM": -2,
"ML": 2,
"GK": -2,
"MG": -3,
"KS": 0,
"EV": -2,
"NN": 6,
"VK": -2,
"RP": -2,
"AM": -1,
"WE": -3,
"FW": 1,
"CF": -2,
"VD": -3,
"FA": -2,
"GI": -4,
"MA": -1,
"RQ": 1,
"CT": -1,
"WD": -4,
"HV": -3,
"SF": -2,
"PT": -1,
"FP": -4,
"CE": -4,
"HM": -2,
"IE": -3,
"GH": -2,
"RR": 5,
"KP": -1,
"CS": -1,
"DV": -3,
"MH": -2,
"MC": -1,
"RS": -1,
"DM": -3,
"EE": 5,
"KM": -1,
"VG": -3,
"RT": -1,
"AA": 4,
"VQ": -2,
"WY": 2,
"FS": -2,
"GM": -3,
"CP": -3,
"EG": -2,
"IW": -3,
"PA": -1,
"FL": 0,
"CA": 0,
"GL": -4,
"RV": -3,
"TF": -2,
"YP": -3,
"MD": -3,
"GC": -3,
"RW": -3,
"ND": 1,
"NV": -3,
"VC": -1,
"AE": -1,
"YH": 2,
"DP": -1,
"GA": 0,
"RY": -2,
"PW": -4,
"YC": -2,
"PL": -3,
"FH": -1,
"IM": 1,
"YT": -2,
"NG": 0,
"WS": -3
}
adj_blosum = {
b"AA": 0,
b"AC": 4,
b"AD": 4,
b"AE": 4,
b"AF": 4,
b"AG": 4,
b"AH": 4,
b"AI": 4,
b"AK": 4,
b"AL": 4,
b"AM": 4,
b"AN": 4,
b"AP": 4,
b"AQ": 4,
b"AR": 4,
b"AS": 3,
b"AT": 4,
b"AV": 4,
b"AW": 4,
b"AY": 4,
b"CA": 4,
b"CC": 0,
b"CD": 4,
b"CE": 4,
b"CF": 4,
b"CG": 4,
b"CH": 4,
b"CI": 4,
b"CK": 4,
b"CL": 4,
b"CM": 4,
b"CN": 4,
b"CP": 4,
b"CQ": 4,
b"CR": 4,
b"CS": 4,
b"CT": 4,
b"CV": 4,
b"CW": 4,
b"CY": 4,
b"DA": 4,
b"DC": 4,
b"DD": 0,
b"DE": 2,
b"DF": 4,
b"DG": 4,
b"DH": 4,
b"DI": 4,
b"DK": 4,
b"DL": 4,
b"DM": 4,
b"DN": 3,
b"DP": 4,
b"DQ": 4,
b"DR": 4,
b"DS": 4,
b"DT": 4,
b"DV": 4,
b"DW": 4,
b"DY": 4,
b"EA": 4,
b"EC": 4,
b"ED": 2,
b"EE": 0,
b"EF": 4,
b"EG": 4,
b"EH": 4,
b"EI": 4,
b"EK": 3,
b"EL": 4,
b"EM": 4,
b"EN": 4,
b"EP": 4,
b"EQ": 2,
b"ER": 4,
b"ES": 4,
b"ET": 4,
b"EV": 4,
b"EW": 4,
b"EY": 4,
b"FA": 4,
b"FC": 4,
b"FD": 4,
b"FE": 4,
b"FF": 0,
b"FG": 4,
b"FH": 4,
b"FI": 4,
b"FK": 4,
b"FL": 4,
b"FM": 4,
b"FN": 4,
b"FP": 4,
b"FQ": 4,
b"FR": 4,
b"FS": 4,
b"FT": 4,
b"FV": 4,
b"FW": 3,
b"FY": 1,
b"GA": 4,
b"GC": 4,
b"GD": 4,
b"GE": 4,
b"GF": 4,
b"GG": 0,
b"GH": 4,
b"GI": 4,
b"GK": 4,
b"GL": 4,
b"GM": 4,
b"GN": 4,
b"GP": 4,
b"GQ": 4,
b"GR": 4,
b"GS": 4,
b"GT": 4,
b"GV": 4,
b"GW": 4,
b"GY": 4,
b"HA": 4,
b"HC": 4,
b"HD": 4,
b"HE": 4,
b"HF": 4,
b"HG": 4,
b"HH": 0,
b"HI": 4,
b"HK": 4,
b"HL": 4,
b"HM": 4,
b"HN": 3,
b"HP": 4,
b"HQ": 4,
b"HR": 4,
b"HS": 4,
b"HT": 4,
b"HV": 4,
b"HW": 4,
b"HY": 2,
b"IA": 4,
b"IC": 4,
b"ID": 4,
b"IE": 4,
b"IF": 4,
b"IG": 4,
b"IH": 4,
b"II": 0,
b"IK": 4,
b"IL": 2,
b"IM": 3,
b"IN": 4,
b"IP": 4,
b"IQ": 4,
b"IR": 4,
b"IS": 4,
b"IT": 4,
b"IV": 1,
b"IW": 4,
b"IY": 4,
b"KA": 4,
b"KC": 4,
b"KD": 4,
b"KE": 3,
b"KF": 4,
b"KG": 4,
b"KH": 4,
b"KI": 4,
b"KK": 0,
b"KL": 4,
b"KM": 4,
b"KN": 4,
b"KP": 4,
b"KQ": 3,
b"KR": 2,
b"KS": 4,
b"KT": 4,
b"KV": 4,
b"KW": 4,
b"KY": 4,
b"LA": 4,
b"LC": 4,
b"LD": 4,
b"LE": 4,
b"LF": 4,
b"LG": 4,
b"LH": 4,
b"LI": 2,
b"LK": 4,
b"LL": 0,
b"LM": 2,
b"LN": 4,
b"LP": 4,
b"LQ": 4,
b"LR": 4,
b"LS": 4,
b"LT": 4,
b"LV": 3,
b"LW": 4,
b"LY": 4,
b"MA": 4,
b"MC": 4,
b"MD": 4,
b"ME": 4,
b"MF": 4,
b"MG": 4,
b"MH": 4,
b"MI": 3,
b"MK": 4,
b"ML": 2,
b"MM": 0,
b"MN": 4,
b"MP": 4,
b"MQ": 4,
b"MR": 4,
b"MS": 4,
b"MT": 4,
b"MV": 3,
b"MW": 4,
b"MY": 4,
b"NA": 4,
b"NC": 4,
b"ND": 3,
b"NE": 4,
b"NF": 4,
b"NG": 4,
b"NH": 3,
b"NI": 4,
b"NK": 4,
b"NL": 4,
b"NM": 4,
b"NN": 0,
b"NP": 4,
b"NQ": 4,
b"NR": 4,
b"NS": 3,
b"NT": 4,
b"NV": 4,
b"NW": 4,
b"NY": 4,
b"PA": 4,
b"PC": 4,
b"PD": 4,
b"PE": 4,
b"PF": 4,
b"PG": 4,
b"PH": 4,
b"PI": 4,
b"PK": 4,
b"PL": 4,
b"PM": 4,
b"PN": 4,
b"PP": 0,
b"PQ": 4,
b"PR": 4,
b"PS": 4,
b"PT": 4,
b"PV": 4,
b"PW": 4,
b"PY": 4,
b"QA": 4,
b"QC": 4,
b"QD": 4,
b"QE": 2,
b"QF": 4,
b"QG": 4,
b"QH": 4,
b"QI": 4,
b"QK": 3,
b"QL": 4,
b"QM": 4,
b"QN": 4,
b"QP": 4,
b"QQ": 0,
b"QR": 3,
b"QS": 4,
b"QT": 4,
b"QV": 4,
b"QW": 4,
b"QY": 4,
b"RA": 4,
b"RC": 4,
b"RD": 4,
b"RE": 4,
b"RF": 4,
b"RG": 4,
b"RH": 4,
b"RI": 4,
b"RK": 2,
b"RL": 4,
b"RM": 4,
b"RN": 4,
b"RP": 4,
b"RQ": 3,
b"RR": 0,
b"RS": 4,
b"RT": 4,
b"RV": 4,
b"RW": 4,
b"RY": 4,
b"SA": 3,
b"SC": 4,
b"SD": 4,
b"SE": 4,
b"SF": 4,
b"SG": 4,
b"SH": 4,
b"SI": 4,
b"SK": 4,
b"SL": 4,
b"SM": 4,
b"SN": 3,
b"SP": 4,
b"SQ": 4,
b"SR": 4,
b"SS": 0,
b"ST": 3,
b"SV": 4,
b"SW": 4,
b"SY": 4,
b"TA": 4,
b"TC": 4,
b"TD": 4,
b"TE": 4,
b"TF": 4,
b"TG": 4,
b"TH": 4,
b"TI": 4,
b"TK": 4,
b"TL": 4,
b"TM": 4,
b"TN": 4,
b"TP": 4,
b"TQ": 4,
b"TR": 4,
b"TS": 3,
b"TT": 0,
b"TV": 4,
b"TW": 4,
b"TY": 4,
b"VA": 4,
b"VC": 4,
b"VD": 4,
b"VE": 4,
b"VF": 4,
b"VG": 4,
b"VH": 4,
b"VI": 1,
b"VK": 4,
b"VL": 3,
b"VM": 3,
b"VN": 4,
b"VP": 4,
b"VQ": 4,
b"VR": 4,
b"VS": 4,
b"VT": 4,
b"VV": 0,
b"VW": 4,
b"VY": 4,
b"WA": 4,
b"WC": 4,
b"WD": 4,
b"WE": 4,
b"WF": 3,
b"WG": 4,
b"WH": 4,
b"WI": 4,
b"WK": 4,
b"WL": 4,
b"WM": 4,
b"WN": 4,
b"WP": 4,
b"WQ": 4,
b"WR": 4,
b"WS": 4,
b"WT": 4,
b"WV": 4,
b"WW": 0,
b"WY": 2,
b"YA": 4,
b"YC": 4,
b"YD": 4,
b"YE": 4,
b"YF": 1,
b"YG": 4,
b"YH": 2,
b"YI": 4,
b"YK": 4,
b"YL": 4,
b"YM": 4,
b"YN": 4,
b"YP": 4,
b"YQ": 4,
b"YR": 4,
b"YS": 4,
b"YT": 4,
b"YV": 4,
b"YW": 2,
b"YY": 0
} |
"""
Constants file
"""
ACCESS_TOKEN_KEY = 'access_token'
API_ID = 'API_ID'
APP_JSON_KEY = 'application/json'
AUTH0_AUDIENCE = 'AUTH0_AUDIENCE'
AUTH0_AUDIENCE_MNGNMT_API = 'AUTH0_AUDIENCE_MNGNMT_API'
AUTH0_CALLBACK_URL = 'AUTH0_CALLBACK_URL'
AUTH0_CLIENT_ID = 'AUTH0_CLIENT_ID'
AUTH0_CLIENT_SECRET = 'AUTH0_CLIENT_SECRET'
AUTH0_CLIENT_ID_MNGNMT_API = 'AUTH0_CLIENT_ID_MNGNMT_API'
AUTH0_CLIENT_SECRET_MNGNMT_API = 'AUTH0_CLIENT_SECRET_MNGNMT_API'
AUTH0_DOMAIN = 'AUTH0_DOMAIN'
AUTHORIZATION_CODE_KEY = 'authorization_code'
CLIENT_ID_KEY = 'client_id'
CLIENT_SECRET_KEY = 'client_secret'
CLIENTS_PAYLOAD = 'clients'
CODE_KEY = 'code'
CONTENT_TYPE_KEY = 'content-type'
GRANT_TYPE = 'GRANT_TYPE'
GRANT_TYPE_KEY = 'grant_type'
JWT_PAYLOAD = 'jwt_payload'
PROFILE_KEY = 'profile'
REDIRECT_URI_KEY = 'redirect_uri'
RULES_PAYLOAD = 'rules'
SECRET_KEY = 'ThisIsTheSecretKey'
|
ALL = [
"add_logentry",
"change_logentry",
"delete_logentry",
"view_logentry",
"can_export_data",
"can_import_historical",
"can_import_third_party",
"can_import_website",
"add_donation",
"change_donation",
"delete_donation",
"destroy_donation",
"generate_tax_receipt",
"view_donation",
"add_donor",
"change_donor",
"delete_donor",
"destroy_donor",
"view_donor",
"add_item",
"change_item",
"delete_item",
"destroy_item",
"update_status_item",
"update_value_item",
"view_item",
"add_itemdevice",
"change_itemdevice",
"delete_itemdevice",
"view_itemdevice",
"add_itemdevicetype",
"change_itemdevicetype",
"delete_itemdevicetype",
"view_itemdevicetype",
"add_group",
"change_group",
"delete_group",
"view_group",
"add_permission",
"change_permission",
"delete_permission",
"view_permission",
"add_user",
"change_user",
"delete_user",
"view_user",
"add_contenttype",
"change_contenttype",
"delete_contenttype",
"view_contenttype",
"add_session",
"change_session",
"delete_session",
"view_session",
]
FRONTLINE = [
'add_donation',
'change_donation',
'delete_donation',
'view_donation',
'add_donor',
'change_donor',
'delete_donor',
'view_donor',
'add_item',
'change_item',
'delete_item',
'view_item',
'add_itemdevice',
'change_itemdevice',
'delete_itemdevice',
'add_itemdevicetype',
'change_itemdevicetype',
'delete_itemdevicetype',
]
MANAGEMENT = FRONTLINE + [
'can_import_historical',
'can_import_third_party',
'can_import_website',
'can_export_data',
'generate_tax_receipt',
'update_status_item',
'update_value_item',
'generate_tax_receipt',
]
|
a= True
b = False
c= a and b
print("jika A={} and B={} = {}". format(a,b,c))
c= a or b
print("jika A={} or B={} = {}". format(a,b,c))
c= not a
print("jika A={} maka not A = {}". format) |
class GameConstants:
# the maximum number of rounds, until the winner is decided by a coinflip
MAX_ROUNDS = 500
# the board size
BOARD_SIZE = 16
# the default seed
DEFAULT_SEED = 1337
|
"""
DAY 24 : Convert to Roman No.
https://www.geeksforgeeks.org/converting-decimal-number-lying-between-1-to-3999-to-roman-numerals/
QUESTION : Given an integer n, your task is to complete the function convertToRoman which prints the
corresponding roman number of n. Various symbols and their values are given below.
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
Expected Time Complexity: O(log10N)
Expected Auxiliary Space: O(log10N * 10)
Constraints:
1<=n<=3999
"""
def convertRoman(number):
roman_value = ""
while number:
if number >= 1000:
roman_value += 'M'
number = number-1000
elif number >= 900:
roman_value += 'CM'
number = number-900
elif number >= 500:
roman_value += 'D'
number = number-500
elif number >= 400:
roman_value += 'CD'
number = number-400
elif number >= 100:
roman_value += 'C'
number = number-100
elif number >= 90:
roman_value += 'XC'
number = number-90
elif number >= 50:
roman_value += 'L'
number = number-50
elif number >= 40:
roman_value += 'XL'
number = number-40
elif number >= 10:
roman_value += 'X'
number = number-10
elif number >= 9:
roman_value += 'IX'
number = number-9
elif number >= 5:
roman_value += 'V'
number = number-5
elif number >= 4:
roman_value += 'IV'
number = number-4
elif number >= 1:
roman_value += 'I'
number = number-1
return roman_value
|
# read file function
def read_file():
file_data = open('./python_examples/file_io/input_file.txt')
for single_line in file_data:
print(single_line, end='')
if __name__ == "__main__":
read_file()
|
{
"variables": {
# Be sure to create OPENNI2 and NITE2 system vars
"OPENNI2%": "$(OPENNI2)",
"NITE2%": "$(NITE2)"
},
"targets": [
{
"target_name":"copy-files",
"conditions": [
[ "OS=='win'", {
"copies": [
{ "files": [ "<(OPENNI2)/Redist/OpenNI2/Drivers/Kinect.dll",
"<(OPENNI2)/Redist/OpenNI2/Drivers/OniFile.dll",
"<(OPENNI2)/Redist/OpenNI2/Drivers/PS1080.dll",
"<(OPENNI2)/Redist/OpenNI2/Drivers/PS1080.ini",
"<(OPENNI2)/Redist/OpenNI2/Drivers/PSLink.dll",
"<(OPENNI2)/Redist/OpenNI2/Drivers/PSLink.ini"],
"destination": "<(module_root_dir)/build/Release/OpenNI2/Drivers/"
},
# If NITE folder is not placed at root of project, it cannot be accessed
# go up through node_modules to project root and drop in NiTE2 folder
{ "files": [ "<(NITE2)/Redist/NiTE2/Data/lbsdata.idx",
"<(NITE2)/Redist/NiTE2/Data/lbsdata.lbd",
"<(NITE2)/Redist/NiTE2/Data/lbsparam1.lbd",
"<(NITE2)/Redist/NiTE2/Data/lbsparam2.lbd"],
"destination": "<(module_root_dir)/../../NiTE2/Data/"
},
{ "files": [ "<(NITE2)/Redist/NiTE2/FeatureExtraction.ini",
"<(NITE2)/Redist/NiTE2/h.dat",
"<(NITE2)/Redist/NiTE2/HandAlgorithms.ini",
"<(NITE2)/Redist/NiTE2/s.dat"],
"destination": "<(module_root_dir)/../../NiTE2/"
},
{ "files": [ "<(OPENNI2)/Redist/OpenNI2.dll",
"<(OPENNI2)/Redist/OpenNI.ini",
"<(NITE2)/Redist/NiTE2.dll",
"<(NITE2)/Redist/NiTE.ini" ],
"destination": "<(module_root_dir)/build/Release/"
}
],
"libraries": ["-l<(OPENNI2)/Lib/OpenNI2", "-l<(NITE2)/Lib/NiTE2"]
}],
["OS=='mac'", {
"copies": [
{ "files": [ "<(OPENNI2)/Redist/OpenNI2/Drivers/libOniFile.dylib",
"<(OPENNI2)/Redist/OpenNI2/Drivers/libPS1080.dylib",
"<(OPENNI2)/Redist/OpenNI2/Drivers/PS1080.ini",
"<(OPENNI2)/Redist/OpenNI2/Drivers/PSLink.ini"],
"destination": "<(module_root_dir)/build/Release/OpenNI2/Drivers/"
},
# If NITE folder is not placed at root of project, it cannot be accessed
# go up through node_modules to project root and drop in NiTE2 folder
{ "files": [ "<(NITE2)/Redist/NiTE2/Data/lbsdata.idx",
"<(NITE2)/Redist/NiTE2/Data/lbsdata.lbd",
"<(NITE2)/Redist/NiTE2/Data/lbsparam1.lbd",
"<(NITE2)/Redist/NiTE2/Data/lbsparam2.lbd"],
"destination": "<(module_root_dir)/../../NiTE2/Data/"
},
{ "files": [ "<(NITE2)/Redist/NiTE2/FeatureExtraction.ini",
"<(NITE2)/Redist/NiTE2/h.dat",
"<(NITE2)/Redist/NiTE2/HandAlgorithms.ini",
"<(NITE2)/Redist/NiTE2/s.dat"],
"destination": "<(module_root_dir)/../../NiTE2/"
},
{ "files": [ "<(OPENNI2)/Redist/libOpenNI2.dylib",
"<(OPENNI2)/Redist/OpenNI.ini",
"<(NITE2)/Redist/libNiTE2.dylib",
"<(NITE2)/Redist/NiTE.ini" ],
"destination": "<(module_root_dir)/build/Release/"
}
]
}],
["OS=='linux'", {
"copies": [
{ "files": [ "<(OPENNI2)/Redist/OpenNI2/Drivers/libOniFile.so",
"<(OPENNI2)/Redist/OpenNI2/Drivers/libPS1080.so",
"<(OPENNI2)/Redist/OpenNI2/Drivers/PS1080.ini",
"<(OPENNI2)/Redist/OpenNI2/Drivers/PSLink.ini"],
"destination": "<(module_root_dir)/build/Release/OpenNI2/Drivers/"
},
# If NITE folder is not placed at root of project, it cannot be accessed
# go up through node_modules to project root and drop in NiTE2 folder
{ "files": [ "<(NITE2)/Redist/NiTE2/Data/lbsdata.idx",
"<(NITE2)/Redist/NiTE2/Data/lbsdata.lbd",
"<(NITE2)/Redist/NiTE2/Data/lbsparam1.lbd",
"<(NITE2)/Redist/NiTE2/Data/lbsparam2.lbd"],
"destination": "<(module_root_dir)/../../NiTE2/Data/"
},
{ "files": [ "<(NITE2)/Redist/NiTE2/FeatureExtraction.ini",
"<(NITE2)/Redist/NiTE2/h.dat",
"<(NITE2)/Redist/NiTE2/HandAlgorithms.ini",
"<(NITE2)/Redist/NiTE2/s.dat"],
"destination": "<(module_root_dir)/../../NiTE2/"
},
{ "files": [ "<(OPENNI2)/Redist/libOpenNI2.so",
"<(OPENNI2)/Redist/OpenNI.ini",
"<(NITE2)/Redist/libNiTE2.so",
"<(NITE2)/Redist/NiTE.ini" ],
"destination": "<(module_root_dir)/build/Release/"
}
]
}]
]
},
{
"target_name": "nuimotion",
"sources": [
"src/Main.cpp",
"src/enums/EnumMapping.cpp",
"src/gestures/GestureRecognizer.cpp",
"src/gestures/Swipe.cpp",
"src/gestures/Wave.cpp" ],
"conditions": [
[ "OS=='win'", {
"libraries": ["-l<(OPENNI2)/Lib/OpenNI2", "-l<(NITE2)/Lib/NiTE2"]
}],
["OS=='mac'", {
"libraries": ["<(OPENNI2)/Tools/libOpenNI2.dylib", "<(NITE2)/Redist/libNiTE2.dylib"]
}],
["OS=='linux'", {
"libraries": ["<(OPENNI2)/Tools/libOpenNI2.so", "<(NITE2)/Redist/libNiTE2.so"]
}],
],
"include_dirs": [ "./src/enums", "./build/Release", "<(OPENNI2)/Include/", "<(NITE2)/Include/" ],
},
{
"target_name": "nuimotion-depth",
"sources": [
"src/Depth.cpp",
"src/enums/EnumMapping.cpp",
"src/gestures/GestureRecognizer.cpp",
"src/gestures/Swipe.cpp",
"src/gestures/Wave.cpp" ],
"conditions": [
[ "OS=='win'", {
"libraries": ["-l<(OPENNI2)/Lib/OpenNI2"]
}],
["OS=='mac'", {
"libraries": ["<(OPENNI2)/Tools/libOpenNI2.dylib"]
}],
["OS=='linux'", {
"libraries": ["<(OPENNI2)/Tools/libOpenNI2.so"]
}],
],
"include_dirs": [ "<(OPENNI2)/Include/"]
}
]
}
|
# Даны координаты двух точек на плоскости, требуется определить, лежат ли они в одной координатной четверти или нет (
# все координаты отличны от нуля).
# Формат ввода
# Вводятся 4 числа: координаты первой точки (x1,y1) и координаты второй точки (x2,y2).
# Формат вывода Программа должна вывести слово YES, если точки находятся в одной координатной четверти, в противном
# случае вывести слово NO.
x1 = int(input())
y1 = int(input())
x2 = int(input())
y2 = int(input())
if x1 > 0 and x2 > 0 and y1 > 0 and y2 > 0:
print('YES') # 1
elif x1 < 0 and x2 < 0 and y1 > 0 and y2 > 0:
print('YES') # 2
elif x1 < 0 and x2 < 0 and y1 < 0 and y2 < 0:
print('YES') # 3
elif x1 > 0 and x2 > 0 and y1 < 0 and y2 < 0:
print('YES') # 4
else:
print('NO')
|
def is_palindrome(number):
if int(number)%15 == 0:
rev = number[::-1]
return True if rev == number else False
else: return False
num = input("Enter a number to check palindrome divisible by 3 and 5: ")
if is_palindrome(number=num):
print(num, "is a Palindrome divisible by 3 and 5")
else:
print(num, "is not Palindrome divisible by 3 and 5") |
# Container With Most Water
# https://www.interviewbit.com/problems/container-with-most-water/
#
# Given n non-negative integers a1, a2, ..., an,
# where each represents a point at coordinate (i, ai).
# 'n' vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0).
#
# Find two lines, which together with x-axis forms a container, such that the container contains the most water.
#
# Your program should return an integer which corresponds to the maximum area of water that can be
# contained ( Yes, we know maximum area instead of maximum volume sounds weird. But this is 2D plane
# we are working with for simplicity ).
#
# Note: You may not slant the container.
#
# Example :
#
# Input : [1, 5, 4, 3]
# Output : 6
#
# Explanation : 5 and 3 are distance 2 apart. So size of the base = 2. Height of container = min(5, 3) = 3.
# So total area = 3 * 2 = 6
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class Solution:
# @param A : list of integers
# @return an integer
def maxArea(self, A):
i, j = 0, len(A) - 1
area = 0
while i < j:
area = max(area, (j - i) * min(A[i], A[j]))
if A[i] < A[j]:
i += 1
else:
j -= 1
return area
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
if __name__ == "__main__":
s = Solution()
print(s.maxArea([1, 5, 4, 3])) |
# 8.请按alist中元素的age由大到小排序
# alist = [{'name':'a','age':20},{'name':'b','age':30},{'name':'c','age':25}]
alist = [{'name':'a','age':20},{'name':'b','age':30},{'name':'c','age':25}]
a = sorted(alist,key = lambda x: x['age'],reverse=True)
print(a)
# 和题目4差不多,多考察了一下reverse |
class Mazmorra():
def __init__(self):
self.__salas = []
@property
def salas(self):
return self.__salas
def addSala(self, sala):
self.__salas.append(sala)
|
a = 33
b = 200
if b > a:
pass |
#
# PySNMP MIB module CISCO-WRED-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-WRED-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:21:31 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)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex")
ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup")
Counter32, Integer32, IpAddress, ModuleIdentity, Gauge32, NotificationType, Counter64, Bits, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, TimeTicks, Unsigned32, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "Integer32", "IpAddress", "ModuleIdentity", "Gauge32", "NotificationType", "Counter64", "Bits", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "TimeTicks", "Unsigned32", "MibIdentifier")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
ciscoWredMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 83))
ciscoWredMIB.setRevisions(('1997-07-18 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: ciscoWredMIB.setRevisionsDescriptions(('Initial version of this MIB module.',))
if mibBuilder.loadTexts: ciscoWredMIB.setLastUpdated('9707180000Z')
if mibBuilder.loadTexts: ciscoWredMIB.setOrganization('Cisco Systems, Inc.')
if mibBuilder.loadTexts: ciscoWredMIB.setContactInfo(' Cisco Systems Customer Service Postal: 170 W. Tasman Drive San Jose, CA 95134-1706 USA Tel: +1 800 553-NETS E-mail: tgrennan-group@cisco.com')
if mibBuilder.loadTexts: ciscoWredMIB.setDescription('Cisco WRED MIB - Overview Cisco Weighted Random Early Detection/Drop is a method which avoids traffic congestion on an output interface. Congestion is detected by computing the average output queue size against preset thresholds. WRED support are on the IP fast switching and IP flow switching only. It does not apply to IP process switching. This MIB incorporates objects from the Cisco WRED line interfaces. Its purpose is to provide Weighted Random Early Detection/Drop packet configuration and packet filtering information. WRED are configured/enabled through the CLI command. Defaults configuration values are assigned and values can be modified through additional CLI commands. ')
ciscoWredMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 83, 1))
cwredConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 83, 1, 1))
cwredStats = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 83, 1, 2))
cwredConfigGlobTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 83, 1, 1, 1), )
if mibBuilder.loadTexts: cwredConfigGlobTable.setStatus('current')
if mibBuilder.loadTexts: cwredConfigGlobTable.setDescription('A table of WRED global configuration variables.')
cwredConfigGlobEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 83, 1, 1, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: cwredConfigGlobEntry.setStatus('current')
if mibBuilder.loadTexts: cwredConfigGlobEntry.setDescription('A collection of configuration entries on this interface. Entries are created and deleted via red command line interface.')
cwredConfigGlobQueueWeight = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 83, 1, 1, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cwredConfigGlobQueueWeight.setStatus('current')
if mibBuilder.loadTexts: cwredConfigGlobQueueWeight.setDescription("The decay factor for the queue average calculation. Numbers are 2's exponent up to 16. The smaller the number, the faster it decays.")
cwredConfigPrecedTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 83, 1, 1, 2), )
if mibBuilder.loadTexts: cwredConfigPrecedTable.setStatus('current')
if mibBuilder.loadTexts: cwredConfigPrecedTable.setDescription('A table of WRED configuration values with respect to the IP precedence of packets.')
cwredConfigPrecedEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 83, 1, 1, 2, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "CISCO-WRED-MIB", "cwredConfigPrecedPrecedence"))
if mibBuilder.loadTexts: cwredConfigPrecedEntry.setStatus('current')
if mibBuilder.loadTexts: cwredConfigPrecedEntry.setDescription('WRED IP precedence configuration table entry. Entries are created and deleted via red command interface.')
cwredConfigPrecedPrecedence = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 83, 1, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 7)))
if mibBuilder.loadTexts: cwredConfigPrecedPrecedence.setStatus('current')
if mibBuilder.loadTexts: cwredConfigPrecedPrecedence.setDescription('The IP precedence of this entry.')
cwredConfigPrecedMinDepthThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 83, 1, 1, 2, 1, 2), Integer32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwredConfigPrecedMinDepthThreshold.setStatus('current')
if mibBuilder.loadTexts: cwredConfigPrecedMinDepthThreshold.setDescription('The average queue depth at which WRED begins to drop packets.')
cwredConfigPrecedMaxDepthThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 83, 1, 1, 2, 1, 3), Integer32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwredConfigPrecedMaxDepthThreshold.setStatus('current')
if mibBuilder.loadTexts: cwredConfigPrecedMaxDepthThreshold.setDescription('The average queue depth at which WRED may begin to drop all packets.')
cwredConfigPrecedPktsDropFraction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 83, 1, 1, 2, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cwredConfigPrecedPktsDropFraction.setStatus('current')
if mibBuilder.loadTexts: cwredConfigPrecedPktsDropFraction.setDescription('The fraction of packets to be dropped when the average queue depth is above cwredConfigPrecedMinDepthThreshold but below cwredConfigPrecedMaxDepthThreshold.')
cwredQueueTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 83, 1, 2, 1), )
if mibBuilder.loadTexts: cwredQueueTable.setStatus('current')
if mibBuilder.loadTexts: cwredQueueTable.setDescription('A table of WRED queue status variable.')
cwredQueueEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 83, 1, 2, 1, 1), )
cwredConfigGlobEntry.registerAugmentions(("CISCO-WRED-MIB", "cwredQueueEntry"))
cwredQueueEntry.setIndexNames(*cwredConfigGlobEntry.getIndexNames())
if mibBuilder.loadTexts: cwredQueueEntry.setStatus('current')
if mibBuilder.loadTexts: cwredQueueEntry.setDescription('A table of WRED queue status variable entry. Entries are created and deleted via the red command line interface.')
cwredQueueAverage = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 83, 1, 2, 1, 1, 1), Gauge32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwredQueueAverage.setStatus('current')
if mibBuilder.loadTexts: cwredQueueAverage.setDescription('The computed queue average length.')
cwredQueueDepth = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 83, 1, 2, 1, 1, 2), Gauge32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwredQueueDepth.setStatus('current')
if mibBuilder.loadTexts: cwredQueueDepth.setDescription('The number of buffers/particles currently withheld in queue.')
cwredStatTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 83, 1, 2, 2), )
if mibBuilder.loadTexts: cwredStatTable.setStatus('current')
if mibBuilder.loadTexts: cwredStatTable.setDescription('A table of WRED status information with respect to the IP precedence of packets.')
cwredStatEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 83, 1, 2, 2, 1), )
cwredConfigPrecedEntry.registerAugmentions(("CISCO-WRED-MIB", "cwredStatEntry"))
cwredStatEntry.setIndexNames(*cwredConfigPrecedEntry.getIndexNames())
if mibBuilder.loadTexts: cwredStatEntry.setStatus('current')
if mibBuilder.loadTexts: cwredStatEntry.setDescription('The WRED interface status information entry. Entries are created and deleted via the red red command line interface.')
cwredStatSwitchedPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 83, 1, 2, 2, 1, 1), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwredStatSwitchedPkts.setStatus('current')
if mibBuilder.loadTexts: cwredStatSwitchedPkts.setDescription('The number of packets output by WRED.')
cwredStatRandomFilteredPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 83, 1, 2, 2, 1, 2), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwredStatRandomFilteredPkts.setStatus('current')
if mibBuilder.loadTexts: cwredStatRandomFilteredPkts.setDescription('The number of packets filtered/dropped due to average queue length exceeds cwredConfigMinDepthThreshold and meet a defined random drop policy.')
cwredStatMaxFilteredPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 83, 1, 2, 2, 1, 3), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cwredStatMaxFilteredPkts.setStatus('current')
if mibBuilder.loadTexts: cwredStatMaxFilteredPkts.setDescription('The number of packets filtered/dropped due to average queue length exceeds cwredConfigMaxDepthThreshold.')
ciscoWredMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 83, 3))
ciscoWredMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 83, 3, 1))
ciscoWredMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 83, 3, 2))
ciscoWredMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 83, 3, 1, 1)).setObjects(("CISCO-WRED-MIB", "ciscoWredMIBGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoWredMIBCompliance = ciscoWredMIBCompliance.setStatus('current')
if mibBuilder.loadTexts: ciscoWredMIBCompliance.setDescription('The compliance statement for entities which implement the WRED on a Cisco RSP platform.')
ciscoWredMIBGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 83, 3, 2, 1)).setObjects(("CISCO-WRED-MIB", "cwredConfigGlobQueueWeight"), ("CISCO-WRED-MIB", "cwredConfigPrecedMinDepthThreshold"), ("CISCO-WRED-MIB", "cwredConfigPrecedMaxDepthThreshold"), ("CISCO-WRED-MIB", "cwredConfigPrecedPktsDropFraction"), ("CISCO-WRED-MIB", "cwredQueueAverage"), ("CISCO-WRED-MIB", "cwredQueueDepth"), ("CISCO-WRED-MIB", "cwredStatSwitchedPkts"), ("CISCO-WRED-MIB", "cwredStatRandomFilteredPkts"), ("CISCO-WRED-MIB", "cwredStatMaxFilteredPkts"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoWredMIBGroup = ciscoWredMIBGroup.setStatus('current')
if mibBuilder.loadTexts: ciscoWredMIBGroup.setDescription('A collection of objects providing WRED monitoring.')
mibBuilder.exportSymbols("CISCO-WRED-MIB", cwredConfigPrecedEntry=cwredConfigPrecedEntry, ciscoWredMIBCompliance=ciscoWredMIBCompliance, cwredConfigPrecedTable=cwredConfigPrecedTable, ciscoWredMIBGroups=ciscoWredMIBGroups, cwredStatSwitchedPkts=cwredStatSwitchedPkts, cwredQueueEntry=cwredQueueEntry, cwredStatMaxFilteredPkts=cwredStatMaxFilteredPkts, cwredConfigPrecedMinDepthThreshold=cwredConfigPrecedMinDepthThreshold, cwredStatEntry=cwredStatEntry, cwredQueueTable=cwredQueueTable, ciscoWredMIBGroup=ciscoWredMIBGroup, cwredConfigGlobEntry=cwredConfigGlobEntry, cwredConfig=cwredConfig, cwredConfigGlobTable=cwredConfigGlobTable, ciscoWredMIB=ciscoWredMIB, cwredQueueDepth=cwredQueueDepth, ciscoWredMIBConformance=ciscoWredMIBConformance, cwredQueueAverage=cwredQueueAverage, cwredStatTable=cwredStatTable, PYSNMP_MODULE_ID=ciscoWredMIB, ciscoWredMIBObjects=ciscoWredMIBObjects, cwredConfigPrecedPrecedence=cwredConfigPrecedPrecedence, cwredConfigPrecedMaxDepthThreshold=cwredConfigPrecedMaxDepthThreshold, cwredStats=cwredStats, cwredStatRandomFilteredPkts=cwredStatRandomFilteredPkts, ciscoWredMIBCompliances=ciscoWredMIBCompliances, cwredConfigPrecedPktsDropFraction=cwredConfigPrecedPktsDropFraction, cwredConfigGlobQueueWeight=cwredConfigGlobQueueWeight)
|
class SqlQueries:
test_result_table_insert = ("""
SELECT
test_id,
vehicle_id,
test_date,
test_class_id,
test_type,
test_result,
test_mileage,
postcode_area
FROM staging_results
WHERE test_mileage IS NOT NULL
""")
test_item_table_insert = ("""
SELECT *
FROM staging_items
""")
vehicle_table_insert = ("""
SELECT
vehicle_id,
make,
model,
colour,
fuel_type,
cylinder_capacity,
first_use_date
FROM staging_results
WHERE cylinder_capacity IS NOT NULL
AND first_use_date IS NOT NULL
""")
test_item_table_update = ("""
UPDATE test_item_table
SET dangerous_mark = 'N'
WHERE dangerous_mark IS Null
""")
|
"""
Lec 7 while loop
"""
i = 5
while i >= 0:
try:
print(1/(i-3))
except:
pass
i = i -1
# if i ==3:
# pass
# print(i)
# try:
# print(1/0)
# except ZeroDivisionError:
# print('Zero Division Error')
# except:
# print('Other Errors') |
with open('fun_file.txt') as close_this_file:
setup = close_this_file.readline()
punchline = close_this_file.readline()
print(setup)
|
# Why a field must have prime order?
prime = 12
for k in (1, 3, 7, 13, 18):
print([k*i % prime for i in range(prime)])
print('sorted:')
for k in (1, 3, 7, 13, 18):
print(sorted([k*i % prime for i in range(prime)]))
# No matter what k you choose, as long as it’s
# greater than 0, multiplying the entire set by k will result in the same
# set as you started with.
# Intuitively, the fact that we have a prime order results in every ele‐
# ment of a finite field being equivalent. If the order of the set was a
# composite number, multiplying the set by one of the divisors would
# result in a smaller set.
for prime in (7, 11, 17, 31):
print([pow(i, prime-1, prime) for i in range(1, prime)])
|
#!/usr/bin/env python3
BOLD = "\033[1m"
DIM = "\033[2m"
END = "\033[0m"
TOWERS = {
"": """
_
| |
| |
| |
| |
_____| |_____
""",
"123": """
_
| |
_|_|_
|_____|
|_______|
_|_________|_
""",
"23": """
_
| |
| |
__|_|__
|_______|
_|_________|_
""",
"12": """
_
| |
| |
_|_|_
|_____|
__|_______|__
""",
"13": """
_
| |
| |
_|_|_
_|_____|_
_|_________|_
""",
"1": """
_
| |
| |
| |
_|_|_
___|_____|___
""",
"2": """
_
| |
| |
| |
__|_|__
__|_______|__
""",
"3": """
_
| |
| |
| |
___|_|___
_|_________|_
""",
}
class HanoiTowers:
def __init__(self):
self.left = [1, 2, 3]
self.middle = []
self.right = []
self.moves = 0
def show_towers(self):
left_tower = TOWERS.get("".join([str(i) for i in self.left]))
middle_tower = TOWERS.get("".join([str(i) for i in self.middle]))
right_tower = TOWERS.get("".join([str(i) for i in self.right]))
output = zip(*[i.split("\n") for i in [left_tower, middle_tower, right_tower]])
for i in output:
print("".join(i))
def get_tower(self, msg):
full_msg = f"{msg} [L]eft, [M]iddle or [R]ight: "
while True:
tower = input(full_msg).lower()
if tower.startswith("l"):
return self.left
elif tower.startswith("m"):
return self.middle
elif tower.startswith("r"):
return self.right
else:
print(f"'{tower}' is not a valid choice")
def make_move(self):
while True:
src = self.get_tower("Which tower should we move from")
dest = self.get_tower("Which tower should we move to")
if src == dest:
print("Can't move from and to the same tower")
elif len(src) == 0:
print("No disks to move off that tower")
elif len(dest) and src[0] > dest[0]:
print(f"Cannot move {src[0]} on top of {dest[0]}")
else:
disk = src.pop(0)
dest.insert(0, disk)
return
def play(self):
print(f"{BOLD}Move all the disks to the Right Tower!{END}")
while True:
self.show_towers()
if self.right == [1, 2, 3]:
print(f"{BOLD}You have won, it took you {self.moves} move(s)!${END}")
break
self.make_move()
self.moves += 1
if __name__ == "__main__":
again = True
while again:
game = HanoiTowers()
game.play()
again = not input("Play again? [Yn] ").lower().startswith("n")
|
def teleport(a,b,x,y):
d1 = abs(a-b)
d2 = abs(a-x)+abs(b-y)
d3 = abs(a-y)+abs(b-x)
print(d1,d2,d3)
if d1 <= d2 and d1 <= d3:
return d1
elif d2 <= d1 and d2 <= d3:
return d2
else:
return d3
print(teleport(3,10,8,2))
print(teleport(86,84,15,78))
print(teleport(35,94,92,87)) |
# Write a program that reads an integer n. Then, for all numbers in the range [1, n], prints the number and if it is special or not (True / False).
# A number is special when the sum of its digits is 5, 7, or 11.
# Examples
# Input Output
# 15 1 -> False
# 2 -> False
# 3 -> False
# 4 -> False
# 5 -> True
# 6 -> False
# 7 -> True
# 8 -> False
# 9 -> False
# 10 -> False
# 11 -> False
# 12 -> False
# 13 -> False
# 14 -> True
# 15 -> False
# 6 1 -> False
# 2 -> False
# 3 -> False
# 4 -> False
# 5 -> True
# 6 -> False
special_range = (5,7,11)
num = int(input())
for i in range(1, num + 1):
str_i = str(i)
char_sum = 0
for j in range(len(str_i)):
char_sum += int(str_i[j])
is_special = True if char_sum in special_range else False
print(f"{i} -> {is_special}")
|
lista = ('Caderno', 5.35, 'Lápis', 1.50, 'Borracha', 0.75, 'Lapiseira', 2.50, 'Folhas A4', 18.50, 'Apontador',
3, 'Fichário', 22.50, 'Lápis de cor', 15.50)
print('\033[1;32m LISTA SUPER MERCADO\033[m')
print('-=' * 30)
for cont in range(0, len(lista), +1):
if cont % 2 == 0:
print(f'{lista[cont]:.<30}', end='')
else:
print(f'R${lista[cont]:.2f}')
print('-=' * 30) |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
if l1 is None and l2 is None:
return None
if l1 is None:
return l2
if l2 is None:
return l1
# same as
#if None in [l1, l2]:
# return l1 or l2
n1 = l1
n2 = l2
if n1.val <= n2.val:
result = n1
n1 = n1.next
else:
result = n2
n2 = n2.next
n3 = result
while n1 is not None and n2 is not None:
if n1.val <= n2.val:
n3.next = n1
n1 = n1.next
else:
n3.next = n2
n2 = n2.next
n3 = n3.next
if n1 is not None:
n3.next = n1
if n2 is not None:
n3.next = n2
return result
|
print('=' * 25)
print(' 10 TERMOS DE UMA PA')
print('=' * 25)
p = int(input('Primeiro termo: '))
r = int(input('Razão: '))
n = p + (10-1)*r
for cont in range(p, n+r, r):
print(cont, end = ' -> ')
print('ACABOU') |
class Solution:
def XXX(self, root: TreeNode) -> int:
def dfs(root, level):
if not root: return
if self.res < level + 1:
self.res = level + 1
if root.left: dfs(root.left, level + 1)
if root.right: dfs(root.right, level + 1)
if not root: return 0
self.res = 0 # 深度
dfs(root, 0)
return self.res
|
class Configuration(object):
"""Configuration describes how a benchmark should be run.
It selects the implementation (for example, different implementations) and
implementation-specific options (for example, whether replay compilation
should be used).
"""
def __init__(self, name):
self.name = name
self.args = {}
def update_args(self, args):
self.args.update(args)
return self
def set_description(self, descr):
self.descr = descr
return self |
f = open("nine.txt", "r")
lines = [x.strip() for x in f.readlines()]
height = len(lines)
width = len(lines[0])
map = []
for line in lines:
cur = [int(ch) for ch in list(line)]
map.append(cur)
risk = 0
for y in range(height):
for x in range(width):
val = map[y][x]
if y !=0 and map[y-1][x] <= val:
continue
if y != height - 1 and map[y+1][x] <= val:
continue
if x != 0 and map[y][x-1] <= val:
continue
if x != width - 1 and map[y][x+1] <= val:
continue
risk += map[y][x] + 1
print(risk)
height = len(lines)
width = len(lines[0])
map = []
for line in lines:
cur = [int(ch) for ch in list(line)]
map.append(cur)
basins = []
low_points = []
for y in range(height):
for x in range(width):
val = map[y][x]
if y !=0 and map[y-1][x] <= val:
continue
if y != height - 1 and map[y+1][x] <= val:
continue
if x != 0 and map[y][x-1] <= val:
continue
if x != width - 1 and map[y][x+1] <= val:
continue
low_points.append((x,y))
for (x,y) in low_points:
size = 0
# low point grow outwards
to_check = [(x,y)]
while len(to_check) != 0:
pos = to_check.pop(0)
x,y = pos
val = map[y][x]
if val == 9:
continue
size += 1
if y !=0 and map[y-1][x] > val and map[y-1][x] != 9:
to_check.append((x,y-1))
if y != height - 1 and map[y+1][x] > val and map[y+1][x] != 9:
to_check.append((x, y + 1))
if x != 0 and map[y][x-1] > val and map[y][x-1] != 9:
to_check.append((x-1, y))
if x != width - 1 and map[y][x+1] > val and map[y][x+1] != 9:
to_check.append((x+1,y))
map[y][x] = 9
basins.append(size)
basins = sorted(basins, reverse=True)
print(basins[0] * basins[1] * basins[2])
|
adult = int(input())
crian = int(input())
preco = float(input())
preco_final = (crian * (preco/2)) + (adult * preco)
print('Total: R$ {:.2f}'.format(preco_final))
|
# ranges sets
#range1
ghmin1, ghmax1, gsdmin1, gsdmax1= 0.35, 0.4, 0.197, 0.207 #range chaos 1 gh/gsd T36
ghmin2, ghmax2, gsdmin2, gsdmax2= 0.1, 0.15, 0.197, 0.207 #range nonchaos 1 gh/gsd T36
#range2
ghmin1b, ghmax1b, gsdmin1b, gsdmax1b= 0.35, 0.40, 0.275, 0.285 #range chaos 4 gh/gsd T36
ghmin2b, ghmax2b, gsdmin2b, gsdmax2b= 0.18, 0.23, 0.275,0.285 #range nonchaos 4 gh/gsd T36
# paremeters for the network
Nnode = 50 # the number of neurons
lyap_min=0 #minmum lyapunov value
lyap_max=1.6 #maxsimum lyapunov value
dt = 0.05 # the time step of simulation
Xdata=0
Ydata=4
Ydata2=3
tEnd=50000
nsim=50
tbin=40
rseed0=[0,20,25,33,40] # the seed for simulation
ranges0=[2,2,2,2,2] # the index of ranges2
Nindex=1 # The number of example ranges for fixed size
|
'''
Given an array of integers, sort the array into a wave like array and return it,
In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5.....
Example
Given [1, 2, 3, 4]
One possible answer : [2, 1, 4, 3]
Another possible answer : [4, 1, 3, 2]
'''
def wave_list(A: list) -> list:
A.sort()
for i in range(0, len(A)-1, 2):
A[i], A[i+1] = A[i+1], A[i]
return A
if __name__ == "__main__":
A = [1, 2, 3, 4]
print(wave_list(A))
|
KEYS = {
"SPOTIFY_CLIENT_ID": "PLACEHOLDER_CLIENT_ID", # Create an app from [here](https://developer.spotify.com/dashboard/applications)
"SPOTIFY_CLIENT_SECRET": "PLACEHOLDER_CLIENT_SECRET", # Create an app from [here](https://developer.spotify.com/dashboard/applications)
"SPOTIFY_REDIRECT_URI": "http://localhost:5000/callback/spotify", # You have to register this call back in your Application's dashboard https://developer.spotify.com/dashboard/applications
}
|
# https://www.codewars.com/kata/52c31f8e6605bcc646000082
def two_sum(numbers, target):
for i, n1 in enumerate(numbers):
for j, n2 in enumerate(numbers[i+1:]):
if n1+n2 == target: return [i, i+j+1]
|
"""
Custom exceptions raised by this local library
"""
class NoApisDefined(Exception):
"""
Raised when there are no APIs defined in the template
"""
pass
class OverridesNotWellDefinedError(Exception):
"""
Raised when the overrides file is invalid
"""
pass
|
class Constants:
NUM_ARMS = "num_arms"
NUM_LEGS = "num_legs"
PERSON = "person"
ANIMAL_TYPE = "animal_type"
CAT = "cat"
DOG = "dog"
ANIMAL = "animal"
NAME = "name"
SURNAME = "surname"
WHISKERS = "whiskers"
TYPE = "type" |
lista = [('Comestibles', 'Loby Bar', 1, 305.2),
('Comestibles', 'Loby Bar', 5, 87.23),
('Comestibles', 'Piano Bar', 2, 236.9),
('Comestibles', 'Piano Bar', 8, 412.69),
('Bebidas', 'Loby Bar', 3, 145.37),
('Bebidas', 'Loby Bar', 5, 640.81),
('Bebidas', 'Piano Bar', 12, 94.51),
('Tabacos', 'Cafeteria', 4, 498.12),
('Tabacos', 'Cafeteria', 6, 651.3),
('Tabacos', 'Piano Bar', 8, 813.5),
('Tabacos', 'Piano Bar', 11, 843.25),
('Otros', 'Loby Bar', 6, 140.24),
('Otros', 'Piano Bar', 9, 267.06),
('Otros', 'Cafeteria', 12, 695.12)]
if len(lista) > 0:
data = []
cur_fami = lista[0][0]
cur_pvta = lista[0][1]
pvtas = []
meses = ['', '', '', '', '', '', '', '', '', '', '', '', 0]
tot_fami = [0] * 13
tot = [0] * 13
for pvfa in lista:
if pvfa[1] != cur_pvta:
pvtas.append((cur_pvta, meses[:]))
cur_pvta = pvfa[1]
meses = ['', '', '', '', '', '', '', '', '', '', '', '', 0]
if pvfa[0] != cur_fami:
data.append((cur_fami, pvtas[:], tot_fami[:]))
cur_fami = pvfa[0]
pvtas = []
tot_fami = [0] * 13
meses[pvfa[2] - 1] = pvfa[3]
meses[12] += pvfa[3]
tot_fami[pvfa[2] - 1] += pvfa[3]
tot_fami[12] += pvfa[3]
tot[pvfa[2] - 1] += pvfa[3]
tot[12] += pvfa[3]
pvtas.append((cur_pvta, meses[:]))
data.append((cur_fami, pvtas[:], tot_fami[:]))
data.append(tot)
print(data)
x = [('Comestibles', [('Loby Bar', [305.2, '', '', '', 87.23, '', '', '', '', '', '', '', 392.43]),
('Piano Bar', ['', 236.9, '', '', '', '', '', 412.69, '', '', '', '', 649.59])],
[305.2, 236.9, 0, 0, 87.23, 0, 0, 412.69, 0, 0, 0, 0, 1042.02]),
('Bebidas', [('Loby Bar', ['', '', 145.37, '', 640.81, '', '', '', '', '', '', '', 786.18]),
('Piano Bar', ['', '', '', '', '', '', '', '', '', '', '', 94.51, 94.51])],
[0, 0, 145.37, 0, 640.81, 0, 0, 0, 0, 0, 0, 94.51, 880.6899999999999]),
('Tabacos', [('Cafeteria', ['', '', '', 498.12, '', 651.3, '', '', '', '', '', '', 1149.42]),
('Piano Bar', ['', '', '', '', '', '', '', 813.5, '', '', 843.25, '', 1656.75])],
[0, 0, 0, 498.12, 0, 651.3, 0, 813.5, 0, 0, 843.25, 0, 2806.17]),
('Otros', [('Loby Bar', ['', '', '', '', '', 140.24, '', '', '', '', '', '', 140.24]),
('Piano Bar', ['', '', '', '', '', '', '', '', 267.06, '', '', '', 267.06]),
('Cafeteria', ['', '', '', '', '', '', '', '', '', '', '', 695.12, 695.12])],
[0, 0, 0, 0, 0, 140.24, 0, 0, 267.06, 0, 0, 695.12, 1102.42]),
[305.2, 236.9, 145.37, 498.12, 728.04, 791.54, 0, 1226.19, 267.06, 0, 843.25, 789.63, 5831.3]]
|
'''
0.写一个元组生成器(类似于列表推导式)
'''
# 用tuple1.__next__()一个一个显示
tuple1 = (x**2 for x in range(10))
def jixu():
return tuple1.__next__()
|
for _ in range(int(input())):
t = 24*60
h, m = map(int, input().split())
print(t-(h*60)-m)
|
'''
My functions that I created to support me during my lessons.
'''
def title(msg):
#This function will show up a title covered by two lines, one above and other below the msg
print('-'*30)
print(msg)
print('-'*30)
|
N=int(input())
for i in range(1,10):
m=N/i
if m.is_integer() and 1<=m<=9:
print("Yes")
break
else:
print("No") |
"""
# Mobius Software LTD
# Copyright 2015-2018, Mobius Software LTD
#
# This is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of
# the License, or (at your option) any later version.
#
# This software 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this software; if not, write to the Free
# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA, or see the FSF site: http://www.fsf.org.
"""
class MQConnect(object):
def __init__(self,username,password,clientID,cleanSession,keepAlive,will):
self.username = username
self.password = password
self.clientID = clientID
self.cleanSession = cleanSession
self.keepAlive = keepAlive
self.will = will
self.protocolLevel = 4
def getLength(self):
length = 10
length = length + len(self.clientID) + 2
if self.will is not None:
length = length + self.will.getLength()
if self.username is not None:
length = length + len(self.username) + 2
if self.password is not None:
length = length + len(self.password) + 2
return int(length)
def getType(self):
return 1
def getProtocol(self):
return 1
def setProtocolLevel(self, level):
self.protocolLevel = level
def willValid(self):
if self.will.getLength()==0:
return False
return True
def getLengthWill(self):
return self.will.getLength
def getKeepAlive(self):
return self.keepAlive |
# Pancake Sorting
'''
Given an array of integers A, We need to sort the array performing a series of pancake flips.
In one pancake flip we do the following steps:
Choose an integer k where 0 <= k < A.length.
Reverse the sub-array A[0...k].
For example, if A = [3,2,1,4] and we performed a pancake flip choosing k = 2, we reverse the sub-array [3,2,1], so A = [1,2,3,4] after the pancake flip at k = 2.
Return an array of the k-values of the pancake flips that should be performed in order to sort A. Any valid answer that sorts the array within 10 * A.length flips will be judged as correct.
Example 1:
Input: A = [3,2,4,1]
Output: [4,2,4,3]
Explanation:
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: A = [3, 2, 4, 1]
After 1st flip (k = 4): A = [1, 4, 2, 3]
After 2nd flip (k = 2): A = [4, 1, 2, 3]
After 3rd flip (k = 4): A = [3, 2, 1, 4]
After 4th flip (k = 3): A = [1, 2, 3, 4], which is sorted.
Notice that we return an array of the chosen k values of the pancake flips.
Example 2:
Input: A = [1,2,3]
Output: []
Explanation: The input is already sorted, so there is no need to flip anything.
Note that other answers, such as [3, 3], would also be accepted.
Constraints:
1 <= A.length <= 100
1 <= A[i] <= A.length
All integers in A are unique (i.e. A is a permutation of the integers from 1 to A.length).
'''
class Solution:
def pancakeSort(self, arr: List[int]) -> List[int]:
n = end = len(arr)
ans = []
def find(num):
for i in range(n):
if arr[i]==num:
return i+1
def flip(i,j):
while i<j:
arr[i], arr[j] = arr[j], arr[i]
i+=1
j-=1
while end>1:
ind = find(end)
flip(0, ind-1)
flip(0, end-1)
ans.append(ind)
ans.append(end)
end-=1
return ans
|
# The following code implements the knapsack problem with bottom-up dynamic programming approach.
def read_file(name):
"""Given the path/nname of a file ,return the Values list, Weights list,
capacity and number of jobs.
"""
file = open(name, 'r')
data = file.readlines()
capacity = int(data[0].split()[0])
n =int(data[0].split()[1])
# Create two lists to store values and sizes
V = [0]*(n+1)
W = [0]*(n+1)
for index, line in enumerate(data[1:]):
V[index+1]=int(line.split()[0])
W[index+1]=int(line.split()[1])
return V, W, capacity, n
V,W, capacity, n = read_file('knapsack1.txt')
def knapsack_dynamic(V, W, capacity, numbers):
"""Return the matrix of maximum value
"""
# initialize the 2-d array
A = [[0]*(capacity+1) for x in range(numbers+1)]
for i in range(1,numbers+1):
for j in range(capacity+1):
# make sure the size of current is not larger than the current capacity.
if W[i]>j:
A[i][j] = A[i-1][j]
else:
A[i][j] = max(A[i-1][j],A[i-1][j-W[i]]+V[i])
return A
def main():
V,W, capacity, n = read_file('knapsack1.txt')
A = knapsack_dynamic(V,W, capacity, n)
# return the largest value of the matrix.
print(A[-1][-1])
if __name__ == '__main__':
main()
### Test case:
values = [0,3,2,4,4]
sizes = [0,4,3,2,3]
capacity = 6
numbers = 4
B = knapsack_dynamic(values, sizes, capacity, numbers)
B[-1][-1] # The answer should be 8.
|
# postgress creadentials
DB_NAME = "DB_NAME"
DB_ADDRESS = "HOST:PORT"
USER_NAME = "USER_NAME"
DB_PASSWORD = "PASSWORD"
SQLALCHEMY_DATABASE_URI = "postgresql+psycopg2://{}:{}@{}/{}".format(
USER_NAME, DB_PASSWORD, DB_ADDRESS, DB_NAME
)
# twitter creadentials
# https://apps.twitter.com
CONSUMER_KEY = "YOUR_CONSUMER_KEY"
CONSUMER_SECRET = "YOUR_CONSUMER_SECRET"
ACCESS_TOKEN = "YOUR_ACCESS_TOKEN"
ACCESS_TOKEN_SECRET = "YOUR_ACCESS_TOKEN_SECRET"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.