blob_id stringlengths 40 40 | language stringclasses 1 value | repo_name stringlengths 5 133 | path stringlengths 2 333 | src_encoding stringclasses 30 values | length_bytes int64 18 5.47M | score float64 2.52 5.81 | int_score int64 3 5 | detected_licenses listlengths 0 67 | license_type stringclasses 2 values | text stringlengths 12 5.47M | download_success bool 1 class |
|---|---|---|---|---|---|---|---|---|---|---|---|
c9bf280be177b8c155da11265353c7322ed6c0e9 | Python | Varvara08/myrepo | /Programm/mix_brush/functions.py | UTF-8 | 19,136 | 3.25 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import numpy as np
#############################
### Some useful functions ###
#############################
#~ A derivative by 7 datapoints
def dervec7(v,h=1):
global f
# Находит производную по 7и точкам
# v - функция, призводную которой ищем
# h - шаг
n=len(v);
f=zeros(n)
for k in range(n):
if k==0:
f[0]=(-147.0*v[0]+360.0*v[1]-450.0*v[2]+400.0*v[3]-225.0*v[4]+72.0*v[5]-10.0*v[6])/60.0/h ;
elif k==1:
f[1]=(-10.0*v[0]-77.0*v[1]+150.0*v[2]-100.0*v[3]+50.0*v[4]-15.0*v[5]+2.0*v[6])/60.0/h ;
elif k==2:
f[2]=(2.0*v[0]-24.0*v[1]-35.0*v[2]+80.0*v[3]-30.0*v[4]+8.0*v[5]-v[6])/60.0/h ;
elif k > 2 and k < n-3:
f[k]=(-v[k-3]+9.0*v[k-2]-45.0*v[k-1]+45.0*v[k+1]-9.0*v[k+2]+v[k+3])/60.0/h;
elif k==n-3:
f[k]=(v[k-4]-8.0*v[k-3]+30.0*v[k-2]-80.0*v[k-1]+35.0*v[k]+24.0*v[k+1]-2.0*v[k+2])/60.0/h;
elif k==n-2:
f[k]=(-2.0*v[k-5]+15.0*v[k-4]-50.0*v[k-3]+100.0*v[k-2]-150.0*v[k-1]+77.0*v[k]+10.0*v[k+1])/60.0/h;
else:
f[k]=(10.0*v[k-6]-72.0*v[k-5]+225.0*v[k-4]-400.0*v[k-3]+450.0*v[k-2]-360.0*v[k-1]+147.0*v[k])/60.0/h;
return f
#~ A derivative by 4 datapoints
def dervec4(v,h=1):
global f,k
# Находит производную по 4ем точкам
# v - функция, призводную которой ищем
# h - шаг
n=len(v);
f=zeros(n)
for k in range(n):
if k==0:
f[0]=(-11.0*v[0]+18.0*v[1]-9.0*v[2]+2.0*v[3])/6.0/h ;
elif k==1:
f[1]=(-2.0*v[0]-3.0*v[1]+6.0*v[2]-v[3])/6.0/h ;
elif k>1 and k<n-1:
f[k]=(v[k-2]-6.0*v[k-1]+3.0*v[k]+2.0*v[k+1])/6.0/h ;
else:
f[k]=(-2*v[k-3]+9.0*v[k-2]-18.0*v[k-1]+11.0*v[k])/6.0/h;
return f
#~ A derivative by 3 datapoints
def dervec3(v,h=1):
global f
# Находит производную по 3м точкам
# v - функция, призводную которой ищем
# h - шаг
n=len(v);
f=zeros(n)
for k in range(n):
if k==0:
f[0]=(-3.0*v[0]+4.0*v[1]-v[2])/2.0/h ;
elif k>0 and k<n-1:
f[k]=(v[k+1]-v[k-1])/2.0/h ;
else:
f[k]=(v[k-2]-4.0*v[k-1]+3.0*v[k])/2.0/h ;
return f
# ?? finds the first fixed point
def findmin(F, Rstar_range):
# ruturns the position of minimum of F as function of R
DF=dervec3(F)
if sum(sign(DF)) == -len(DF):
R0 = Rstar_range[-1]
elif sum(sign(DF)) == len(DF):
R0 = Rstar_range[0]
else:
# ?? do not understand what find() is doing
nearest_to_zero_positive_index = find(sign(DF) == 1)[ 0]
nearest_to_zero_negative_index = find(sign(DF) == -1)[-1]
R1 = Rstar_range[nearest_to_zero_positive_index];R1=float(R1)
R2 = Rstar_range[nearest_to_zero_negative_index];R2=float(R2)
DF1 = DF[nearest_to_zero_positive_index];DF1=float(DF1)
DF2 = DF[nearest_to_zero_negative_index];DF2=float(DF2)
R0 = -DF1/(DF2-DF1)*(R2-R1)+R1
return R0
def findmin7(F, Rstar_range):
# ruturns the position of minimum of F as function of R
DF=dervec7(F)
if sum(sign(DF)) == -len(DF):
R0 = Rstar_range[-1]
elif sum(sign(DF)) == len(DF):
R0 = Rstar_range[0]
else:
i = 0
while sign(DF[i]) == -1:
index = i
i = i+1
nearest_to_zero_positive_index = i
nearest_to_zero_negative_index = i-1
R1 = Rstar_range[nearest_to_zero_positive_index];R1=float(R1)
R2 = Rstar_range[nearest_to_zero_negative_index];R2=float(R2)
DF1 = DF[nearest_to_zero_positive_index];DF1=float(DF1)
DF2 = DF[nearest_to_zero_negative_index];DF2=float(DF2)
R0 = -DF1/(DF2-DF1)*(R2-R1)+R1
return R0
#~ Makes xy plot, xname and yname are the names of axis
def vplot(x,y,xname = 'x', yname = 'y', xlog = False, ylog = False, color = 'black', PlotLine = True, marker = 'circle', markersize = '2pt'):
global g, graph, xy
try:
type (g) == veusz.Embedded
try:
type(graph) == veusz.WidgetNode
except NameError:
page = g.Root.page1
graph = page.graph1
except NameError:
g = veusz.Embedded('F')
g.EnableToolbar()
page = g.Root.Add('page')
graph = page.Add('graph')
x_dataname = xname
y_dataname = yname
if len(np.shape(x)) == 2:
x_data = x[0]
x_data_err = x[1]
g.SetData(x_dataname, x_data, symerr = x_data_err)
else:
x_data = x
g.SetData(x_dataname, x_data)
if len(np.shape(y)) == 2:
y_data = y[0]
y_data_err = y[1]
g.SetData(y_dataname, y_data, symerr = y_data_err)
else:
y_data = y
g.SetData(y_dataname, y_data)
xy = graph.Add('xy')
xy.xData.val = x_dataname
xy.yData.val = y_dataname
xy.marker.val = marker
xy.MarkerFill.color.val = color
xy.markerSize.val = markersize
#~ xy_sfbox.ErrorBarLine.width.val = '2pt'
#~ xy_sfbox.ErrorBarLine.transparency.val = 50
xy.PlotLine.width.val = '2pt'
xy.PlotLine.style.val = 'solid'
xy.PlotLine.color.val = color
xy.PlotLine.hide.val = not PlotLine
x_axis = graph.x
y_axis = graph.y
x_axis.label.val = xname
x_axis.log.val = xlog
y_axis.label.val = yname
y_axis.log.val = ylog
#~
#~ y_axis.min.val = -1.1
#~ y_axis.max.val = 1.1
#~ x_axis.min.val = 0.25
#~ x_axis.max.val = 0.6
xy.ErrorBarLine.width.val = '1pt'
#~ xy_sim.ErrorBarLine.transparency.val = 50
def veusz2csv(g, filename):
global DATA, strings, w
# writes all the datasets from graphic object g to a csv file for further using in gnuplot
Datasets = g.GetDatasets()
DATA = {}
#~ DATA = {Dataset: g.GetData(Dataset) for Dataset in Datasets}
for Dataset in Datasets:
DATA[Dataset] = g.GetData(Dataset)
keys = DATA.keys()
for i in keys:
val = DATA[i][0]
if not DATA[i][1] == None:
print 'err'
err = DATA[i][1]
DATA[i+'_err'] = list(err)
DATA[i] = list(val)
import csv
strings = []
for i in range(len(DATA)):
string = DATA.items()[i][1]
string.insert(0, DATA.items()[i][0])
strings.append(string)
strings.sort()
longest_length = 0
for i in range(len(strings)):
l = len(strings[i])
if l > longest_length:
longest_length = l
for i in range(len(strings)):
d = longest_length - len(strings[i])
for j in range(d):
strings[i].append(None)
strings = array(strings)
strings = strings.T
with open(filename,'wb') as f:
w = csv.writer(f, delimiter=' ')
w.writerows(strings)
print 'data is stored in ', filename
########Average function z#######
def calc_average(z):
av = 0
norm = 0
for k in arange(0,len(z)):
av = av+(k+1)*z[k]
norm = norm+z[k]
av = av/norm
return av
########Average function z#######
def calc_2average(z):
av2 = 0
norm = 0
for k in arange(0,len(z)):
av2 = av2+(k+1)*(k+1)*z[k]
norm = norm+z[k]
av2 = av2/norm
return av2
#########Fraction of stars########
def findmax(To_finding_max):
global num
nmax=0; l=num
while (nmax==0) and (l-1) > 0:
if num > 0:
if To_finding_max[l-1] < To_finding_max[l]:
nmax=1
num=l
l=l-1;
else:
nmax=1
num=l
return num
def findmin(To_finding_min):
global num
nmin=0; l=num
while (nmin==0):
if num > 0 and (l-1) > 0:
if To_finding_min[l-1] > To_finding_min[l] :
nmin=1
num=l
l=l-1;
else:
nmin=1
num=0
return num
def lambdafind(To_finding_bp,To_finding_ne):
global num, extremdatabp, extremdatane, lambdadictbp, lambdadictne
netot=0; bptot=0; num=len(To_finding_ne)-1; a=0;
extremdatabp={}; extremdatane={} ; lambdadictbp={} ; lambdadictne={}
#Creating extremdata dictinary for branching point and ends
num=len(To_finding_ne)-1
j=1
while num > 0:
extremdatane['min'+str(j)]=findmin(To_finding_ne)
extremdatane['max'+str(j)]=findmax(To_finding_ne)
j=j+1
j=1
num=len(To_finding_bp)-1
while num > 0:
extremdatabp['min'+str(j)]=findmin(To_finding_bp)
extremdatabp['max'+str(j)]=findmax(To_finding_bp)
j=j+1
for k in range(1,len(To_finding_ne)):
netot = netot + To_finding_ne[k]/b.sigma/(b.f-1)
for k in range(1,len(To_finding_bp)):
bptot = bptot + To_finding_bp[k]/b.sigma
mylist_bp=[]
for key in extremdatabp.keys():
if key[0:-1] == 'min':
mylist_bp.append(key)
a=len(mylist_bp)
for i in range(1,a):
lambdadictbp['lam'+str(i)]=calc_area_bp(To_finding_bp,extremdatabp['min'+str(i)],extremdatabp['min'+str(i+1)])
mylist_ne=[]
for key in extremdatane.keys():
if key[0:-1] == 'min':
mylist_ne.append(key)
a=len(mylist_ne)
for i in range(1,a):
lambdadictne['lam'+str(i)]=calc_area_ne(To_finding_ne,extremdatane['min'+str(i)],extremdatane['min'+str(i+1)])
return extremdatabp, extremdatane, lambdadictbp, lambdadictne
def calc_area_bp(To_finding_bp,a,c):
lam = 0
for k in range(a,c,-1):
lam = lam + To_finding_bp[k]/b.sigma
return lam
def calc_area_ne(To_finding_ne,a,c):
lam = 0
for k in range(a,c,-1):
lam = lam + To_finding_ne[k]/b.sigma/(b.f-1)
return lam
def varpar(variation):
global my_parameter_bp, my_fraction_bp, my_parameter_ne, my_fraction_ne
varpardictbp[variation]=lambdadictbp.values()
varpardictne[variation]=lambdadictne.values()
my_keys_bp=[]; my_values_bp=[]; my_keys_ne=[]; my_values_ne=[]
for key in varpardictbp.keys():
for length_box_value in range(0,len(varpardictbp.get(key))):
my_keys_bp.append(key)
my_values_bp.append(varpardictbp.get(key)[length_box_value])
for key in varpardictne.keys():
for length_box_value in range(0,len(varpardictne.get(key))):
my_keys_ne.append(key)
my_values_ne.append(varpardictne.get(key)[length_box_value])
my_parameter_bp=np.array(my_keys_bp)
my_fraction_bp=np.array(my_values_bp)
my_parameter_ne=np.array(my_keys_ne)
my_fraction_ne=np.array(my_values_ne)
return
#########LINECOLORS AND LINETYPES ########
def my_line_color():
my_line_color_dict={}
my_line_color_dict={1:'black',2:'red',3:'green',4:'blue',5:'magenta',6:'#01A9DB',7:'grey',8:'#8904B1',9:'#B4045F',10:'#585858',11:'#DF3A01',12:'#DBA901',13:'#74DF00',14:'#CEF6F5'}
#my_line_color_dict={1:'#B40404',2:'#B43104',3:'#DBA901',4:'#5FB404',5:'#01DF74',6:'#01A9DB',7:'#0040FF',8:'#8904B1',9:'#B4045F',10:'#585858'}
line_color=my_line_color_dict[line_color_num]
return line_color
def my_line_type():
my_line_type_dict={}
#my_line_type_dict={1:'solid',2:'solid',3:'solid',4:'solid',5:'solid',6:'solid',7:'solid',8:'solid',9:'solid',10:'solid'}
#my_line_type_dict={1:'dashed',2:'dashed',3:'dashed',4:'dashed',5:'dashed',6:'dashed',7:'dashed',8:'dashed',9:'dashed',10:'dashed'}
#my_line_type_dict={1:'dotted',2:'dotted',3:'dotted',4:'dotted',5:'dotted',6:'dotted',7:'dotted',8:'dotted',9:'dotted',10:'dotted'}
#my_line_type_dict={1:'dash-dot',2:'dash-dot',3:'dash-dot',4:'dash-dot',5:'dash-dot',6:'dash-dot',7:'dash-dot',8:'dash-dot',9:'dash-dot',10:'dash-dot'}
my_line_type_dict={1:'solid',2:'dashed',3:'dotted',4:'dash-dot',5:'dash-dot-dot',6:'dotted-fine',7:'dashed-fine',8:'dash-dot-fine',9:'dot1',10:'dot2'}
line_type=my_line_type_dict[line_type_num]
return line_type
#########FRACTION OF EXTENDED STARS ########
def extendedStarFind(To_finding_bp,To_finding_ne):
global num, firstdatabp, firstdatane, lambdaonebp, lambdaonene
netot=0; bptot=0; num=len(To_finding_ne)-1; a=0;
firstdatabp={}; firstdatane={} ; lambdaonebp={} ; lambdaonene={}
#Creating e:xtremdata dictinary for branching point and ends
num=len(To_finding_ne)-1
j=1
while j < 3:
firstdatane['min'+str(j)]=findmin(To_finding_ne)
firstdatane['max'+str(j)]=findmax(To_finding_ne)
j=j+1
j=1
num=len(To_finding_bp)-1
while j < 3:
firstdatabp['min'+str(j)]=findmin(To_finding_bp)
firstdatabp['max'+str(j)]=findmax(To_finding_bp)
j=j+1
for k in range(1,len(To_finding_ne)):
netot = netot + To_finding_ne[k]/b.sigma/(b.f-1)
for k in range(1,len(To_finding_bp)):
bptot = bptot + To_finding_bp[k]/b.sigma
if firstdatabp.get('min2') == 0:
lambdaonebp['lam1']=0
else:
lambdaonebp['lam1']=calc_area_bp(To_finding_bp,firstdatabp['min1'],firstdatabp['min2'])
if firstdatane.get('min2') == 0:
lambdaonene['lam1']=0
else:
lambdaonene['lam1']=calc_area_ne(To_finding_ne,firstdatane['min1'],firstdatane['min2'])
return firstdatabp, firstdatane, lambdaonebp, lambdaonene
def varparfirst(variation):
global my_oneparameter_bp, my_onefraction_bp, my_oneparameter_ne, my_onefraction_ne, my_twoparameter_bp, my_twoparameter_ne
varparfirstbp[variation]=lambdaonebp.values()
varparfirstne[variation]=lambdaonene.values()
my_keys_bp=[]; my_values_bp=[]; my_keys_ne=[]; my_values_ne=[]; my_keys2_bp=[]; my_keys2_ne=[]
for key in varparfirstbp.keys():
for length_box_value in range(0,len(varparfirstbp.get(key))):
my_keys_bp.append(key)
my_keys2_bp.append(b.chi)
my_values_bp.append(varparfirstbp.get(key)[length_box_value])
for key in varparfirstne.keys():
for length_box_value in range(0,len(varparfirstne.get(key))):
my_keys_ne.append(key)
my_keys2_ne.append(b.chi)#####
my_values_ne.append(varparfirstne.get(key)[length_box_value])
my_oneparameter_bp=np.array(my_keys_bp)
my_twoparameter_bp=np.array(my_keys2_bp)
my_onefraction_bp=np.array(my_values_bp)
my_oneparameter_ne=np.array(my_keys_ne)
my_twoparameter_ne=np.array(my_keys2_ne)
my_onefraction_ne=np.array(my_values_ne)
return
#########CALCULATION PROPAGATOR GTl AND GF (LINE CASE)########
def calc_gtl_gfl(w):
global gtl, gfl
#init
gtl = np.zeros((b.chain_length,b.chain_length+1))
gfl = np.zeros((b.chain_length,b.chain_length+1))
#condition
gtl[0][0] = w[0]
for j in range(0,b.chain_length+1):
gfl[0][j] = w[j]
#start_recurrence
for k in range(1,b.chain_length):
gtl[k][0] = num_lambda*w[0]*(4.0*gtl[k-1][0]+gtl[k-1][1])
gfl[k][0] = num_lambda*w[0]*(4.0*gfl[k-1][0]+gfl[k-1][1])
for j in range(1,k+1):
gtl[k][j] = num_lambda*w[j]*(gtl[k-1][j-1]+4.0*gtl[k-1][j]+gtl[k-1][j+1])
for j in range(1,b.chain_length-k+1):
gfl[k][j] = num_lambda*w[j]*(gfl[k-1][j-1]+4.0*gfl[k-1][j]+gfl[k-1][j+1])
return gtl, gfl
#########CALCULATION PHI AND PROBABILYTI OF TERMINAL GROUP (LINE CASE)########
def calc_phiL_zeL(w):
global phiL, zeL
Zn = gfl[b.chain_length-1][0]
phiL = np.zeros((b.chain_length))
zeL = np.zeros((b.chain_length))
for k in range(0,b.chain_length-1):
for j in range(0,b.chain_length-1):
phiL[k] = phiL[k] + gtl[j][k]*gfl[b.chain_length-j-1][k]/w[k]
phiL = phiL/Zn
phiL = phiL/b.chain_length
zeL = gtl[b.chain_length-1]/Zn
return phiL, zeL
#########CALCULATION PROPAGATOR GT AND GF (BRUSH CASE)########
def calc_gtb_gfb(w):
global gtb, gfb
#init
gtb = np.zeros((arm_length+2,arm_length+2))
gfb = np.zeros((arm_length+2,2*arm_length+2))
#condition
gtb[0][0] = w[0]
for j in range(0,(2*arm_length+1)+1):
gfb[0][j] = w[j]
#start_recurrence
for k in range(1,arm_length+1):
gtb[k][0] = num_lambda*w[0]*(4.0*gtb[k-1][0]+gtb[k-1][1])
gfb[k][0] = num_lambda*w[0]*(4.0*gfb[k-1][0]+gfb[k-1][1])
for j in range(1,k+1):
gtb[k][j] = num_lambda*w[j]*(gtb[k-1][j-1]+4.0*gtb[k-1][j]+gtb[k-1][j+1])
for j in range(1,(2*arm_length+1)-k-1):
gfb[k][j] = num_lambda*w[j]*(gfb[k-1][j-1]+4.0*gfb[k-1][j]+gfb[k-1][j+1])
return gtb, gfb
#########CALCULATION PROPAGATOR G2 (BRUSH CASE)########
def calc_g2(w):
global g2
#init
g2 = np.zeros((arm_length+2,arm_length+2,2*arm_length+5))
#condition
for j in range(0,arm_length+1):
g2[0][j][j] = w[j]
#start_recurrence
for k in range(1,arm_length+1):
for z1 in range(0,arm_length+1):
g2[k][z1][0] = num_lambda*w[0]*(4.0*g2[k-1][z1][0]+g2[k-1][z1][1])
for j in range(1,k+z1+1):
g2[k][z1][j] = num_lambda*w[j]*(g2[k-1][z1][j-1]+4.0*g2[k-1][z1][j]+g2[k-1][z1][j+1])
return g2
#########CALCULATION ZBP AND ZE (BRUSH CASE)########
def calc_zbp_ze(w):
global zbp_calc, ze_calc
Znb = 0; Zne = 0
zbp_calc = np.zeros((arm_length+2))
ze_calc = np.zeros((2*arm_length+1))
for k in range(0,arm_length):
zbp_calc[k] = gtb[arm_length-1][k]*(gfb[arm_length][k]/w[k])**(f1-1)
Znb = Znb + zbp_calc[k]
zbp_calc = zbp_calc/Znb
for k in range(0,2*arm_length+1):
for z1 in range(0,arm_length):
ze_calc[k] = ze_calc[k] + gtb[arm_length-1][z1]*(gfb[arm_length][z1]/w[z1])**(f1-2)*(g2[arm_length][z1][k]/w[z1])
Zne = Zne + ze_calc[k]
ze_calc = ze_calc/Zne
return zbp_calc, ze_calc
def potention_from_formula():
global M
M = (math.pi*n_formula/2)/arccos(sqrt((f_formula-1.)/f_formula))
potention_formula = np.zeros((b.chain_length+1))
for i in range(0,b.chain_length+1):
if i < (b.h2n*2*n_formula-1):
#potention_formula[i] = -3*log(cos(b.h2n*math.pi/2))-((3*math.pi**2/8)*((b.h2n)**2-(b.h2n*2*n_formula/M)**2))-(-3*log(cos((math.pi/2)*(i/200)))-((3*math.pi**2/8)*((i/200)**2-(i/M)**2)))
potention_formula[i] = -3.*log(cos(b.h2n*math.pi/2.))-((3.*math.pi**2/8.)*((b.h2n)**2-(b.h2n*2.*n_formula/M)**2))-(-3.*log(cos((math.pi/2.)*(i/(2.*n_formula))))-((3.*math.pi**2/8.)*((i/(2.*n_formula))**2-(i/M)**2)))
else:
potention_formula[i] = 0
return potention_formula
def change_potention_from_sfbox(pot_in):
global M
pot_up = np.zeros((2*n_formula+5))
pot_mod = np.zeros((2*n_formula+5))
pot_out = np.zeros((b.chain_length+5))
M = (math.pi*n_formula/2)/arccos(sqrt((f_formula-1.)/f_formula))
pot_up = pot_in[5] - pot_in
for i in range(0,(2*n_formula)):
pot_mod[i] = pot_up[i] -((3.*math.pi**2/8.)*((i/(2.*n_formula))**2-(i/M)**2))
for i in range(0,b.chain_length+5):
if i < (b.h2n*2*n_formula-1):
pot_out[i] = pot_mod[b.h2n*2*n_formula-1]-pot_mod[i]
else:
pot_out[i] = 0
pot_out = array(pot_out)
return pot_out
#~ for p in range(len(To_finding_h),0,-1):
#~ if To_finding_h[p-1]<1.0e-8:
#~ h=p
#~ p=p-1;
#~ h1=min(b.n, extremdata['min2'])
#~ h2=h-h1
| true |
20053a4238e8b586606aad19e02bb619482749aa | Python | finesure2017/Labs | /courses/Toronto_ECE410/Lab1/lab1.py | UTF-8 | 1,024 | 3.78125 | 4 | [] | no_license | """
This file is the pre-requisite to the course ECE410: Control Systems at University of Toronto
It is the basics to working with Linear Algebra and Ordinary Differential Equations
"""
import numpy as np
""" Create the matrix
1 2 3
[ 4 5 6 ]
7 8 9
"""
def createMatrix(row, col):
result = np.empty((row, col))
count = 1
for rowIndex in range(row):
for colIndex in range(col):
result[rowIndex, colIndex] = count
count += 1
return result
def createMatrixWithValue(row, col, value):
return value * np.ones((row, col))
def KthRow(matrix, k):
return matrix[k][:]
def KthCol(matrix, k):
return matrix[:,k]
if __name__ == "__main__":
A = createMatrixWithValue(3, 3, 2)
print A
A = createMatrix(3, 3)
print A
print KthRow(A, 0)
print KthCol(A, 0)
# Make Reduced Row Echelon Form Manually
A[2][:] -= 7 * A[0][:]
A[1][:] -= 4 * A[0][:]
A[2][:] -= 2*A[1][:]
A[1][:] /= -3
A[0][:] -= 2 * A[1][:]
print A
| true |
15a549ecbb0afcfa1da132aaa140fd21c6af0694 | Python | karbekk/Python_Data_Structures | /Interview/FInal_Prep/DSalgo/String/1_String_Rotation.py | UTF-8 | 219 | 3.21875 | 3 | [] | no_license | def rotate(s1,s2):
if len(s1) == len(s2):
s1 = s1 + s1
if s2 in s1:
return True
else:
return False
return False
s1 = 'Karthik'
s2 = 'thikKac'
print rotate(s1,s2) | true |
6516288b6dabc8e14141d32c621b02548bfffb58 | Python | MysteriousSonOfGod/propython | /xml/converter/intelimap2freemind.py | UTF-8 | 1,422 | 2.546875 | 3 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
import sys
from xml.etree import cElementTree as ElementTree
FREEMIND_VERSION = '0.7.1'
if len(sys.argv) == 2:
filename = sys.argv[1]
else:
print 'Usage: %s <InteliMap-text-with-tabs.txt>' % sys.argv[0]
raise SystemExit
def parse_line(line):
parts = line.split('\t')
level = 0
while len(parts[level]) == 0:
level += 1
return (level, parts[level].strip())
map = ElementTree.Element('map', version=FREEMIND_VERSION)
map.text = '\n'
map.tail = '\n'
in_file = open(filename)
line = in_file.readline()
node = ElementTree.Element('node', TEXT=line.strip())
map.append(node)
parents = [node]
line_num = 0
for line in in_file:
line_num += 1
level, text = parse_line(line)
level += 1 # correct InteliMap quirk
level_change = level - len(parents)
if level_change == 1:
parents.append(node)
elif level_change < 0:
for i in range(abs(level_change)):
parents.pop()
elif level_change > 1:
print 'Invalid text file: too many tabs indent at line', line_num
node = ElementTree.Element('node', TEXT=text)
node.text = '\n'
node.tail = '\n'
parents[-1].append(node)
out_name = filename.replace('.','_') + '_freemind.mm'
out_file = open(out_name, 'wb')
ElementTree.ElementTree(map).write(out_file, 'utf-8')
out_file.close()
| true |
2f9604f6d46542e8e6036beaf1e894fcedc4e8d7 | Python | NardJ/STLViewer | /STLViewer.py | UTF-8 | 9,526 | 2.625 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | #!/usr/bin/env python3
import sys
import os
import vtk
import numpy
import cv2
# TODO: rotate model does not work nicely if up axis was wrong
################################################
### Print Manual
################################################
print ("STLViewer v0.1 (python3)")
print ("")
print ("Arguments: no arguments will open current dir and default size")
print (" valid arguments: 'file:[yourfile.stl]' OR 'dir:[yourdir]'")
print (" 'size:[width],[height]' for windowsize" )
print (" 'auto' to autoscan dir and save png's" )
print ("")
print ("Controls: [mouse-left]: rotate, [mouse-wheel/right]: zoom, ")
print (" [up]: change up vector, [down]: rotate model")
print (" [s]: shrink to fit, [g]: grow to fit")
print (" [space]: save screenshot, [q],[esc]: quit viewer")
print ("")
################################################
### GET all input values like filepath and derive working dir
################################################
filename='.'
argsList=sys.argv[1:]
# Get dir where we show files from
filepath=os.getcwd()
for arg in argsList:
if 'dir:' in arg:
key,val=arg.split(':')
if not os.path.isdir(val):
print ("Directory is not a valid path")
quit()
filepath=os.path.abspath(val)
if 'file:' in arg:
key,val=arg.split(':')
if not os.path.isfile(val):
print ("File is not found")
quit()
absfilename=os.path.abspath(val)
filepath=os.path.split(absfilename)[0]
# Get STL files in found dir
otherfiles=[]
for file in os.listdir(filepath):
name, ext = os.path.splitext(file)
if ext.lower()==".stl":
otherfiles.append(file)
otherfiles=sorted(otherfiles,key=str.lower)
last_idx=len(otherfiles)-1
# Check if files in dir
if len(otherfiles)==0:
print ("No STL files found to display.")
quit()
# Check if file key used
idx=0
for arg in argsList:
if 'file:' in arg:
filename=arg.split(':')[1]
idx=otherfiles.index(os.path.split(filename)[1])
# Extract window size if specified
w,h=240,240
for arg in argsList:
if 'size:' in arg:
size=arg.split(':')[1].split(',')
if len(size)!=2:
print ("'size' value should have format 'width,height', e.g. '320,240'.")
quit()
w,h=int(size[0]),int(size[1])
# Check if we are in automatic screenshot mode
auto=False
for arg in argsList:
if 'auto' in arg:
auto=True
###################################################
print ("Load init file - idx:",idx,otherfiles[idx])
nfilename=otherfiles[idx]
def growImage():
global campos,camfoc,camup,camera,ren,renWin
while isFitImage():
campos[0]=campos[0]/1.1
campos[1]=campos[1]/1.1
camera=vtk.vtkCamera()
camera.SetViewUp(camup)
camera.SetFocalPoint(camfoc)
camera.SetPosition(campos)
ren.SetActiveCamera(camera)
renWin.Render()
fitImage()
def fitImage():
global campos,camfoc,camup,camera,ren,renWin
while not isFitImage():
campos[0]=campos[0]*1.1
campos[1]=campos[1]*1.1
camera=vtk.vtkCamera()
camera.SetViewUp(camup)
camera.SetFocalPoint(camfoc)
camera.SetPosition(campos)
ren.SetActiveCamera(camera)
renWin.Render()
def isFitImage():
global vtk,renWin,idx,nfilename,w,h
#print ("fitImage",idx,filename)
image = vtk.vtkWindowToImageFilter()
image.SetInput(renWin)
image.Update()
writer = vtk.vtkPNGWriter()
writer.SetWriteToMemory(1)
writer.SetInputConnection(image.GetOutputPort())
writer.Write()
shape=image.GetOutput().GetDimensions()
assert shape[2]==1, "Expected 3d dimension to be 1!"
shape=shape[:2]
bpp=image.GetOutput().GetScalarSize()
assert bpp==1, "Expected png image with pixeldata in numpy.uint8!"
#print ("Shape:",shape)
#print ("Bytes per pixel",bpp)
data=numpy.frombuffer(writer.GetResult(),dtype=numpy.uint8)
#print ("data",data.shape,data.dtype)#,data)
im=cv2.imdecode(data,cv2.IMREAD_UNCHANGED)
#print ("im",im.shape,im.dtype)#,data)
fit=True
R,G,B=2,1,0
for x in range(0,w):
blackTop=not numpy.any(im[0,x,:])
blackBot=not numpy.any(im[h-1,x,:])
if not blackTop or not blackBot: fit=False
for y in range(0,h):
blackLeft=not numpy.any(im[y,0,:])
blackRight=not numpy.any(im[y,w-1,:])
if not blackLeft or not blackRight: fit=False
#cv2.imwrite("test.png",im)
return fit
def makePrintScreen():
global vtk,renWin,idx,nfilename
image = vtk.vtkWindowToImageFilter()
image.SetInput(renWin)
image.Update()
writer = vtk.vtkPNGWriter()
barename, ext = os.path.splitext(nfilename)
imgname=os.path.join(filepath,barename+".png")
writer.SetFileName(imgname)
writer.SetInputData(image.GetOutput())
writer.Write()
camIdx=0
camUp=[(0,1,0),(1,0,0),(0,0,1),(0,-1,0),(-1,0,0),(0,0,-1)]
camDirIdx=0
def keypress_callback(obj, ev):
global idx,nfilename,reader,renWin,ren,camPos,camIdx
key = obj.GetKeySym()
if key=='KP_Left' or key=='Left':
idx=idx-1
if idx<0:
idx=0
else:
nfilename=otherfiles[idx]
#reader.SetFileName(nfilename)
loadFile()
print ("Load prev file - idx:",idx,nfilename)
if key=='KP_Right' or key=='Right':
idx=idx+1
if idx>last_idx:
idx=last_idx
else:
nfilename=otherfiles[idx]
#reader.SetFileName(nfilename)
loadFile()
print ("Load next file - idx:",idx,nfilename)
if key=='space':
print ("Save print screen of ",idx,nfilename)
makePrintScreen()
if key=='Escape': quit()
if key=='s':
print ("Shrink to fit image")
fitImage()
if key=='g':
print ("Grow to fit image")
growImage()
if key=='KP_Up' or key=="Up":
print ("Change up vector")
global campos,camfoc,camup,camera,ren,renWin
global camUp,camIdx
camIdx=camIdx+1
if camIdx>5: camIdx=0
if camIdx<0: camIdx=5
camup=camUp[camIdx]
camera=vtk.vtkCamera()
camera.SetViewUp(camup)
camera.SetFocalPoint(camfoc)
camera.SetPosition(campos)
ren.SetActiveCamera(camera)
renWin.Render()
if key=='KP_Down' or key=="Down":
global camDirIdx
camDirIdx=camDirIdx+1
if camDirIdx>3: camDirIdx=0
if camDirIdx==1: campos[1]=-campos[1]
if camDirIdx==2: campos[0]=-campos[0]
if camDirIdx==3: campos[1]=-campos[1]
if camDirIdx==0: campos[0]=-campos[0]
camera=vtk.vtkCamera()
camera.SetViewUp(camup)
camera.SetFocalPoint(camfoc)
camera.SetPosition(campos)
ren.SetActiveCamera(camera)
renWin.Render()
campos=[0,0,0]
camfoc=[0,0,0]
camup=[0,0,0]
camera=None
def loadFile():
global actor,nfilename,vtk,ren,reader,iren, renWin,loading
global camera,campos,camfoc,camup
if loading: return
loading=True
ren.SetBackground(1,0,0)
renWin.Render()
renWin.SetWindowName("STLViewer - loading...")
reader = vtk.vtkSTLReader()
reader.SetFileName(os.path.join(filepath,nfilename))
mapper = vtk.vtkPolyDataMapper()
if vtk.VTK_MAJOR_VERSION <= 5:
mapper.SetInput(reader.GetOutput())
else:
mapper.SetInputConnection(reader.GetOutputPort())
renWin.RemoveRenderer(ren)
ren = vtk.vtkRenderer()
renWin.AddRenderer(ren)
ren.RemoveActor(actor)
actor = vtk.vtkActor()
actor.SetMapper(mapper)
ren.AddActor(actor)
#iren.Initialize()
addText("")
# Set camera up
#camera=ren.GetActiveCamera()
bnds=actor.GetBounds()
mZ=(bnds[5]+bnds[4])/2
mX=(bnds[1]+bnds[0])/2
mY=(bnds[3]+bnds[2])/2
dX=bnds[1]-bnds[0]
dY=bnds[3]-bnds[2]
dZ=bnds[5]-bnds[4]
#sC=1.5*max(dY,dZ)+1.75*dX
sC=1.4*dZ
#print ('%.2f' % dX,'%.2f' % dY,'%.2f' % dZ,"->",'%.2f' % sC)
#changeText(str())
camera=vtk.vtkCamera()
camera.SetViewUp(0,0,1)
camera.SetFocalPoint(mX,mY,mZ)
camup=[0,0,1]
camfoc=[mX,mY,mZ]
#sC is not enough, a fatter object is closer to the cam.
#camera.SetPosition(sC+2.5*dX/2,0,mZ)
campos=[sC,-sC,mZ]
camera.SetPosition(campos)
#print (camera.GetOrientation())
ren.SetActiveCamera(camera)
fitImage()
renWin.SetWindowName("STLViewer - "+nfilename.split('.')[-2])
ren.SetBackground(0,0,0)
renWin.Render()
loading=False
# Create a rendering window and renderer
renWin = vtk.vtkRenderWindow()
renWin.SetWindowName("STLViewer")
renWin.SetSize(w,h)
ren = vtk.vtkRenderer()
reader=None;
# Create a debug message actor
txt=None
def addText(msg="Hello world!"):
global txt
txt = vtk.vtkTextActor()
txt.SetInput(msg)
txtprop=txt.GetTextProperty()
txtprop.SetFontFamilyToArial()
txtprop.SetFontSize(18)
txtprop.SetColor(250,1,1)
txt.SetDisplayPosition(10,10)
ren.AddActor(txt)
def changeText(msg="New text!"):
global txt
txt.SetInput(msg)
# Create a renderwindowinteractor
iren = vtk.vtkRenderWindowInteractor()
iren.AddObserver('KeyPressEvent', keypress_callback, 1.0)
iren.SetRenderWindow(renWin)
# Assign actor to the renderer
actor=None
if auto:
iren.Initialize()
for idx in range(0,last_idx):
nfilename=otherfiles[idx]
loading=False
loadFile()
makePrintScreen()
quit()
else:
loading=False
loadFile()
# Enable user interface interactor
iren.Initialize()
renWin.Render()
iren.Start()
| true |
b1b878f29f30d129696e889547bd442e04c3527a | Python | RapetiBhargav/MyDataSciencePractice | /MyCode/DataVisualization/ScatterPlots.py | UTF-8 | 896 | 3.40625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 3 16:59:39 2020
@author: bhargav
"""
from sklearn.datasets import load_boston
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Set the palette and style to be more minimal
sns.set(style='ticks', palette='Set2')
# Load data as explained in introductory lesson
boston_data = load_boston()
boston_df = pd.DataFrame(boston_data.data, columns=boston_data.feature_names)
# Create the scatter plot
sns.lmplot(x="CRIM", y="NOX", data=boston_df)
# Remove excess chart lines and ticks for a nicer looking plot
sns.despine()
#By default, it plots a regression line so you can see potential linear relationships more
#easily. Our variables appear to be somewhat positively correlated.
#The lighter shade around the line is the 95% confidence interval for our regression line and
#is calculated using bootstraps of our data.
| true |
f8943dd24312bc0f47ea44f446a3d7e226753c57 | Python | jin38895/nn_Scratch | /nn_scratch.py | UTF-8 | 3,077 | 3.765625 | 4 | [] | no_license | # For matrix operations as all input, output and weights are in matrix form
import numpy as np
# Dataset
train_data = np.array([[1,0,1],[1,1,1],[0,1,0],[0,0,0]])
train_labels = np.array([[1,1,1,0]]).T
test_data = np.array([[1,1,0],[1,0,0]])
# Class of a neural network of 2 hidden layers
class nn():
# initializing weights for both hidden layers
def __init__(self):
self.__layer1_weights = 2*(np.random.random(train_data.shape).T)-1
self.__layer2_weights = 2*np.random.random(train_labels.shape)-1
# activating function of the perceptron
def activate(self,x,deriv=False):
if(deriv==True):
return x*(1-x)
return 1/(1+np.exp(-x))
# training our neural network
def train(self ,x,y):
for i in range(60000): # You can change number of iterations according to dataset
# initializing all layers
input_layer = x # Input Layer
h_layer1 = self.activate(np.dot(x,self.__layer1_weights)) # 1st hidden layer
h_layer2 = self.activate(np.dot(h_layer1,self.__layer2_weights)) # 2nd hidden layer
output_layer = h_layer2 # Output Layer
# Calculating errors and gradients for both hidden layers
e_layer2 = y - output_layer # Error in hidden layer 2
g_layer2 = e_layer2*self.activate(h_layer2,deriv=True) # Gradient to minimize error in hidden layer 2
e_layer1 = g_layer2.dot((self.__layer2_weights).T) # Error in hidden layer 1
g_layer1 = e_layer1*self.activate(h_layer1,deriv = True) # Gradient to minimize error in hidden layer 1
# Updating our original weights using gradients
self.__layer2_weights += h_layer1.T.dot(g_layer2)
self.__layer1_weights += input_layer.T.dot(g_layer1)
# testing of our neural network
def test(self,x):
input_layer = x
h_layer1 = self.activate(np.dot(x,self.__layer1_weights))
h_layer2 = self.activate(np.dot(h_layer1,self.__layer2_weights))
output_layer = h_layer2
return output_layer
nn =nn() # Object creation of our model
nn.train(x=train_data,y=train_labels) # training of our model
print(nn.test(test_data)) # testing of our model | true |
f5bf3381f7b553768293fafc3e9fa718feb7b6d8 | Python | joshuajz/Borg | /courses/database/queens.py | UTF-8 | 1,827 | 2.765625 | 3 | [] | no_license | import json
import requests
from methods.database import Courses_DB
base = "https://api.qmulus.io/v1/courses/"
async def get_info(offset=0):
parameters = {
"limit": "100",
"offset": str(offset),
}
response = requests.get(base, params=parameters)
if response.status_code == 200:
return json.loads(response.content.decode("utf-8"))
else:
return False
async def pull_values():
db = await Courses_DB("queens")
courses = await db.fetch_courses()
offset = 0
while True:
info = await get_info(offset)
if info != False and len(info) != 0:
await place_info(info, courses, db)
offset += 100
else:
break
print("Finished Queens Courses.")
async def place_info(items: list, in_database, db):
for item in items:
course_id = item["id"]
course_code = item["course_code"]
requirements = item["requirements"]
if item["units"] == 0:
continue
if course_id[-1] == "B" or course_id[-1] == "A":
course_id = course_id[0:-1]
if course_code[-1] == "B" or course_code[-1] == "A":
course_code = course_code[0:-1]
if requirements == "":
requirements = None
try:
course_code = int(course_code)
except:
continue
if course_id in in_database:
continue
await db.add_course(
course_id,
int(course_code),
item["department"],
item["course_name"],
item["description"],
requirements=requirements,
academic_level=item["academic_level"],
units=item["units"],
)
| true |
afb4a9cc343f5cff878d7f3efad64a8890a8b94c | Python | KadirCubukcu/DjangoBlog | /image/forms.py | UTF-8 | 865 | 2.5625 | 3 | [] | no_license | from django import forms
from django.utils.translation import ugettext as _
import os
from models import Image
class ImageForm(forms.Form):
image = forms.FileField(label=_('Select an Image File'),
allow_empty_file=False)
def clean_image(self):
"""
Check size, ext and type of the uploaded image
"""
image = self.cleaned_data.get('image')
ext = os.path.splitext(os.path.basename(image.name))[1][1:]
if image._size > Image.MAX_SIZE:
raise forms.ValidationError(_('Max file size: %d MB' %
(Image.MAX_SIZE / 1024**2)))
if ext not in Image.ALLOWED_EXTS or\
image.content_type not in Image.ALLOWED_TYPES:
raise forms.ValidationError(_('The uploaded image is not allowed'))
return image
| true |
c8a510b9f791a4ac9463a3c18e6a892d5b42779b | Python | DanilooSilva/Cursos_de_Python | /Curso_Python_3_UDEMY/banco_dados/criar_grupo.py | UTF-8 | 769 | 2.734375 | 3 | [
"MIT"
] | permissive | from mysql.connector.errors import ProgrammingError
from db import nova_conexao
tabela_grupo = """
CREATE TABLE IF NOT EXISTS GRUPOS(
ID INT AUTO_INCREMENT PRIMARY KEY,
DESCRICAO VARCHAR(30)
)
"""
alterar_tabela_contato_addcampo = """
ALTER TABLE CONTATOS ADD COLUMN IDGRUPO INT
"""
alterar_tabela_contato = """
ALTER TABLE CONTATOS ADD FOREIGN KEY (IDGRUPO)
REFERENCES GRUPOS (ID)
"""
with nova_conexao() as conexao:
try:
cursor = conexao.cursor()
cursor.execute(tabela_grupo)
cursor.execute(alterar_tabela_contato_addcampo)
cursor.execute(alterar_tabela_contato)
except ProgrammingError as e:
print(f'Erro: {e.msg}')
else:
print('Tabela(s) alterada(s) com sucesso!') | true |
9e11e69ff4165046ae28eba1763166acc6d3ba34 | Python | daxm/debt_payoff_optimizer | /payoff_debts.py | UTF-8 | 1,611 | 2.59375 | 3 | [] | no_license | #! /usr/bin/env python3
from helper import *
from ruamel.yaml import YAML
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
logging_format = '%(asctime)s - %(levelname)s:%(filename)s:%(lineno)s - %(message)s'
logging_dateformat = '%Y/%m/%d-%H:%M:%S'
logging_level = logging.INFO
logging_filename = 'output.log'
logging.basicConfig(format=logging_format,
datefmt=logging_dateformat,
filename=logging_filename,
filemode='w',
level=logging_level)
def main():
unsorted_debts = []
userdata_file = 'userdata.yml'
yaml = YAML(typ='safe')
with open(userdata_file, 'r') as stream:
try:
userdata = (yaml.load(stream))
if 'extra_starting_cash' in userdata:
extra_starting_cash = userdata['extra_starting_cash']
else:
extra_starting_cash = 0.0
logging.info(f"Opened and loaded {userdata_file}")
for debt in userdata['debts']:
unsorted_debts.append(Debt(name=debt['name'],
balance=debt['balance'],
interest=debt['interest_rate'],
payment=debt['payment']))
snowball(sort_debts(debts=unsorted_debts), addition_funds=extra_starting_cash)
logging.info("Done.")
except OSError:
logging.error(f"An error has occurred trying to open {userdata_file}.")
exit(1)
if __name__ == '__main__':
main()
| true |
da347a72e0d2e2f9b901af6ecbd3f9c60546880b | Python | coke-killer/matploblibDemo | /three_circles.py | UTF-8 | 1,435 | 2.5625 | 3 | [] | no_license | # __author__: "yudongyue"
# date: 2021/3/25
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.gridspec import GridSpec
import os
import shutil
import time
fig = plt.figure(figsize=(15, 5))
# ax_1 = fig.add_subplot(1, 3, 1)
# ax_2 = fig.add_subplot(132)
# ax_3 = fig.add_subplot(133)
# plt.tight_layout(0)
gs = GridSpec(1, 3, figure=fig) # GridSpec将fiure分为1行3列,每行三个axes,gs为一个matplotlib.gridspec.GridSpec对象,可灵活的切片figure
for one_key in range(3):
# color_list = ['#5A6CA6', '#E9BCC7', '#D98433']
color_list = ['navy', '#E9BCC7', '#D98433']
x_list = [0.38, 0.295, 0.35]
ax = fig.add_subplot(gs[0, one_key])
plt.tight_layout(0)
circle = Circle(xy=(0.5, 0.4), radius=0.4, color=color_list[one_key], alpha=1)
ax.add_patch(circle)
# ax.plot([0.5, 0.5, 0.5], [0.8, 0.81, 0.82], color='red', marker='+')
ax.axis('off')
Ele_data = [['总用电量(KWh)', '日平均用电量(KWh)', '总电费(RMB)'], [8611248, 277782, 5925686]]
ax.text(x_list[one_key], 0.9, Ele_data[0][one_key], fontsize=30, color='black')
ax.text(0.3, 0.4, str(Ele_data[1][one_key]), fontsize=40, color='r')
plt.show()
path = './/plot_folder_user//'
if os.path.isdir(path):
shutil.rmtree(path)
time.sleep(2)
os.makedirs(path)
else:
os.makedirs(path)
plt.savefig(path + '总用电量统计.jpg')
plt.cla()
plt.close("all")
| true |
2fed26f8168b710f672c1ec1c9eb3bd37056ede0 | Python | seoljeongwoo/learn | /algorithm/boj_2159.py | UTF-8 | 557 | 2.8125 | 3 | [] | no_license | import sys
input = sys.stdin.readline
n = int(input())
sx,sy = map(int,input().split())
direction = [(-1,0), (1,0), (0,-1) , (0,1)]
ans = 0
xy = [(sx,sy)] * 5
dist = [0]*5
for _ in range(n):
u,v = map(int,input().split())
new_lst = [(u,v)] + list((u+dx,v+dy) for dx,dy in direction)
new_dist = [int(1e12)+5]*5
for i in range(5):
px,py = xy[i]
for j in range(5):
cx,cy = new_lst[j]
new_dist[j] = min(new_dist[j] , dist[i] + abs(px-cx) + abs(py-cy))
xy , dist = new_lst, new_dist
print(min(dist))
| true |
58da99a85e3826d28bf1fa5f522299bc6532f221 | Python | KimBitrus26/json_formatter_and_validator | /app/models.py | UTF-8 | 770 | 2.625 | 3 | [] | no_license | from app import db, ma
#user model
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key = True)
username = db.Column(db.String(50), nullable=False)
email = db.Column(db.String(100), nullable=False)
password = db.Column(db.String(300), nullable=False)
#constructor
def __init__(self, username, email, password):
self.username = username
self.email = email
self.password = password
class UserSchema(ma.Schema):
class Meta:
model = User
sqla_session = db.session
fields = ('id','username','email','password')
user_schema = UserSchema()
users_schema = UserSchema(many=True)
#programmatic creating database
db.create_all()
| true |
29a6ff9c543ef7ab322707e21cc6dc6dff2fb46a | Python | nyedun22/carbon-crush | /main.py | UTF-8 | 40,675 | 2.984375 | 3 | [] | no_license | from replit import web
import flask
app = flask.Flask(__name__)
#displays home page
@app.route('/')
def index():
return flask.render_template('index.html')
#displays information page
@app.route('/info/')
def info():
return flask.render_template('info.html')
#displays pledge page
@app.route('/pledge/', methods =['GET','POST'])
def pledge():
pledgesresult=[]
if flask.request.method == "POST":
#print(flask.request.form.getlist('pledges'))
pledgesresult = flask.request.form.getlist('pledges')
print(pledgesresult)
#open file object and write to pledgesmade
#file.
with open('data/pledgesmade.txt','w') as f:
f.write(str(pledgesresult))
print(pledgesresult)
#now flash message to user to say that pledges
#have been recorded.
#return '<h4>Your pledges are <br> {} </h4>'.format(pledgesresult,sep=',')
return flask.render_template('pledge.html', pledgesresult=pledgesresult)
#displays contact page
@app.route('/contact/')
def contact():
return flask.render_template('contact.html')
#displays calculator page
@app.route('/calculator/', methods = ['GET','POST'])
def calculator():
# Values needed in the calculator
fly_co2 = 0.115
fly_speed = 1000
global carbon_emission , carbon_emission_travel , carbon_emission_diet, carbon_emission_diet
# Making sure the form was filled in with all the relevant values
if flask.request.method == "POST":
how_long_car = float(flask.request.form.get('driven_miles'))
type_car = int(flask.request.form.get('type_car'))
bus_how_many = float(flask.request.form.get('bus_how_many'))
bus_how_long = float(flask.request.form.get('bus_how_long'))
train_how_many = float(flask.request.form.get('train_how_many'))
train_how_long = float(flask.request.form.get('train_how_long'))
fly_how_long = float(flask.request.form.get('fly_how_long'))
diet_type = float(flask.request.form.get('diet_type'))
energy_usage = float(flask.request.form.get('energy_usage'))
energy_type = float(flask.request.form.get('energy_type'))
carbon_emission = ''
carbon_emission_travel = ''
carbon_emission_diet = ''
carbon_emission_energy = ''
if type_car == 1:
carbon_emission_travel = (fly_how_long * fly_speed * fly_co2) + (train_how_long * 52 * train_how_many * 0.0366 * 10/6) + (bus_how_long * 52 * bus_how_many * 0.1 * 0.5)
if (diet_type == 1) :
carbon_emission_diet = 2049
if energy_type == 1:
carbon_emission_energy = 0.997 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return ''' <h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 2:
carbon_emission_energy = 0.408 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: kg/yr </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 3 :
carbon_emission_energy = 0.861 * 12* energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 4 :
carbon_emission_energy = 0.2 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif (diet_type == 2):
carbon_emission_diet = 1387
if energy_type == 1:
carbon_emission_energy = 0.997 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 2:
carbon_emission_energy = 0.408 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 3 :
carbon_emission_energy = 0.861 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: kg/yr </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 4 :
carbon_emission_energy = 0.2 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif (diet_type == 3):
carbon_emission_diet = 1052
if energy_type == 1:
carbon_emission_energy = 0.997 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 2:
carbon_emission_energy = 0.408 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 3 :
carbon_emission_energy = 0.861 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {}kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 4 :
carbon_emission_energy = 0.2 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif type_car == 2:
carbon_emission_travel = (0.2 * how_long_car) + (fly_how_long * fly_speed * fly_co2) + (train_how_long * 52 * train_how_many * 0.0366 * 10/6) + (bus_how_long * 52 * bus_how_many * 0.1 * 0.5)
if (diet_type == 1) :
carbon_emission_diet = 2049
if energy_type == 1:
carbon_emission_energy = 0.997 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: kg/yr </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 2:
carbon_emission_energy = 0.408 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 3 :
carbon_emission_energy = 0.861 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 4 :
carbon_emission_energy = 0.2 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif (diet_type == 2):
carbon_emission_diet = 1387
if energy_type == 1:
carbon_emission_energy = 0.997 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 2:
carbon_emission_energy = 0.408 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 3 :
carbon_emission_energy = 0.861 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {}kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 4 :
carbon_emission_energy = 0.2 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {}kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif (diet_type == 3):
carbon_emission_diet = 1052
if energy_type == 1:
carbon_emission_energy = 0.997 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 2:
carbon_emission_energy = 0.408 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 3 :
carbon_emission_energy = 0.861 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {}kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 4 :
carbon_emission_energy = 0.2 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif type_car == 3 :
carbon_emission_travel = (0.12 * how_long_car) + (fly_how_long * fly_speed * fly_co2) + (train_how_long * 52 * train_how_many * 0.0366 * 10/6) + (bus_how_long * 52 * bus_how_many * 0.1 * 0.5)
if (diet_type == 1) :
carbon_emission_diet = 2049
if energy_type == 1:
carbon_emission_energy = 0.997 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 2:
carbon_emission_energy = 0.408 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 3 :
carbon_emission_energy = 0.861 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 4 :
carbon_emission_energy = 0.2 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif (diet_type == 2):
carbon_emission_diet = 1387
if energy_type == 1:
carbon_emission_energy = 0.997 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 2:
carbon_emission_energy = 0.408 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 3 :
carbon_emission_energy = 0.861 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 4 :
carbon_emission_energy = 0.2 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif (diet_type == 3):
carbon_emission_diet = 1052
if energy_type == 1:
carbon_emission_energy = 0.997 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 2:
carbon_emission_energy = 0.408 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 3 :
carbon_emission_energy = 0.861 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 4 :
carbon_emission_energy = 0.2 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif type_car == 4 :
carbon_emission_travel = 0.105 * how_long_car + fly_how_long * fly_speed * fly_co2 + train_how_long * 52 * train_how_many * 0.0366 * 10/6 + bus_how_long * 52 * bus_how_many * 0.1 * 0.5
if (diet_type == 1) :
carbon_emission_diet = 2049
if energy_type == 1:
carbon_emission_energy = 0.997 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 2:
carbon_emission_energy = 0.408 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 3 :
carbon_emission_energy = 0.861 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 4 :
carbon_emission_energy = 0.2 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif (diet_type == 2):
carbon_emission_diet = 1387
if energy_type == 1:
carbon_emission_energy = 0.997 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 2:
carbon_emission_energy = 0.408 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 3 :
carbon_emission_energy = 0.861 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 4 :
carbon_emission_energy = 0.2 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif (diet_type == 3):
carbon_emission_diet = 1052
if energy_type == 1:
carbon_emission_energy = 0.997 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 2:
carbon_emission_energy = 0.408 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 3 :
carbon_emission_energy = 0.861 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 4 :
carbon_emission_energy = 0.2 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif type_car == 5 :
carbon_emission_travel = (0.08 * how_long_car) + (fly_how_long * fly_speed * fly_co2) + (train_how_long * 52 * train_how_many * 0.0366 * 10/6) + (bus_how_long * 52 * bus_how_many * 0.1 * 0.5)
if (diet_type == 1) :
carbon_emission_diet = 2049
if energy_type == 1:
carbon_emission_energy = 0.997 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 2:
carbon_emission_energy = 0.408 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 3 :
carbon_emission_energy = 0.861 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {}kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 4 :
carbon_emission_energy = 0.2 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif (diet_type == 2):
carbon_emission_diet = 1387
if energy_type == 1:
carbon_emission_energy = 0.997 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 2:
carbon_emission_energy = 0.408 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 3 :
carbon_emission_energy = 0.861 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 4 :
carbon_emission_energy = 0.2 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {}kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif (diet_type == 3):
carbon_emission_diet = 1052
if energy_type == 1:
carbon_emission_energy = 0.997 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 2:
carbon_emission_energy = 0.408 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {}kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 3 :
carbon_emission_energy = 0.861 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 4 :
carbon_emission_energy = 0.2 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif (diet_type == 2):
carbon_emission_diet = 1387
if energy_type == 1:
carbon_emission_energy = 0.997 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 2:
carbon_emission_energy = 0.408 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 3 :
carbon_emission_energy = 0.861 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {}kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {}kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 4 :
carbon_emission_energy = 0.2 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {}kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif (diet_type == 3):
carbon_emission_diet = 1052
if energy_type == 1:
carbon_emission_energy = 0.997 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 2:
carbon_emission_energy = 0.408 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {}kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 3 :
carbon_emission_energy = 0.861 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
elif energy_type == 4 :
carbon_emission_energy = 0.2 * 12 * energy_usage
carbon_emission = carbon_emission_diet + carbon_emission_energy + carbon_emission_travel
return '''<h4>Your carbon footprint is {} kg/yr </h4> <br>
<p>Let's break it down: kg/yr </p>
<ul>
<li> Travel : {} kg/yr </li>
<li> Diet : {} kg/yr </li>
<li> Energy : {} kg/yr </li>
</ul>
'''.format(carbon_emission , carbon_emission_travel, carbon_emission_diet, carbon_emission_energy)
return flask.render_template('calculator.html')
#displays leaderboard
@app.route('/leaderboard/')
def leaderboard():
return flask.render_template('leaderboard.html')
#displays scores from quiz and pledge page
@app.route('/your_scores/',methods=["GET", "POST"])
def your_scores():
return flask.render_template('your_scores.html')
#displays information about queen queens team
@app.route('/green_queens/')
def green_queens():
return flask.render_template('green_queens.html')
#displays quiz page
@app.route('/quiz/')
def quiz():
return flask.render_template('quiz.html')
@app.route('/game_home/')
def qhome():
return flask.render_template('quiz_home.html')
@app.route('/your_scores_profile/')
def your_scores_profile():
return flask.render_template('your_scores_profile.html')
# Start the app running and listening on a known port
#must be here or app wont Run
web.run(app)
| true |
823f6f4abc855ce2f4c02f91f6670e71afdcc193 | Python | Dillon2332/Python-Files | /karatechop.py | UTF-8 | 915 | 3.34375 | 3 | [] | no_license | array_of_int = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 100, 1233, 133]
def chop(num, array):
index_val = len(array)
first_half = array[:int(len(array)/2)]
second_half = array[int(len(array)/2):]
print(f"First half: {first_half}")
print(f"Second half: {second_half}")
if num not in first_half and num not in second_half:
print("-1")
elif first_half == [] or second_half == []:
print("Done")
print(index_val-1)
elif num in first_half:
index_val = [range(0, int(len(array/2)))]
print(index_val)
chop(num, first_half)
elif num in second_half:
index_val = [range((int(len(array)/2)), len(array))]
print(index_val)
chop(num, second_half)
chop(100, array_of_int)
| true |
9b8a4622b1c7b1dcca85a0f1a68d0ac5e900e168 | Python | richardvogg/learning-pytorch | /intro.py | UTF-8 | 1,334 | 3.71875 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 17 17:46:32 2021
@author: Richard
from: https://pytorch.org/tutorials/beginner/blitz/tensor_tutorial.html
"""
import torch
import numpy as np
import torchvision
#%%
# create a tensor from a list
data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)
#%%
# from numpy array
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
#%%
#from another tensor
x_ones = torch.ones_like(x_data) # retains the properties of x_data
print(f"Ones Tensor: \n {x_ones} \n")
x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data
print(f"Random Tensor: \n {x_rand} \n")
test = torch.ones(2,3)
test2 = torch.ones((2,3,))
#%%
#Attributes: shape, data type, device of a tensor
print(f"Shape: {test.shape} \n")
print(f"Data type: {test.dtype} \n")
print(f"Device tensor is stored on: {test.device}")
#%%
#slicing - as in numpy
tensor = torch.ones(4, 4)
tensor[:2,1] = 64
print(tensor)
#%%
#concatenating
#dim = 0: concat along rows
#dim = 1: concat along columns
large_object = torch.cat([tensor,tensor],dim = 0)
#%%
#point-wise multiplication
tensor * tensor
#or
tensor.mul(tensor)
#%%
# matrix multiplication
tensor.matmul(tensor.T)
# or
tensor @ tensor.T
#%%
#in-place operations (use is discouraged)
tensor.add_(2)
print(tensor)
| true |
bd5b72cf538c57dd39f300eb30039ccdaf66fec0 | Python | TakamasaIkeda/-100- | /NLP100/chap1/knock00.py | UTF-8 | 74 | 2.84375 | 3 | [] | no_license | stressed = "stressed"
reverse = stressed[len(stressed)::-1]
print reverse
| true |
1b66cde194abf6fe26b5113fb1f74d8726408213 | Python | InbarShirizly/MAFAT-Challenge | /serve_the_model/mafat_api_local.py | UTF-8 | 3,446 | 2.984375 | 3 | [] | no_license | """
flask api for server:
- upload spectorgran track as a pickle file
- predict for each segments using given model
- present results of prediction with spectrograms in a server, along with image of the full track
- history page to present previous spectrograms in the server
"""
from flask import Flask, render_template, url_for, flash, redirect, request
from werkzeug.utils import secure_filename
import pickle
import numpy as np
import os
from matplotlib.colors import LinearSegmentedColormap
from python_scripts.utils import save_images_and_csv, generate_track_and_segments_data
# configuratiom constants
UPLOAD_FOLDER = r".\uploaded_track_files"
SEGMENTS_IMAGES_FOLDER = r".\static\segment_images"
ALLOWED_EXTENSIONS = ('pkl')
color_map_path = "./data_train/cmap.npy"
cm_data = np.load(color_map_path)
color_map = LinearSegmentedColormap.from_list('parula', cm_data)
# flask app with configuration
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SEGMENTS_FOLDER'] = SEGMENTS_IMAGES_FOLDER
app.config['SECRET_KEY'] = os.urandom(16)
app.config['target_dict'] = {0: "animal", 1: "human"}
@app.route("/")
@app.route("/home")
def home():
return render_template("home.html")
@app.route("/about")
def about():
return render_template("about.html", title="About")
@app.route("/prediction", methods=['POST'])
def prediction():
"""
- check files in the post request and validate the files posted is pickle
- saves images of spectrograms and csv of data
- present predictions and data of each segment in the track in the page
"""
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part', "error")
return redirect(url_for('home'))
file = request.files['file']
# if user does not select file, browser also
# submit an empty part without filename
if file.filename == '':
flash('No selected file', 'warning')
return redirect(url_for('home'))
if not file.filename.endswith(ALLOWED_EXTENSIONS):
flash('File selected is not valid', 'warning')
return redirect(url_for('home'))
flash(f'file {file.filename} uploaded', 'success')
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
with open(os.path.join(app.config['UPLOAD_FOLDER'], filename), "rb") as f:
track_dict = pickle.load(f)
full_track_dict, df = save_images_and_csv(app, track_dict)
df['predictions'] = df['predictions'].round(4)
segment_data = list(df.reset_index().T.to_dict().values())
return render_template("prediction.html", segment_data=segment_data, full_track_dict=full_track_dict)
@app.route("/history")
def history():
"""
present history of predictions - list of tracks with data
"""
files = os.listdir(app.config['SEGMENTS_FOLDER'])
if len(files) <= 3:
flash('There is no history yet', 'warning')
return redirect(url_for('home'))
range_list, segments_list, full_track_dict_list = generate_track_and_segments_data(app, files)
return render_template("history.html", segments_list=segments_list,
full_track_dict_list=full_track_dict_list,
range_list=range_list,
title="history")
if __name__ == '__main__':
app.run(debug=False) | true |
2f5c0ae9114b1312fc59390fc715907935bcaaf9 | Python | M10307431/Jingho | /WSN_simulation/WSNresult/Main_parse.py | UTF-8 | 4,650 | 2.75 | 3 | [] | no_license | import os
import xlwt, xlrd
def parsefile(path, sheet, col):
row=1
sheet.write(row,col+1,"SetAmount_MeetRatio")
sheet.write(row,col+2,"Missratio_perset")
sheet.write(row,col+3,"Meetratio_perset")
sheet.write(row,col+4,"MissLatency_perpkt")
sheet.write(row,col+5,"MeetLatency_perpkt")
sheet.write(row,col+6,"Lifetime")
sheet.write(row,col+7,"AverageEnergy")
row=row+1
rate=80
data=[]
f=open(path,'r')
for i in f:
if i.find("SetAmount_MeetRatio")>=0:
o=i[i.find('=')+1:i.find('\n')]
data.append(o)
if i.find("Missratio_perset")>=0:
o=i[i.find('=')+1:i.find('\n')]
if o.find('-')<0:
data.append(o)
else:
data.append("0")
if i.find("Meetratio_perset")>=0:
o=i[i.find('=')+1:i.find('\n')]
if o.find('-')<0:
data.append(o)
else:
data.append("0")
if i.find("MissLatency_perpkt")>=0:
o=i[i.find('=')+1:i.find('\n')]
if o.find('-')<0:
data.append(o)
else:
data.append("0")
if i.find("MeetLatency_perpkt")>=0:
data.append(i[i.find('=')+1:i.find('\n')])
if i.find("Lifetime")>=0:
data.append(i[i.find('=')+1:i.find('\n')])
if i.find("AverageEnergy")>=0:
data.append(i[i.find('=')+1:i.find('\n')])
if i.find("==============================================")>=0:
sheet.write(row,col+0,str(rate))
sheet.write(row,col+1,data[0])
sheet.write(row,col+2,data[1])
sheet.write(row,col+3,data[2])
sheet.write(row,col+4,data[3])
sheet.write(row,col+5,data[4])
sheet.write(row,col+6,data[5])
sheet.write(row,col+7,data[6])
row=row+1
data=[]
rate+=40
f.close()
def plotdata(filename, sheetname, tag, outfilename):
datasize=8
outfile=open(outfilename, 'w')
read_wb=xlrd.open_workbook(filename)
for i in range(len(read_wb.sheet_names())):
if read_wb.sheet_names()[i]==sheetname:
print read_wb.sheet_names()[i]
s=read_wb.sheet_by_index(i)
#====================Tag Name
#print "rate",
outfile.write("Rate"+" ")
for v in range(0,len(s.row_values(0)),datasize):
#print s.row_values(0)[v],
outfile.write(s.row_values(0)[v]+" ")
#print ""
outfile.write("\n")
#====================Tag Name's index
tagindex=0
while s.row_values(1)[tagindex]!=tag:
tagindex=tagindex+1
#print tag,tagindex
#====================Data
for row in range(2, len(s.col_values(0)), 1):
#print s.row_values(row)[0],
outfile.write(s.row_values(row)[0]+" ")
for v in range(tagindex,len(s.row_values(row)),datasize):
#print s.row_values(row)[v],
outfile.write(s.row_values(row)[v]+" ")
#print ""
outfile.write("\n")
outfile.close()
def main():
filename="Result.xls"
wb=xlwt.Workbook()
#Write file
for l in os.listdir('.'):
if l.find('.')<0:
col=0
sheet=wb.add_sheet(l)
for j in os.listdir('./'+l):
if j.find('.')<0:
path='./'+l+'/'+j+'/FinalResult.txt' #l =>nodenum, j=>approach
print path
try:
f=open(path,'r')
f.close()
print "Get"
sheet.write(0,col,j)
parsefile(path,sheet, col)
col=col+8
except:
print "No file:",path
wb.save(filename)
plotdata(filename, "node3", "Meetratio_perset", "MeetRatio.txt")
plotdata(filename, "node3", "Lifetime", "Lifetime.txt")
plotdata(filename, "Single", "Meetratio_perset", "Single_MeetRatio.txt")
plotdata(filename, "Single", "Lifetime", "Single_Lifetime.txt")
plotdata(filename, "VariedSleep", "Lifetime", "CS_Lifetime.txt")
if __name__=="__main__":
main()
| true |
b1be379d5954967d0604f0fab8211240b4a582b9 | Python | andrewstring/remote-thermometer | /arduino/convert.py | UTF-8 | 1,931 | 3.546875 | 4 | [] | no_license | import collections
class Converter():
def __init__(self, file_name):
self.file_name = file_name
self.data_dict = self.get_calibration(self.file_name)
def get_calibration(self, file_name):
calibration_dict = {}
# open calibration file for reading
with open(self.file_name, 'r') as reader:
for line in reader.readlines():
if line == '\n':
continue
temp, resistance = line.split(' ')
data = [int(temp), int(resistance)]
calibration_dict[data[1]] = data[0]
return calibration_dict
def between(self, input_resistance):
# if resistance is out of range
if input_resistance < min(self.data_dict.keys()) or input_resistance > max(self.data_dict.keys()):
print('out of calibration range')
return None
# if resistance already in calibration file
elif input_resistance in self.data_dict.keys():
return input_resistance
sorted_keys = sorted(self.data_dict.keys())
for index in range(len(sorted_keys)):
if input_resistance < sorted_keys[index]:
break
return (sorted_keys[index], sorted_keys[index - 1])
def get_temp(self, input_resistance):
bounded_by = self.between(input_resistance)
if bounded_by is None:
return
elif isinstance(bounded_by, int):
return self.data_dict[bounded_by]
resistance_one = bounded_by[0]
resistance_two = bounded_by[1]
temp_one = self.data_dict[resistance_one]
temp_two = self.data_dict[resistance_two]
return ((input_resistance - resistance_one) / (resistance_two - resistance_one) * (temp_two - temp_one)) + temp_one
if __name__ == '__main__':
converter = Converter('calibration.txt')
print(converter.get_temp(170000.1)) | true |
c3c47442725c44493ecedf7db35afc322d0109d9 | Python | xwk1993/LearningPython | /basic/2.变量.py | UTF-8 | 66 | 3.390625 | 3 | [] | no_license | name = input('请输入你的姓名:')
print('你好!', name)
| true |
d013f95dadfd457d01158536d7c9e2b559df6a7b | Python | gil9red/SimplePyScripts | /games/tetris/main_console.py | UTF-8 | 8,040 | 2.84375 | 3 | [
"CC-BY-4.0"
] | permissive | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
import sys
import time
from threading import Thread
from typing import Callable
from asciimatics.effects import Print
from asciimatics.renderers import FigletText, StaticRenderer
from asciimatics.event import Event, KeyboardEvent
from asciimatics.screen import Screen
from asciimatics.scene import Scene
from asciimatics.widgets import Frame
from asciimatics.exceptions import StopApplication, NextScene, ResizeScreenError
from board import Board
from piece import PieceO, PieceI, PieceS, PieceZ, PieceL, PieceJ, PieceT
# SOURCE: https://asciimatics.readthedocs.io/en/stable/io.html#colours
# https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
PIECE_BY_COLOR = {
PieceO(0, 0).get_color().name(): Screen.COLOUR_YELLOW,
PieceI(0, 0).get_color().name(): Screen.COLOUR_CYAN,
PieceS(0, 0).get_color().name(): Screen.COLOUR_GREEN,
PieceZ(0, 0).get_color().name(): Screen.COLOUR_RED,
PieceL(0, 0).get_color().name(): Screen.COLOUR_BLUE,
PieceJ(0, 0).get_color().name(): Screen.COLOUR_MAGENTA,
PieceT(0, 0).get_color().name(): Screen.COLOUR_WHITE,
}
class MyLateFigletText(StaticRenderer):
def __init__(self, rendered_text_func: Callable[[], str], **kwargs):
super().__init__()
self.rendered_text_func = rendered_text_func
self.kwargs = kwargs
@property
def rendered_text(self):
renderer = FigletText(
text=self.rendered_text_func(),
**self.kwargs,
)
return renderer.rendered_text
class BoardWidget(Frame):
def __init__(
self,
board: Board,
screen: Screen,
y: int,
x: int,
height: int,
width: int,
next_scene: str,
):
self.y = y
self.x = x
self.height = height
self.width = width
super().__init__(
screen,
height=self.height,
width=self.width,
x=self.x,
y=self.y,
can_scroll=False,
name="BoardWidget",
)
self.set_theme("monochrome")
self.board = board
self.current_piece = self.board.current_piece
self.is_fail = False
self.next_scene = next_scene
self.thread = Thread(target=self._run_timer, daemon=True)
self.thread.start()
def _run_timer(self):
while self.board.do_step():
time.sleep(0.3)
self.is_fail = True
def update(self, frame_no: int):
super().update(frame_no)
if self.is_fail:
raise NextScene(self.next_scene)
self.current_piece = self.board.current_piece
self.screen.set_title(f"Tetris. Score: {self.board.score}")
# Рисование заполненных ячеек
for y, row in enumerate(self.board.matrix):
for x, cell_color in enumerate(row):
if not cell_color:
continue
color = PIECE_BY_COLOR[cell_color.name()]
# TODO: Рисовать квадратами, а не линиями
self.screen.print_at(" ", x + 1, y + 1, bg=color)
if self.current_piece:
color = PIECE_BY_COLOR[self.current_piece.get_color().name()]
for x, y in self.current_piece.get_points():
# TODO: Рисовать квадратами, а не линиями
self.screen.print_at(" ", x + 1, y + 1, bg=color)
def process_event(self, event: Event):
if isinstance(event, KeyboardEvent):
key_code = event.key_code
match key_code:
case 81 | 113: # Q | q
raise StopApplication("User requested exit")
case 87 | 119 | Screen.KEY_UP: # W | w
if self.current_piece:
self.current_piece.turn()
case 65 | 97 | Screen.KEY_LEFT: # A | a
if self.current_piece:
self.current_piece.move_left()
case 68 | 100 | Screen.KEY_RIGHT: # D | d
if self.current_piece:
self.current_piece.move_right()
case 83 | 115 | Screen.KEY_DOWN: # S | s
while self.current_piece and self.current_piece.move_down():
pass
return event
@property
def frame_update_count(self) -> int:
"""
Frame update rate required.
"""
return 5
class NextPieceWidget(Frame):
def __init__(
self,
board: Board,
screen: Screen,
y: int, x: int, height: int, width: int,
):
self.y = y
self.x = x
self.height = height
self.width = width
super().__init__(
screen,
height=self.height,
width=self.width,
y=self.y,
x=self.x,
can_scroll=False,
name="NextPieceWidget",
)
self.set_theme("monochrome")
self.board = board
self.next_piece = self.board.next_piece
def update(self, frame_no: int):
super().update(frame_no)
self.next_piece = self.board.next_piece
if self.next_piece:
x_next = self.x + 3
y_next = self.y
color = PIECE_BY_COLOR[self.next_piece.get_color().name()]
for x, y in self.next_piece.get_points_for_state(x=x_next, y=y_next):
# TODO: Рисовать квадратами, а не линиями
self.screen.print_at(" ", x + 1, y + 1, bg=color)
def process_event(self, event: Event):
return event
@property
def frame_update_count(self) -> int:
return 5
class ScoreWidget(Frame):
def __init__(
self,
board: Board,
screen: Screen,
y: int, x: int, height: int, width: int,
):
self.y = y
self.x = x
self.height = height
self.width = width
super().__init__(
screen,
height=self.height,
width=self.width,
y=self.y,
x=self.x,
can_scroll=False,
name="ScoreWidget",
)
self.set_theme("monochrome")
self.board = board
def update(self, frame_no: int):
super().update(frame_no)
self.screen.print_at(f"Score: {self.board.score}", self.x, self.y)
def process_event(self, event: Event):
return event
@property
def frame_update_count(self) -> int:
return 5
def demo(screen: Screen, scene: Scene):
board = Board()
scenes = [
Scene(
[
BoardWidget(
board,
screen,
y=0,
x=0,
width=board.COLS + 2,
height=board.ROWS + 2,
next_scene="LOSE",
),
NextPieceWidget(
board, screen, y=0, x=board.COLS + 2, width=8, height=6
),
ScoreWidget(board, screen, y=6, x=board.COLS + 2, width=8, height=2),
],
duration=-1,
),
Scene(
[
Print(
screen,
MyLateFigletText(
lambda: f"YOU LOSE!\nScore: {board.score}", font="standard"
),
x=0,
y=screen.height // 3 - 3,
),
],
duration=-1,
name="LOSE",
),
]
screen.play(scenes, stop_on_resize=True, start_scene=scene)
last_scene = None
while True:
try:
Screen.wrapper(
demo,
# TODO:
# catch_interrupt=True,
arguments=[last_scene],
)
sys.exit(0)
except ResizeScreenError as e:
last_scene = e.scene
| true |
a564c07bdc5b5cd015e00f5afac4d87efeb5b983 | Python | alexandraback/datacollection | /solutions_2449486_0/Python/pix1gg/b.py | UTF-8 | 1,464 | 2.703125 | 3 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
import os
import sys
import numpy as np
import scipy as sp
import pylab as pl
def perr(errmsg):
sys.stderr.write(errmsg);
def help(prog):
perr("Usage: %s input\n" % prog);
def check_pattern(pattern):
minval = pattern.min();
if minval > 100:
return True;
[N, M] = pattern.shape;
index = pattern.flatten().tolist().index(minval);
row = int(np.floor(index / M));
col = index % M;
#print minval, row, col;
v = pattern.copy(); v[:, col][v[:, col]==minval] = minval + 100;
#print "v", (v[:, col] > 100).min()
#print np.hstack((pattern, v));
if (v[:, col] > 100).min():
if check_pattern(v):
return True;
h = pattern.copy(); h[row, :][h[row, :]==minval] = minval + 100;
#print "h", (h[:, col] > 100).min();
#print np.hstack((pattern, h));
if (h[row, :] > 100).min():
if check_pattern(h):
return True;
return False;
def main(argv):
try:
inpath = argv[1];
except:
help(argv[0]);
sys.exit(1);
with open(inpath) as infile:
T = int(infile.readline());
for i in range(T):
[N, M] = [int(x) for x in infile.readline().split()];
pattern = np.zeros((N, M), np.int);
for j in range(N):
pattern[j, :] = [int(x) for x in infile.readline().split()];
if (check_pattern(pattern)):
print "Case #%d: YES" % (i+1);
else:
print "Case #%d: NO" % (i+1);
if __name__ == '__main__':
main(sys.argv);
| true |
07dfeb10dfad3f5328a3b81e402eeb77397f7928 | Python | ShanjinurIslam/Online-Judge-Problems | /Codeforces/1333B.py | UTF-8 | 886 | 3.140625 | 3 | [] | no_license | t = int(input())
for k in range(t):
n = int(input())
a = list([int(x) for x in input().split()])
prev = [set()]
for i in range(1,n):
s = set()
s.add(a[i-1])
s = s.union(prev[i-1])
prev.append(s)
b = list([int(x) for x in input().split()])
if(a[0]!=b[0]):
print("NO")
continue
flag = True
for j in range(1,n):
if a[j] != b[j]:
diff = b[j]-a[j]
if diff>0:
if(1 in prev[j]):
continue
else:
print("NO")
flag = False
break
if diff<0:
if(-1 in prev[j]):
continue
else:
print("NO")
flag = False
break
if(flag):
print("YES")
| true |
578e90e0fcb611ec4e4cc43b0162f6adaa94a079 | Python | takin6/algorithm-practice | /at_coder/e869120/03_knapsack_dp/basic/knapsack.py | UTF-8 | 429 | 2.75 | 3 | [] | no_license | N,W = map(int,input().split())
weights = []
vals = []
for _ in range(N):
v,w = map(int,input().split())
weights.append(w)
vals.append(v)
dp = [ [0]*(W+1) for _ in range(N+1)]
for i in range(1, N+1):
wei, val = weights[i-1], vals[i-1]
for w in range(W+1):
if w >= wei:
dp[i][w] = max(dp[i-1][w], dp[i-1][w-wei] + val)
else:
dp[i][w] = max(dp[i][w-1], dp[i-1][w])
print(dp[N][W])
| true |
a270873065ed72f3bc5515099a62dd8903dd639e | Python | RKruizinga/WSD | /customFeatures.py | UTF-8 | 2,469 | 2.609375 | 3 | [] | no_license | import numpy as np
import re
from sklearn.base import BaseEstimator, TransformerMixin
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from sklearn import preprocessing
class CustomFeatures:
class wordCount(TransformerMixin):
def fit(self, X, y=None):
return self
def transform(self, X):
newX = []
for x in X:
newX.append(len(x.split(' ')))
return np.transpose(np.matrix(newX))
class characterCount(TransformerMixin):
def fit(self, X, y=None):
return self
def transform(self, X):
newX = [len(x) for x in X]
return np.transpose(np.matrix(newX))
class userMentions(TransformerMixin):
def fit(self, X, y=None):
return self
def transform(self, X):
newX = []
for x in X:
user_counter = 0
tokens = x.split(' ')
for token in tokens:
if '@username' in token:
user_counter += 1
newX.append(user_counter)
return np.transpose(np.matrix(newX))
class urlMentions(TransformerMixin):
def fit(self, X, y=None):
return self
def transform(self, X):
newX = []
for x in X:
url_counter = 0
tokens = x.split(' ')
for token in tokens:
if 'url' in token:
url_counter += 1
newX.append(url_counter)
return np.transpose(np.matrix(newX))
class hashtagUse(TransformerMixin):
def fit(self, X, y=None):
return self
def transform(self, X):
newX = []
for x in X:
hashtag_counter = 0
tokens = x.split(' ')
for token in tokens:
if '#' in token:
hashtag_counter += 1
newX.append(hashtag_counter)
return np.transpose(np.matrix(newX))
class sentiment(TransformerMixin):
def fit(self, X, y=None):
return self
def transform(self, X):
newX = []
sid = SentimentIntensityAnalyzer()
for x in X:
newX.append(round(sid.polarity_scores(x)['pos']-sid.polarity_scores(x)['neg'], 2))
return np.transpose(np.matrix(newX))
class emoticonUse(TransformerMixin):
def fit(self, X, y=None):
return self
def transform(self, X):
newX = []
for x in X:
#print(token)
emoticon_counter = len(re.findall(r'(:\(|:\))', x))
if emoticon_counter > 0:
emoticon_counter = 1
newX.append(emoticon_counter)
return np.transpose(np.matrix(newX))
| true |
911a2ad3bdef879825fdc91e3d52c9762158b634 | Python | chuzcjoe/Leetcode | /1202. Smallest String With Swaps.py | UTF-8 | 936 | 3.15625 | 3 | [] | no_license | class Solution:
def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
graph = collections.defaultdict(list)
ans = []
for i,j in pairs:
graph[i].append(j)
graph[j].append(i)
f = {}
def find(x):
f.setdefault(x,x)
if x != f[x]:
f[x] = find(f[x])
return f[x]
def union(x,y):
f[find(x)] = find(y)
for x,y in pairs:
union(x,y)
cluster = collections.defaultdict(list)
for i in range(len(s)):
cluster[find(i)].append(s[i])
for c in cluster.keys():
cluster[c].sort(reverse=True)
for j in range(len(s)):
ans.append(cluster[find(j)].pop())
return "".join(ans) | true |
1eddc29405c1ed5d18502182413961cc48d8e139 | Python | javacode123/oj | /swordOffer/ugly_num.py | UTF-8 | 649 | 2.96875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
# @Time : 2019-09-06 16:57
# @Author : Zhangjialuo
# @mail : zhang_jia_luo@foxmail.com
# @File : ugly_num.py
# @Software: PyCharm
# -*- coding:utf-8 -*-
class Solution:
def GetUglyNumber_Solution(self, index):
# write code here
if index == 1:
return 1
res = [1]
p2, p3, p5 = 0, 0, 0
for i in range(index):
temp = min(res[0] * 2, res[p3] * 3, res[p5] * 5)
res.append(temp)
if temp % 2 == 0:
p2 += 1
elif temp % 3 == 0:
p3 += 1
else:
p5 += 1
return res[index] | true |
3226e34f4df893514144999ae5a44dfe5e399a52 | Python | agoncecelia/datascience | /lists.py | UTF-8 | 102 | 3.0625 | 3 | [] | no_license | studentat = ["Agon Cecelia", "Taulant Fisteku", "Agon Cecelia"]
print(studentat)
studentat[2] = "Filan Fisteku"
print(studentat)
| true |
dc50d26b0ff4d2489c59da4897f361472e2527ae | Python | jamesben6688/slgbuilder | /slgbuilder/qpbobuilder.py | UTF-8 | 4,382 | 2.6875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | import numpy as np
import thinqpbo
from .graphobject import GraphObject
from .slgbuilder import SLGBuilder
class QPBOBuilder(SLGBuilder):
def __init__(self, estimated_nodes=0, estimated_edges=0, flow_type=np.int32, jit_build=True):
"""Creates a helper for creating and solves a maxflow graph using the QPBO implementation Vladimir Kolmogorov.
int (int32), float (float32) or double (float64) edge capacities/energies are supported.
This class requires the ```thinqpbo``` Python package available on PyPi or https://github.com/Skielex/thinqpbo.
It uses a modified version of QPBO algorithm by Vladimir Kolmogorov availble at https://github.com/Skielex/QPBO.
The QPBO algorithm uses the BK maxflow implementation, which is a Augmenting-Path type algorithm.
"""
super().__init__(estimated_nodes=estimated_nodes, estimated_edges=estimated_edges, flow_type=flow_type, jit_build=jit_build)
def _add_nodes(self, graph_object):
return self.graph.add_node(graph_object.data.size)
def _set_flow_type_and_inf_cap(self, flow_type):
if flow_type == np.int32:
self.flow_type = np.int32
self.inf_cap = self.INF_CAP_INT32
elif flow_type == np.float32:
self.flow_type = np.float32
self.inf_cap = self.INF_CAP_FLOAT32
elif flow_type == np.float64:
self.flow_type = np.float64
self.inf_cap = self.INF_CAP_FLOAT64
else:
raise ValueError("Invalid flow_type '%s'. Only 'int32', 'float32' and 'float64' allowed.")
def create_graph_object(self):
if self.flow_type == np.int32:
self.graph = thinqpbo.QPBOInt(self.estimated_nodes, self.estimated_edges)
elif self.flow_type == np.float32:
self.graph = thinqpbo.QPBOFloat(self.estimated_nodes, self.estimated_edges)
elif self.flow_type == np.float64:
self.graph = thinqpbo.QPBODouble(self.estimated_nodes, self.estimated_edges)
else:
raise ValueError("Invalid flow_type '%s'. Only 'int32', 'float32' and 'float64' allowed.")
def add_object(self, graph_object, pack_nodes=False):
if graph_object in self.objects:
# If object is already added, return its id.
return self.objects.index(graph_object)
# Add object to graph.
object_id = len(self.objects)
if self.jit_build:
first_id = (np.min(self.nodes[-1]) + self.objects[-1].data.size) if self.objects else 0
else:
first_id = self._add_nodes(graph_object)
self.objects.append(graph_object)
self.nodes.append(first_id)
if pack_nodes:
self.nodes[-1] = self.pack_object_nodes(graph_object)
return object_id
def add_unary_terms(self, i, e0, e1):
if self.graph is None:
i, e0, e1 = np.broadcast_arrays(i, e0, e1)
self.unary_nodes.append(i.flatten().astype(np.int32))
self.unary_e0.append(e0.flatten().astype(self.flow_type))
self.unary_e1.append(e1.flatten().astype(self.flow_type))
else:
np.vectorize(self.graph.add_unary_term, otypes=[np.bool])(i, e0, e1)
def add_pairwise_terms(self, i, j, e00, e01, e10, e11):
if self.graph is None:
i, j, e00, e01, e10, e11 = np.broadcast_arrays(i, j, e00, e01, e10, e11)
self.pairwise_from.append(i.flatten().astype(np.int32))
self.pairwise_to.append(j.flatten().astype(np.int32))
self.pairwise_e00.append(e00.flatten().astype(self.flow_type))
self.pairwise_e01.append(e01.flatten().astype(self.flow_type))
self.pairwise_e10.append(e10.flatten().astype(self.flow_type))
self.pairwise_e11.append(e11.flatten().astype(self.flow_type))
else:
return np.vectorize(self.graph.add_pairwise_term, otypes=[np.int])(i, j, e00, e01, e10, e11)
def get_labels(self, i):
if isinstance(i, GraphObject):
return self.get_labels(self.get_nodeids(i))
return np.vectorize(self.graph.get_label, otypes=[np.int8])(i)
def solve(self, compute_weak_persistencies=True):
self.build_graph()
self.graph.solve()
if compute_weak_persistencies:
self.graph.compute_weak_persistencies()
return self.graph.compute_twice_energy()
| true |
e8f8c71667c94fbd5d9ac1c36a5a8b327175fec4 | Python | HVA-FRC-3824/RoHAWKticsScoutingPythonServer | /src/data_models/team_pick_ability.py | UTF-8 | 5,665 | 2.6875 | 3 | [] | no_license | from .data_model import DataModel
from calculators.team_calculator import TeamCalculator
class TeamPickAbility(DataModel):
'''Data about a team's strength as a specific type of pick'''
def __init__(self, d=None):
DataModel.__init__(self)
self.team_number = -1
self.nickname = ""
self.pick_ability = 0.0
self.manual_ranking = -1
self.top_line = ""
self.second_line = ""
self.third_line = ""
self.robot_picture_filepath = ""
self.yellow_card = False
self.red_card = False
self.stopped_moving = False
self.picked = False
self.dnp = False
if d is not None:
self.set(d)
@staticmethod
def calculate_first_pick_ability(team_number, database):
tpa = TeamPickAbility()
tpa.team_number = team_number
tc = TeamCalculator(team_number, database)
tpa.pick_ability = tc.first_pick_ability()
pit = database.get_team_pit_data(team_number)
if(pit.robot_picture_default > -1 and pit.robot_picture_default < len(pit.robot_pictures)):
tpa.robot_picture_filepath = pit.robot_pictures[pit.robot_picture_default].filepath
calc = database.get_team_calculated_data(team_number)
tpa.yellow_card = calc.yellow_card.total > 0
tpa.red_card = calc.red_card.total > 0
tpa.stopped_moving = calc.stopped_moving.total > 1
tpa.top_line = ("PA: {0:0.2f} Average High Goal Balls: Auto {1:0.2f}, Teleop {2:0.2f}"
.format(tpa.pick_ability, calc.auto_shooting.high.made.average,
calc.teleop_shooting.high.made.average))
tpa.second_line = ("Average Gears: Auto {0:0.2f}, Teleop {1:0.2f}"
.format(calc.auto_gears.total.placed.average,
calc.teleop_gears.total.placed.average))
tpa.third_line = ("Climb: Success Percentage {0:0.2f}%, Time {1:0.2f}s"
.format(calc.climb.success_percentage * 100, calc.climb.time.average))
tpa.fourth_line = ""
return tpa
@staticmethod
def calculate_second_pick_ability(team_number, database):
tpa = TeamPickAbility()
tpa.team_number = team_number
tc = TeamCalculator(team_number, database)
tpa.pick_ability = tc.second_pick_ability()
pit = database.get_team_pit_data(team_number)
if(pit.robot_picture_default > -1 and pit.robot_picture_default < len(pit.robot_pictures)):
tpa.robot_picture_filepath = pit.robot_pictures[pit.robot_picture_default].filepath
calc = database.get_team_calculated_data(team_number)
tpa.yellow_card = calc.yellow_card.total > 0
tpa.red_card = calc.red_card.total > 0
tpa.stopped_moving = calc.stopped_moving.total > 1
# qual = database.get_team_qualitative_data(team_number)
tpa.top_line = ("PA: {0:0.2f} Average High Goal Balls: Auto {1:0.2f}, Teleop {2:0.2f}"
.format(tpa.pick_ability, calc.auto_shooting.high.made.average,
calc.teleop_shooting.high.made.average))
'''
tpa.top_line = ("PA: {0:0.2f} Defense: {1:d} Control: {2:d} Speed: {3:d} Torque: {3:d}"
.format(tpa.pick_ability,
qual.defense.rank,
qual.control.rank,
qual.speed.rank,
qual.torque.rank))
'''
tpa.second_line = ("Average Gears: Auto {0:0.2f}, Teleop {1:0.2f}"
.format(calc.auto_gears.total.placed.average,
calc.teleop_gears.total.placed.average))
tpa.third_line = ("Climb: Success Percentage {0:0.2f}%, Time {1:0.2f}s"
.format(calc.climb.success_percentage * 100, calc.climb.time.average))
tpa.fourth_line = ("Weight: {0:0.2f} lbs, PL: {1:s}"
.format(pit.weight, pit.programming_language))
return tpa
@staticmethod
def calculate_third_pick_ability(team_number, database):
tpa = TeamPickAbility()
tpa.team_number = team_number
tc = TeamCalculator(team_number, database)
tpa.pick_ability = tc.third_pick_ability()
pit = database.get_team_pit_data(team_number)
if(pit.robot_picture_default > -1 and pit.robot_picture_default < len(pit.robot_pictures)):
tpa.robot_picture_filepath = pit.robot_pictures[pit.robot_picture_default].filepath
calc = database.get_team_calculated_data(team_number)
tpa.yellow_card = calc.yellow_card.total > 0
tpa.red_card = calc.red_card.total > 0
tpa.stopped_moving = calc.stopped_moving.total > 1
tpa.top_line = ("PA: {0:0.2f} Average High Goal Balls: Auto {1:0.2f}, Teleop {2:0.2f}"
.format(tpa.pick_ability, calc.auto_shooting.high.made.average,
calc.teleop_shooting.high.made.average))
tpa.second_line = ("Average Gears: Auto {0:0.2f}, Teleop {1:0.2f}"
.format(calc.auto_gears.total.placed.average,
calc.teleop_gears.total.placed.average))
tpa.third_line = ("Climb: Success Percentage {0:0.2f}%, Time {1:0.2f}s"
.format(calc.climb.success_percentage * 100, calc.climb.time.average))
tpa.fourth_line = ("Weight: {0:0.2f} lbs, PL: {1:s}"
.format(pit.weight, pit.programming_language))
return tpa
| true |
f9dc5d67b1912f6ffc6121bfc6378299e09538b8 | Python | lj72808up/ML_Handcraft | /ml/supervised/LinearRegression.py | UTF-8 | 1,702 | 3.25 | 3 | [
"Apache-2.0"
] | permissive | # -*- coding: utf-8 -*-
# 本文实现线性回归预测波士顿房价
import numpy as np
import pandas as pd
def getData():
data = pd.read_csv("../datasets/boston.csv")
m = data.shape[0] # 输入个数
price_raw = data['price'].as_matrix().reshape(m,1)
features_raw = data.drop('price',axis=1).as_matrix()
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler() # 此处进行数据的归一化,才能适应后面的线性回归, 不至于多次循环后出现Nan问题
price_raw = scaler.fit_transform(price_raw)
features_raw = scaler.fit_transform(features_raw)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(features_raw, price_raw, test_size = 0.2, random_state = 0)
return X_train.T, X_test.T, y_train.T, y_test.T
if __name__ == "__main__":
X_train, X_test, y_train, y_test = getData()
X_train = np.insert(X_train,0,values=1,axis=0) # 第一行增加x0=1
#y_train = y_train.T
# 1. 变量声明
m = X_train.shape[1] # 样本数量
n = X_train.shape[0] # 特征数量
rate = 0.2
W = np.zeros((n,1),dtype="float64")
# 梯度下降
for i in range(10000):
A = np.dot(X_train.T,W).T
# print A-y_train
# print np.sum(np.multiply((A-y_train),X_train),axis=1,keepdims=True)
dW = (1.0/m)*np.sum(np.multiply((A-y_train),X_train),axis=1,keepdims=True) # 按行相加
W -= rate*dW
print "系数矩阵为: "
print W.T
print "回归的输入feature:"
print X_train[:,0]
print "回归的预测输出: "
print np.dot(X_train[:,0],W)
print "实际输出值: "
print(y_train[:,0]) | true |
0c22ff54316038be9fd28cb82a393c85ea6f93b6 | Python | Young9235/dev_inyoung | /python/171205/quiz_16.py | UTF-8 | 264 | 3.234375 | 3 | [] | no_license | txt = 'programing is poet'
print(txt.center(40, '@'));
print('is의 위치는 : ' , txt.find('is'))
print('p는 총', txt.count('p'), '번 나옵니다.')
print('*'.join(txt))
print(txt[0:10].split('/') + txt[11:13].split('/') + txt[14:18].split('/'));
| true |
578e7f5601cbf5dfd0d944f8d56e0ee8855a5292 | Python | MetOffice/stylist | /source/stylist/style.py | UTF-8 | 1,926 | 3.125 | 3 | [
"BSD-3-Clause"
] | permissive | ##############################################################################
# (c) Crown copyright 2019 Met Office. All rights reserved.
# The file LICENCE, distributed with this code, contains details of the terms
# under which the code may be used.
##############################################################################
"""
Classes relating to styles made up of rules.
"""
from abc import ABC
import logging
from typing import List
import stylist.fortran
import stylist.issue
from stylist.rule import Rule
import stylist.source
class Style(ABC):
"""
Abstract parent of all style lists.
"""
__unnamed_tally = 1
def __init__(self, *rules: Rule) -> None:
"""
:param *args: Rules which make up this style.
"""
self.__rules = list(rules)
self.__name = f"Unnamed style {self.__unnamed_tally}"
self.__unnamed_tally += 1
@property
def name(self) -> str:
return self.__name
@name.setter
def name(self, name: str):
self.__name = name
def list_rules(self) -> List[Rule]:
"""
Gets a list of the rules which make up this style.
"""
return self.__rules
def check(self,
source: stylist.source.SourceTree) -> List[stylist.issue.Issue]:
"""
Applies every rule in this style to a source code.
:param source: Source code to inspect.
:return: All issues found in the source.
"""
logging.getLogger(__name__).info(f"Style: {self.name}")
issues: List[stylist.issue.Issue] = []
for rule in self.__rules:
additional_issues = rule.examine(source)
issues.extend(additional_issues)
result = "Failed" if additional_issues else "Passed"
message = f"Rule: {rule.__class__.__name__} - {result}"
logging.getLogger(__name__).info(message)
return issues
| true |
dfe31b382dcc6e33a8fe2f9bd130ebfd711e50f1 | Python | dhoatlin/MemoryManager | /mm.py | UTF-8 | 7,304 | 3.09375 | 3 | [] | no_license | #!/usr/bin/python
from Tkinter import *
from tkFileDialog import *
import math
#line numbers
currentLine = 1.0
totalLines = 0
#page/frame size
pageSize = 512.0
#colors
available = '#82FF86'
taken = '#FF4F4F'
#physical pages
pageFrames = []
#all paging tables
pagingTables = {}
'''------------------------------------------
Defining function to be used during execution
------------------------------------------'''
'''
Browse function for loading a file, uses tkinter library
'''
def browse():
global currentLine, totalLines
file = askopenfile(parent=root, mode='rb',title='Choose a file')
if file != None:
#enable writing to textbox
inputbox.config(state=NORMAL)
outputbox.config(state=NORMAL)
#delete old data from textboxes
inputbox.delete(1.0, END)
outputbox.delete(1.0, END)
#write file to textbox
totalLines = 0
currentLine = 1.0
for line in file:
inputbox.insert(END, line)
totalLines += 1
file.close()
#disbale writing to textbox enable next button
inputbox.config(state=DISABLED)
outputbox.config(state=DISABLED)
nextButton.config(state=NORMAL)
'''
Function for the next button
Tracks which line the program is on and updates the ouputbox/paging frames
'''
def nextStep():
global currentLine, totalLines
#enable writing to output box
outputbox.config(state=NORMAL)
if currentLine <= totalLines:
#grab next line from input box and write to output box
inputLine = inputbox.get(currentLine, currentLine+1)
outputbox.insert(END, '==>' + inputLine)
#parse input line to brief description of what is happening
output = parseInput(inputLine)
outputbox.insert(END, output)
#update current line
currentLine += 1.0
else:
outputbox.insert(END, 'End of simulation')
nextButton.config(state=DISABLED)
#disable output box
outputbox.config(state=DISABLED)
'''
#for debugging: show every process paging table
keys = pagingTables.keys()
keys.sort()
for key in keys:
for i in range(len(pagingTables[key])):
print 'pid: ' + key + ' ' + str(pagingTables[key][i])
print '----------------------'
print '********************'
'''
'''
#for debugging: show contents of every frame
for page in pageFrames:
print page
print '*****************************'
'''
'''
Removes a process from it's frames
after removal, it checks to see if there are any waiting processes
'''
def removeProgram(inputs):
for i in range(len(pageFrames)):
if pageFrames[i]['pid'] == inputs['pid']:
pageFrames[i]['avail'] = True
pageFrames[i]['label'].config(bg=available, text='Free')
pageFrames[i]['pid'] = 'N/A'
#sort keys to follow FIFO
keys = pagingTables.keys()
keys.sort()
for key in keys:
for i in range(len(pagingTables[key])):
if pagingTables[key][i]['status'] == 'waiting':
enough = checkAvailSpace(len(pagingTables[key]))
if enough:
addPhysicalLocation(key, True)
'''
loads a process into it's frames
initializes new process page tables
'''
def loadProgram(inputs):
total = inputs['codeSize'] + inputs['dataSize']
enough = checkAvailSpace(total)
#enough room -> add paging table to program
if enough:
initPageTable(inputs['pid'], total, 'running', inputs['codeSize'])
#add physical location
addPhysicalLocation(inputs['pid'], False)
else:
initPageTable(inputs['pid'], total, 'waiting', inputs['codeSize'])
'''
builds a new paging table without a physical location yet
'''
def initPageTable(pid, total, status, codeTotal):
pagingTables[pid] = []
count = 0
for i in range(total):
if count < codeTotal:
pagingTables[pid].append({'type': 'code', 'logical': str(i), 'status': status})
count += 1
else:
pagingTables[pid].append({'type': 'data', 'logical':str(i), 'status': status})
'''
adds the physical address to the page table
'''
def addPhysicalLocation(pid, restore):
for page in pagingTables[pid]:
for i in range(len(pageFrames)):
if(pageFrames[i]['avail']):
page['physical'] = str(i)
if restore:
page['status'] = 'running'
labelText = page['type'] + '-' + page['logical'] + ' of P' + pid
pageFrames[i]['label'].config(bg=taken, text=labelText)
pageFrames[i]['avail'] = False
pageFrames[i]['pid'] = pid
break
'''
checks if there is enough frames for a new process
returns true if space is available
'''
def checkAvailSpace(total):
found = 0
enough = False
for i in range(len(pageFrames)):
if pageFrames[i]['avail']:
found += 1
if found == total:
enough = True
break
return enough
'''
parses a line from the inputbox
loads and removes programs where needed
prints to output box some information about a new program
'''
def parseInput(inputLine):
global pageSize
splitInput = inputLine.split()
pid = splitInput[0]
if splitInput[1] == '-1':
output = 'End of program ' + pid + '\n'
removeProgram({'pid': pid})
else:
code = splitInput[1]
codePages = int(math.ceil(int(code) / pageSize))
data = splitInput[2]
dataPages = int(math.ceil(int(data) / pageSize))
output = 'Loading program ' + pid + ' into RAM: code=' + code + '(' + str(codePages) + ' page(s))' + ', data=' + data + '(' + str(dataPages) + ' page(s))' + '\n'
loadProgram({'pid': pid, 'codeSize': codePages, 'dataSize': dataPages})
return output
'''---------------------------
Creating the GUI using tkinter
---------------------------'''
#create the main window
root = Tk()
root.title('Memory Manager - Dave Hoatlin')
#making sure window isnt created under any system menu bars like OS X
root.geometry('+50+50')
#setup the menubar
menubar = Menu(root)
fileMenu = Menu(menubar, tearoff=0)
fileMenu.add_command(label='Load', command=browse)
fileMenu.add_separator()
fileMenu.add_command(label='Exit', command=root.quit)
menubar.add_cascade(label='File', menu=fileMenu)
root.config(menu=menubar)
#creating a textbox
inputFrame = Frame(root)
inputbox = Text(inputFrame, height=20, width=30, state=DISABLED)
scrollbar = Scrollbar(inputFrame)
scrollbar.pack(side=RIGHT, fill=Y)
inputbox.pack()
scrollbar.config(command=inputbox.yview)
inputbox.config(yscrollcommand=scrollbar.set)
#create memory frame
memFrame = Frame(root)
for i in range(8):
newLabel = Label(memFrame, text='Free', height=3, width=20, bg=available, relief=SUNKEN)
newLabel.grid(row=i)
pageFrames.append({'label': newLabel, 'avail': True, 'pid': 'N/A'})
#create output frame
outputFrame = Frame(root)
outputbox = Text(outputFrame, height = 20, width=70, state=DISABLED)
outScrollbar = Scrollbar(outputFrame)
outScrollbar.pack(side=RIGHT, fill=Y)
outputbox.pack()
outScrollbar.config(command=outputbox.yview)
outputbox.config(yscrollcommand=outScrollbar.set)
#create next button for stepping through
nextButton = Button(root, text='next', command=nextStep, state=DISABLED)
#place frames in grid layout
inputFrame.grid(row=0, column=0, sticky=N)
nextButton.grid(row=1, column=0)
memFrame.grid(row=0, column=1, rowspan=2)
outputFrame.grid(row=0, column=2, sticky=N)
'''------------------------------
Start tkinter's event driven loop
------------------------------'''
mainloop() | true |
3918d97e835e80a83a4b232349a2b3b7f412da61 | Python | Namyaasingh/dictionary-saral- | /question8.py | UTF-8 | 145 | 3.546875 | 4 | [] | no_license | details={}
for i in range(10):
user=input("enter the name :")
marks=input("enter the marks:")
details[user]=marks
print(details)
| true |
19bb8209c66e195e7e6720a373ea21976fa40dbf | Python | Erich6917/python_general_py2 | /util/date_check_util.py | UTF-8 | 864 | 2.859375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
# @Time : 2018/6/4
# @Author : ErichLee ErichLee@qq.com
# @File : date_check_util.py
# @Comment : 日期类检查工具
#
import datetime
import time
def __curr_time():
print time.time()
print time.localtime((time.time()))
print time.localtime()
print time.strftime("%Y-%m-%d %H:%M:%S %Y", time.localtime())
print datetime.datetime.now()
def curr_date_str():
return time.strftime("%Y-%m-%d", time.localtime())
def curr_date_str2():
return time.strftime("%Y%m%d", time.localtime())
def curr_data_ymdhm():
return str(time.strftime("%Y%m%d%H%M", time.localtime()))
def curr_ymd():
return time.strftime("%Y%m%d", time.localtime())
def curr_ymd_hms():
return time.strftime("%Y%m%d%H%M%S", time.localtime())
def curr_date_format():
now_time = datetime.datetime.now()
return now_time
| true |
bf4e838c789428191005e6eec301a29316d4d49c | Python | Ekluv/Recursive-CTE | /recursive_cte_demo/company/networkx_graphs.py | UTF-8 | 477 | 2.78125 | 3 | [] | no_license | import networkx as nx
from company.models import Employee
G=nx.Graph()
G.add_edge(1, 2)
G.add_edge(2, 3)
G.add_edge(3, 4)
G.add_edge(1, 4)
G.add_edge(4, 5)
G.add_edge(3, 5)
nx.shortest_path(G, source=1, target=3)
# [1,2,3]
nx.shortest_path(G, source=1, target=4)
# [1,4]
nx.shortest_path(G, source=1, target=5)
# [1,4,5]
nx.shortest_path(G, source=3, target=5)
# [3,5]
nx.shortest_path(G, source=2, target=3)
# [2,3,5]
#
employees = Employee.objects.all()
G=nx.Graph()
| true |
1e927dbea0c6b867fbbf13fc76e563c09fc448ad | Python | CorentinAmbroise/brainite | /brainite/models/pmvae.py | UTF-8 | 11,332 | 2.546875 | 3 | [
"CECILL-B"
] | permissive | # -*- coding: utf-8 -*-
##########################################################################
# NSAp - Copyright (C) CEA, 2021
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
# for details.
##########################################################################
"""
Pathway Modules Variational Auto-Encoder (pmVAE).
[1] pmVAE: Learning Interpretable Single-Cell Representations with Pathway
Modules, Gilles Gut, biorxiv 2021, https://github.com/ratschlab/pmvae.
"""
# Imports
import math
import numpy as np
import pandas as pd
from scipy.linalg import block_diag
import torch
import torch.nn as nn
import torch.nn.functional as func
class PMVAE(nn.Module):
""" pmVAE constructs a pathway-factorized latent space.
"""
def __init__(self, membership_mask, latent_dim, hidden_layers,
bias_last_layer=False, add_auxiliary_module=True,
terms=None, activation=None):
""" Init class.
Parameters
----------
membership_mask: bool array (pathways, genes)
a binary mask encoding which genes belong to wich pathways.
latent_dim: int
the dimension of each module latent space.
hidden_layers: list of int
the dimension of each module encoder/decoder hidden layer.
bias_last_layer: bool, default False
use a bias term on the final decoder output.
add_auxiliary_module: bool, default True
include a fully connected pathway module.
terms: list of str (pathways, ), default None
the pathway names.
activation: klass, default None
the activation function.
"""
super(PMVAE, self).__init__()
self.n_annotated_modules, self.num_feats = membership_mask.shape
if isinstance(membership_mask, pd.DataFrame):
terms = membership_mask.index
membership_mask = membership_mask.values
self.add_auxiliary_module = add_auxiliary_module
if add_auxiliary_module:
membership_mask = np.vstack(
(membership_mask, np.ones_like(membership_mask[0])))
if terms is not None:
terms = list(terms) + ["AUXILIARY"]
self.activation = activation or nn.ELU
# Then encoder maps the input data to the latent space.
self.encoder = PMVAE.build_encoder(
membership_mask, hidden_layers, latent_dim, self.activation,
batch_norm=True)
# The decoder maps a code to the output of each module.
# The merger connects each module output to its genes.
self.decoder, self.merger = PMVAE.build_decoder(
membership_mask, hidden_layers, latent_dim, self.activation,
batch_norm=True, bias_last_layer=bias_last_layer)
self.membership_mask = membership_mask
self.module_isolation_mask = PMVAE.build_module_isolation_mask(
self.membership_mask.shape[0], hidden_layers[-1])
self._latent_dim = latent_dim
self._hidden_layers = hidden_layers
assert len(terms) == len(self.membership_mask)
self.terms = list(terms)
self.kernel_initializer()
def kernel_initializer(self):
""" Init network weights.
"""
for module in self.modules():
if isinstance(module, MaskedLinear):
fan_in, fan_out = nn.init._calculate_fan_in_and_fan_out(
module.weight)
limit = math.sqrt(6 / fan_in)
nn.init.uniform_(module.weight, a=-limit, b=limit)
if module.bias is not None:
nn.init.constant_(module.bias, 0)
@staticmethod
def build_base_masks(membership_mask, hidden_layers, latent_dim):
""" Builds the masks used by the encoders/decoders.
Parameters
----------
membership_mask: bool array (pathways, genes)
a binary mask encoding which genes belong to wich pathways.
latent_dim: int
the dimension of each module latent space.
hidden_layers: list of int
the dimension of each module encoder/decoder hidden layer.
Returns
-------
base: list of array
pathway mask assigns genes to pathway modules, and separation
masks keep modules separated. Encoder modifies the last
separation mask to give mu/logvar, and the decoder reverses and
transposes the masks.
"""
n_modules, n_feats = membership_mask.shape
base = []
base.append(PMVAE.build_pathway_mask(
n_feats, membership_mask, hidden_layers[0]))
dims = hidden_layers + [latent_dim]
for input_dim, output_dim in zip(dims[:-1], dims[1:]):
base.append(PMVAE.build_separation_mask(
input_dim, output_dim, n_modules))
base = [mask.astype(np.float32) for mask in base]
return base
@staticmethod
def build_pathway_mask(nfeats, membership_mask, hidden_layers):
""" Connects genes to pathway modules.
Repeats the membership mask for each module input node.
See M in Methods 2.2.
"""
return np.repeat(membership_mask, hidden_layers, axis=0).T
@staticmethod
def build_separation_mask(input_dim, out_put_dim, nmodules):
""" Removes connections betweens pathway modules.
Block diagonal matrix, see Sigma in Methods 2.2.
"""
blocks = [np.ones((input_dim, out_put_dim))] * nmodules
return block_diag(*blocks)
@staticmethod
def build_module_isolation_mask(nmodules, module_output_dim):
""" Isolates a single module for gradient steps.
Used for the local reconstruciton terms, drops all modules except one.
"""
blocks = [np.ones((1, module_output_dim))] * nmodules
return block_diag(*blocks)
@staticmethod
def build_encoder(membership_mask, hidden_layers, latent_dim,
activation, batch_norm=True):
""" Build the encoder module.
"""
masks = PMVAE.build_base_masks(
membership_mask, hidden_layers, latent_dim)
masks[-1] = np.hstack((masks[-1], masks[-1]))
masks = [torch.from_numpy(mask.T) for mask in masks]
modules = []
in_features = membership_mask.shape[1]
for cnt, mask in enumerate(masks):
out_features = mask.shape[0]
modules.append(MaskedLinear(in_features, out_features, mask))
if batch_norm:
modules.append(nn.BatchNorm1d(out_features, eps=0.001,
momentum=0.99))
if cnt != (len(masks) - 1):
modules.append(activation())
in_features = out_features
encoder = nn.Sequential(*modules)
return encoder
@staticmethod
def build_decoder(membership_mask, hidden_layers, latent_dim,
activation, batch_norm=True, bias_last_layer=False):
""" Build the decoder/merger modules.
"""
masks = PMVAE.build_base_masks(
membership_mask, hidden_layers, latent_dim)
in_features = masks[-1].shape[1]
masks = [torch.from_numpy(mask) for mask in masks[::-1]]
modules = []
for mask in masks[:-1]:
out_features = mask.shape[0]
modules.append(MaskedLinear(in_features, out_features, mask))
if batch_norm:
modules.append(nn.BatchNorm1d(out_features, eps=0.001,
momentum=0.99))
modules.append(activation())
in_features = out_features
decoder = nn.Sequential(*modules)
merger = MaskedLinear(in_features, masks[-1].shape[0], masks[-1],
bias=bias_last_layer)
return decoder, merger
def encode(self, x):
""" Computes the inference distribution q(z | x).
Parameters
----------
x: torch.Tensor (batch_size, data_size)
the input data.
Returns
-------
q(z | x): @callable
the distribution q(z | x) with shape (batch_size, latent_dim.
"""
params = self.encoder(x)
mu, logvar = torch.split(
params, split_size_or_sections=(params.size(dim=1) // 2), dim=1)
return mu, logvar
def decode(self, z):
""" Computes the generative distribution p(x | z).
Parameters
----------
z: torch.Tensor (batch_size, latent_dim)
the stochastic latent state z.
Returns
-------
p(x | z): @callable
the distribution p(x | z) with shape (batch_size, data_size).
"""
module_outputs = self.decoder(z)
global_recon = self.merger(module_outputs, **kwargs)
return global_recon
def reparametrize(self, mu, logvar):
""" Implement the reparametrization trick.
"""
eps = torch.randn_like(logvar)
return mu + torch.exp(logvar / 2.) * eps
def forward(self, x):
""" The forward method.
"""
mu, logvar = self.encode(x)
z = self.reparametrize(mu, logvar)
module_outputs = self.decoder(z)
global_recon = self.merger(module_outputs)
return global_recon, {"z": z, "module_outputs": module_outputs,
"mu": mu, "logvar": logvar, "model": self}
def get_masks_for_local_losses(self):
""" Get module/pathway associated masks.
"""
if self.add_auxiliary_module:
return zip(self.membership_mask[:-1],
self.module_isolation_mask[:-1])
return zip(self.membership_mask, self.module_isolation_mask)
def latent_space_names(self, terms=None):
""" Get latent space associated names.
"""
terms = self.terms or terms
assert terms is not None, "Need to specify gene set terms."
if (self.add_auxiliary_module and
(len(terms) == self.n_annotated_modules)):
terms = list(terms) + ["AUXILIARY"]
z = self._latent_dim
repeated_terms = np.repeat(terms, z)
index = np.tile(range(z), len(terms)).astype(str)
latent_dim_names = map("-".join, zip(repeated_terms, index))
return list(latent_dim_names)
class MaskedLinear(nn.Linear):
""" Masked Linear module.
"""
def __init__(self, in_features, out_features, mask, *args, **kwargs):
""" Init class.
Parameters
----------
in_features: int
size of each input sample.
out_features: int
size of each output sample.
mask: torch.Tensor
mask weights with this boolean tensor.
"""
super(MaskedLinear, self).__init__(
in_features, out_features, *args, **kwargs)
self.mask = nn.Parameter(mask, requires_grad=False)
def forward(self, inputs):
""" Forward method.
"""
assert self.mask.shape == self.weight.shape
return func.linear(inputs, self.weight * self.mask, self.bias)
| true |
f006e0e94ba429d0f9b8e75e3568a7a7796a7f38 | Python | nchlsb/fun_algs_in_python | /is_palindrome.py | UTF-8 | 287 | 3.9375 | 4 | [] | no_license | # There are simpler ways to do this in Python, but this demos an algorithm
def is_palindrome(string):
i = 0
j = len(string) - 1
while i < j:
if string[i] != string[j]:
return False
i += 1
j -= 1
return True
| true |
6199f22651354405069bb5079496faceef6595a9 | Python | pints-team/pints | /pints/tests/test_noise.py | UTF-8 | 7,718 | 3 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | #!/usr/bin/env python3
#
# Tests the noise generators
#
# This file is part of PINTS (https://github.com/pints-team/pints/) which is
# released under the BSD 3-clause license. See accompanying LICENSE.md for
# copyright notice and full license details.
#
import unittest
import numpy as np
import pints.noise as pn
class TestNoise(unittest.TestCase):
"""
Tests if the noise generators work ok.
"""
def test_independent_noise(self):
# Test on numpy vector, tuple shape
clean = np.asarray([1, 2, 3, 10])
noisy = clean + pn.independent(1, clean.shape)
self.assertFalse(np.all(clean == noisy))
# Test integer shape
noise = pn.independent(3, 1000)
# No need to test noise characteristics extensively: handled by numpy!
np.random.seed(1)
noise = pn.independent(3, 1000)
self.assertTrue(np.abs(np.mean(noise)) < 0.2)
self.assertTrue(np.abs(np.std(noise) - 3) < 0.3)
# Test multidimensional arrays, single sigma
noise = pn.independent(3, [10, 10])
self.assertEqual(noise.shape, (10, 10))
# Standard deviation cannot be 0 or less (handled by numpy)
self.assertRaisesRegex(
ValueError, 'scale', pn.independent, -1, clean.shape)
# Shape must be a nice shape (handled by numpy)
self.assertRaises(TypeError, pn.independent, 1, 'hello')
def test_ar1(self):
# Simple test
clean = np.array([1, 2, 3, 10, 15, 8])
noisy = clean + pn.ar1(0.5, 5.0, len(clean))
self.assertFalse(np.all(clean == noisy))
# Test length
self.assertEqual(len(pn.ar1(0.1, 1, 100)), 100)
# Magnitude of rho must be less than 1
pn.ar1(0.9, 5, 10)
pn.ar1(-0.9, 5, 10)
self.assertRaisesRegex(ValueError, 'rho', pn.ar1, 1.1, 5, 10)
self.assertRaisesRegex(ValueError, 'rho', pn.ar1, -1.1, 5, 10)
# Sigma cannot be negative
pn.ar1(0.5, 5, 10)
self.assertRaisesRegex(
ValueError, 'Standard deviation', pn.ar1, 0.5, -5, 10)
# N cannot be negative
pn.ar1(0.5, 5, 1)
self.assertRaisesRegex(
ValueError, 'Number of values', pn.ar1, 0.5, 5, 0)
# Test noise properties
self.assertTrue(np.abs(np.std(pn.ar1(0.99, 1, 1000)) -
np.std(pn.ar1(0.50, 1, 1000)) < 5))
self.assertTrue(np.abs(np.std(pn.ar1(0.50, 1, 1000)) -
np.std(pn.ar1(0.50, 5, 1000)) < 2))
self.assertTrue(np.abs(np.mean(pn.ar1(-0.5, 1, 10000))) < 5)
def test_ar1_unity(self):
# Simple test
clean = np.asarray([1.3, 2, 3, 10, 15, 8])
noisy = clean + pn.ar1_unity(0.5, 5.0, len(clean))
self.assertFalse(np.all(clean == noisy))
# Test length
self.assertEqual(len(pn.ar1_unity(0.1, 1, 100)), 100)
# Magnitude of rho must be less than 1
pn.ar1(0.9, 5, 10)
pn.ar1(-0.5, 5, 10)
self.assertRaisesRegex(ValueError, 'rho', pn.ar1_unity, 1.1, 5, 10)
self.assertRaisesRegex(ValueError, 'rho', pn.ar1_unity, -1.1, 5, 10)
# Sigma cannot be negative
pn.ar1_unity(0.5, 5, 10)
self.assertRaisesRegex(
ValueError, 'Standard deviation', pn.ar1_unity, 0.5, -5, 10)
# N cannot be negative
pn.ar1(0.5, 5, 1)
self.assertRaisesRegex(
ValueError, 'Number of values', pn.ar1_unity, 0.5, 5, 0)
# Test noise properties
self.assertTrue(np.abs(np.std(pn.ar1_unity(0.9, 1, 10000)) -
np.std(pn.ar1_unity(0.50, 1, 10000))) < 2)
self.assertTrue(np.abs(np.mean(pn.ar1_unity(-0.5, 1, 10000)) - 1) < 2)
def test_arma11(self):
# Test construction errors
self.assertRaisesRegex(
ValueError, 'rho', pn.arma11, 1.1, 0.5, 5, 100)
self.assertRaisesRegex(
ValueError, 'theta', pn.arma11, 0.5, 1.1, 5, 100)
self.assertRaisesRegex(
ValueError, 'Standard deviation', pn.arma11, 0.5, 0.5, -5, 100)
self.assertRaisesRegex(
ValueError, 'Number of values', pn.arma11, 0.5, 0.5, 5, -100)
# test values
samples = pn.arma11(0.5, 0.5, 5, 10000)
self.assertTrue(np.mean(samples) < 1)
self.assertTrue(np.abs(np.std(samples) - 5) < 1)
def test_arma11_unity(self):
# Test construction errors
self.assertRaisesRegex(
ValueError, 'rho', pn.arma11_unity, 1.1, 0.5, 5, 100)
self.assertRaisesRegex(
ValueError, 'theta', pn.arma11_unity, 0.5, 1.1, 5, 100)
self.assertRaisesRegex(
ValueError, 'Standard dev', pn.arma11_unity, 0.5, 0.5, -5, 100)
self.assertRaisesRegex(
ValueError, 'Number of values', pn.arma11_unity, 0.5, 0.5, 5, -100)
# test values
samples = pn.arma11_unity(0.5, 0.5, 5, 10000)
self.assertTrue(np.abs(np.mean(samples) - 1) < 1)
self.assertTrue(np.abs(np.std(samples) - 5) < 1)
def test_multiplicative_gaussian(self):
# Test construction errors
self.assertRaisesRegex(
ValueError,
'Standard deviation',
pn.multiplicative_gaussian,
1.0,
-1.0,
[1, 2, 3]
)
self.assertRaisesRegex(
ValueError,
'Standard deviation',
pn.multiplicative_gaussian,
1.0,
[2.0, -1.0],
np.array([[1, 2, 3], [4, 5, 6]])
)
f_too_many_dims = np.zeros((2, 10, 5))
self.assertRaisesRegex(
ValueError,
'f must have be of shape',
pn.multiplicative_gaussian,
1.0,
1.0,
f_too_many_dims
)
self.assertRaisesRegex(
ValueError,
'eta must be',
pn.multiplicative_gaussian,
np.array([[1, 2, 3], [4, 5, 6]]),
1.0,
[1, 2, 3]
)
self.assertRaisesRegex(
ValueError,
'eta must be',
pn.multiplicative_gaussian,
np.array([1, 2, 3]),
1.0,
[1, 2, 3]
)
self.assertRaisesRegex(
ValueError,
'sigma must be',
pn.multiplicative_gaussian,
1.0,
np.array([[1, 2, 3], [4, 5, 6]]),
[1, 2, 3]
)
self.assertRaisesRegex(
ValueError,
'sigma must be',
pn.multiplicative_gaussian,
1.0,
np.array([1, 2, 3]),
[1, 2, 3]
)
# Test values
samples_small_f = pn.multiplicative_gaussian(2.0, 1.0, [1] * 10000)
self.assertTrue(np.abs(np.mean(samples_small_f)) < 1)
self.assertTrue(np.abs(np.std(samples_small_f) - 1) < 1)
samples_large_f = pn.multiplicative_gaussian(2.0, 1.0, [2] * 10000)
self.assertTrue(np.abs(np.mean(samples_large_f)) < 1)
self.assertTrue(np.abs(np.std(samples_large_f) - 4) < 1)
# Test multi-outputs
f_2d = np.array([[1, 2, 3, 4], [11, 12, 13, 14]])
samples_2d_eta = pn.multiplicative_gaussian([1.0, 3.0], 5.0, f_2d)
self.assertTrue(samples_2d_eta.shape == f_2d.shape)
samples_2d_sigma = pn.multiplicative_gaussian(1.0, [0.5, 0.75], f_2d)
self.assertTrue(samples_2d_sigma.shape == f_2d.shape)
samples_2d_both = pn.multiplicative_gaussian([1.0, 3.0],
[0.5, 0.75], f_2d)
self.assertTrue(samples_2d_both.shape == f_2d.shape)
if __name__ == '__main__':
unittest.main()
| true |
ba7f0b2b9ccda48f971f0d25411aadd24c53a53f | Python | dronag/Python | /hangman.py | UTF-8 | 1,342 | 3.953125 | 4 | [] | no_license | import random
movies=['Omkara','Rustom','Aandhi','Saagar','Simmba','Sholay','Sarkar','Haider','Baaghi','koi mil gaya']
def choose_word():
word = random.choice(movies)
play_game(word)
def play_game(randomword):
word = list(randomword)
blanks = "_" * len(word)
blanks = list(blanks)
guessed = []
incorrect = 6
while incorrect > 0:
print("\nYou have {} chances left.".format(incorrect) + "\nYour word: " + "".join(blanks) + "\nGuessed letters: " + ",".join(guessed))
letter = input("Your guess: ")
if len(letter) == 1 and letter.isalpha():
if letter in word:
for index,character in enumerate(word):
blanks = list(blanks)
if character == letter:
blanks[index] = letter
current = "".join(blanks)
if blanks == word:
print("\n\nCONGRATULATIONS, YOU WON!!\nYour word was " + ''.join(word) + ".\n")
exit()
elif letter not in word:
incorrect -= 1
guessed.append(letter)
else:
print("\n\n!Only single letters allowed!\n\n")
else:
print("\nSorry " + player + ", your game is over!\nYour word was " + ''.join(word) + ".")
player = input("Welcome To Hangman! Please type your name :: >")
player = player.title()
print("\nHey, " + player + " You get six incorrect guesses before you Die.")
f=choose_word()
| true |
cd9c3fe6f876e9ab0b957abc4453d446bc4c8345 | Python | Farooqut21/my-work | /Detailed assignment 3.16 to 3.44/3.17 TO 3.44/3.42.py | UTF-8 | 84 | 3.28125 | 3 | [] | no_license | #3.42
def avg(lists):
for list in lists:
print(sum(list)/len(list))
| true |
42769f170adddce60ffa4abafff797f7e549b573 | Python | sagarjaspal/Training | /Exceptions/nested_try_except.py | UTF-8 | 248 | 3.234375 | 3 | [] | no_license | a = int(input('Enter a'))
b = int(input('Enter b'))
try:
x = a/b
li = [1, 2, 3, 4]
print('Output:', x)
print(li[8])
except ZeroDivisionError as ze:
print(ze)
except IndexError as ie:
print(ie)
print('Still in running mode')
| true |
c7044b9b4a15f54954bc81c7bb4b9bdecc77bc59 | Python | BenRW/Diploid-CA | /tasks.py | UTF-8 | 5,182 | 2.875 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
import DCA
import time
import glob, os
def vary_lambda(size, n_iterations, save=True, is_22=True):
l = 0
threshold = 0.01
density = []
l_array = []
n = 0
large_step = False
while l <= 1.04: # 1.04, not 1, in case the code takes a big step at the end
if is_22:
DCA_i = DCA.DiploidCA(n=size, nt=n_iterations, l=l)
else:
DCA_i = DCA.DiploidCA(n=size, nt=n_iterations, l=l, rule=254)
DCA_i.run(history=False)
density.append(DCA_i.get_density())
l_array.append(l)
if n==0 or density[n] - density[n-1]>threshold:
#threshold = 0.005
if large_step:
l = l_array[-2]
density.pop()
l_array.pop()
n-=1
l += 0.01
large_step = False
else:
l += 0.05
#threshold = 0.01
large_step = True
n+=1
print(n, l)
density = np.asarray(density)
l_array = np.asarray(l_array)
if save:
# saving data to files with unique names so they won't overwrite
if is_22:
np.savetxt("data/vary_lambda_"+str(size)+"_"+str(n_iterations)+"_"+str(time.time())+".txt",
(l_array, density), delimiter=", " )
else:
np.savetxt("data/vary_lambda_254_"+str(size)+"_"+str(n_iterations)+"_"+str(time.time())+".txt",
(l_array, density), delimiter=", " )
else:
plt.plot(l_array, density)
plt.show()
return l_array, density
def vary_lambda_analysis(size, n_iterations, is_22=True):
"""Plots all saved runs of the same system size and number of iterations
on a single figure"""
l_arrays = []
densities = []
os.chdir("data/")
for file in glob.glob("*.txt"):
if is_22:
# finding system size from filename (number after 2nd '_')
u = file.find('_')+1
u += file[u:].find('_')+1
u2 = file[u:].find('_') + u
s = int(file[u:u2])
else:
# finding system size from filename (number after 3rd '_')
u = file.find('_')+1
u += file[u:].find('_')+1
u += file[u:].find('_')+1
u2 = file[u:].find('_') + u
s = int(file[u:u2])
if s==size:
u += file[u:].find('_')+1
u2 = file[u:].find('_') + u
nt = int(file[u:u2])
if nt==n_iterations:
l, d = np.loadtxt(file, delimiter=", ")
l_arrays.append(l)
densities.append(d)
# compute mean and std of "averaged run"
l_av = np.arange(0, 0.99, 0.01)
rho_matrix = np.zeros((len(l_arrays), len(l_av)))
for i in range(len(l_arrays)):
rho_matrix[i, :] = np.interp(l_av, l_arrays[i], densities[i])
rho_av = rho_matrix.mean(axis=0)
rho_std = rho_matrix.std(axis=0)
# plot all runs in a single figure
plt.figure(1)
for i in range(len(l_arrays)):
plt.plot(l_arrays[i], densities[i], alpha=0.75)
plt.ylabel(r"$\rho$")
plt.xlabel(r"$\lambda$")
# plot averaged run with estimated uncertainties
plt.figure(2)
plt.fill_between(l_av, rho_av-2*rho_std, rho_av+2*rho_std, facecolor="r", alpha=0.4, label="2$\sigma$")
plt.plot(l_av, rho_av, "r-", label="mean")
plt.ylabel(r"$\rho$")
plt.xlabel(r"$\lambda$")
plt.legend()
# plot together
fig3, (ax1, ax2) = plt.subplots(1, 2, sharey=True, figsize=(9,3))
if is_22:
ax1.axvspan(0.72, 0.73, facecolor='blue', alpha=0.4)
else:
ax1.axvspan(0.52, 0.53, facecolor='blue', alpha=0.4)
for i in range(len(l_arrays)):
ax1.plot(l_arrays[i], densities[i], alpha=0.75)
ax1.set_ylabel(r"$\rho$")
ax2.set_xlabel(r"$\lambda$")
if is_22:
ax2.axvspan(0.72, 0.73, facecolor='blue', alpha=0.4)
else:
ax2.axvspan(0.52, 0.53, facecolor='blue', alpha=0.4)
ax2.fill_between(l_av, rho_av-2*rho_std, rho_av+2*rho_std, facecolor="#ffa1a1", label="2$\sigma$")
ax2.plot(l_av, rho_av, "r-", label="mean")
ax2.set_xlabel(r"$\lambda$")
ax2.legend()
# subfigure labels
ax1.text(0.94, 0.02, "a)", fontsize=13, backgroundcolor="#ededed")
ax2.text(0.94, 0.02, "b)", fontsize=13, backgroundcolor="#ededed")
fig3.tight_layout()
os.chdir("..")
if is_22 and size==10000:
plt.savefig("figs\\density_lambda.pdf")
elif not is_22 and size==10000:
plt.savefig("figs\\density_lambda254.pdf")
plt.show()
return 0
def st_diagram_DCA(size, n_iterations):
eca22 = DCA.DiploidCA(n=size, nt=n_iterations, l=1)
eca22.run(history=True)
fig, ax = eca22.get_diagram()
# fig.savefig("figs\\ECA22_"+str(size)+"_"+str(n_iterations)+".pdf")
plt.show()
# start = time.time()
# for _ in range(1):
# larray, density = vary_lambda(10000, 5000, is_22=False)
# speed = time.time() - start
# print('Simulation time: '+str(speed))
# vary_lambda_analysis(500, 100, is_22=False)
vary_lambda_analysis(10000, 5000, is_22=False) | true |
3033881459bc2b139ff83303eb96b114cfa63ac1 | Python | k-jinwoo/python | /Ch04/p85.py | UTF-8 | 219 | 3.625 | 4 | [] | no_license | """
날짜 : 2021/04/29
이름 : 김진우
내용 : 실습 단일 리스트 객체 예 교재 p85
"""
# (1) 단일 list 예
lst = [1,2,3,4,5]
print(lst)
print(type(lst))
for i in lst :
print(lst[:i]) # i 전까지 | true |
068fb45ef9943c88baeeaace6c68401f756cfd29 | Python | possientis/Prog | /poly/DesignPatterns/Command/command.py | UTF-8 | 5,980 | 3.671875 | 4 | [] | no_license | # Command Design Pattern
# from https://en.wikipedia.org/wiki/Command_pattern
# In object-oriented programming, the command pattern is a behavioral
# design pattern in which an object is used to encapsulate all information
# needed to perform an action or trigger an event at a later time. This
# information includes the method name, the object that owns the method
# and values for the method parameters.
#
# Four terms always associated with the command pattern are command,
# receiver, invoker and client. A command object knows about receiver
# and calls a method of the receiver. Values for parameters of the
# receiver method are stored in the command. The receiver then does
# the work. An invoker object knows how to execute a command, and
# optionally does bookkeeping about the command execution. The invoker
# does not know anything about a concrete command, it knows only about
# command interface. Both an invoker object and several command objects
# are held by a client object. The client decides which commands to
# execute at which points. To execute a command, it passes the command
# object to the invoker object.
#
# Using command objects makes it easier to construct general components
# that need to delegate, sequence or execute method calls at a time of
# their choosing without the need to know the class of the method or the
# method parameters. Using an invoker object allows bookkeeping about
# command executions to be conveniently performed, as well as implementing
# different modes for commands, which are managed by the invoker object,
# without the need for the client to be aware of the existence of
# bookkeeping or modes.
# This is the Command interface
class Command:
def execute(self):
raise NotImplementedError("Command::execute is abstract")
# This is the Invoker class. It is akin to the remote control of an
# electronic device, or a menu object within an application. It allows
# the client perform actions through a single interface, without
# having to worry about the various part of a system. The invoker class
# it itself very generic and is unaware if the specifics of commands.
class RemoteControl:
def __init__(self, on, off, up, down):
self._powerOn = on
self._powerOff = off
self._volumeUp = up
self._volumeDown = down
def switchPowerOn(self): self._powerOn.execute()
def switchPowerOff(self): self._powerOff.execute()
def raiseVolume(self): self._volumeUp.execute()
def lowerVolume(self): self._volumeDown.execute()
# This is the receiver class. It is the class of objects which will perform
# the various actions. There may be sereral receiver classes comprising
# a system, and the invoker object may invoke commands which applies
# to many different receivers. Typically a menu will execute actions
# involving not just the application object, but many other sub-objects
# As this is a simple coding exercise with one receiver object, their
# seems to be a correspondance between the interface of the RemoteControl
# and that of the Televion. However, this correspondance is misleading
# as in general, the interface of the invoker object may have little in
# common with those of the various receiver objects.
class Television:
def __init__(self):
self._volume = 10
self._isOn = False
def switchOn(self):
if (self._isOn == False):
self._isOn = True
print("Television is now switched on")
def switchOff(self):
if (self._isOn):
self._isOn = False
print("Television is now switched off")
def volumeUp(self):
if(self._isOn & self._volume < 20): # '&' rather than '&&' for and
self._volume += 1
print("Televsion volume increased to " + str(self._volume))
def volumeDown(self):
if(self._isOn & self._volume > 0): # '&' rather than '&&' for and
self._volume -= 1
print("Televsion volume decreased to " + str(self._volume))
# These are the concrete command objects. These commands have exact
# knowledge of receiver objects as well as which methods and argument
# should be used when issuing a request to receiver objects.
# As can be seen, the command design pattern relies on a fair amount
# of indirection: client code will call an invoker object (menu, remote)
# which will in turn execute a command, which will send a request to
# to a receiver object, which will finally perform the requested action.
class OnCommand(Command):
def __init__(self, television):
self._television = television
def execute(self):
self._television.switchOn()
class OffCommand(Command):
def __init__(self, television):
self._television = television
def execute(self):
self._television.switchOff()
class UpCommand(Command):
def __init__(self, television):
self._television = television
def execute(self):
self._television.volumeUp()
class DownCommand(Command):
def __init__(self, television):
self._television = television
def execute(self):
self._television.volumeDown()
# let's try it all out
# our application will need some receiver object
television = Television()
# our application will need an invoker object, which
# in turns relies on concrete command objects:
on = OnCommand(television) # command to switch tv on
off = OffCommand(television) # command to switch tv on
up = UpCommand(television) # command to switch tv on
down = DownCommand(television) # command to switch tv on
# now we are ready to create our invoker object which
# we should think of as some sort of application menu.
menu = RemoteControl(on, off, up, down)
# client code is now able to access the involker object
menu.switchPowerOn()
menu.raiseVolume()
menu.raiseVolume()
menu.raiseVolume()
menu.lowerVolume()
menu.switchPowerOff()
| true |
6b52dd105f8cc649b8ad9ec056606de3202700fc | Python | kragen/shootout | /bench/prodcons/prodcons.psyco | UTF-8 | 1,010 | 2.65625 | 3 | [
"BSD-3-Clause"
] | permissive | #!/usr/bin/python
# $Id: prodcons.psyco,v 1.3 2007-12-04 06:32:39 bfulgham Exp $
# http://www.bagley.org/~doug/shootout/
import sys, psyco
from threading import *
psyco.full()
access = Condition()
count = 0
consumed = 0
produced = 0
data = 0
def consumer(n):
global count, data, consumed
while 1:
access.acquire()
while count == 0:
access.wait()
i = data
count = 0
access.notify()
access.release()
consumed += 1
if i == n:
break
def producer(n):
global count, data, produced
for i in xrange(1,n+1):
access.acquire()
while count == 1:
access.wait()
data = i
count = 1
access.notify()
access.release()
produced += 1
def main(n):
t1 = Thread(target=producer, args=(n,))
t2 = Thread(target=consumer, args=(n,))
t1.start()
t2.start()
t1.join()
t2.join()
print produced, consumed
main(int(sys.argv[1]))
| true |
91b8fa6f367911c39658daed51eb556f18f35813 | Python | thomasmatt88/dataanimation | /videotrim.py | UTF-8 | 2,688 | 2.59375 | 3 | [] | no_license | from hachoir.metadata import extractMetadata
from datetime import datetime
import moviepy.editor as mpe
# custom modules
from videotimestamp import videotimestamp
def trim_start(new_start_time, video_file_path):
#convert new_start_time to datetime object
new_start_time = datetime.strptime(new_start_time, '%Y-%m-%d %H:%M:%S')
#returns datetime object
video_creation_datetime = videotimestamp(video_file_path)
#subtract video creation date from data start date and end date in order to get elapsed times
#convert elapsed timedelta objects into floats
start_time_seconds = (new_start_time - video_creation_datetime).total_seconds()
#trim video based off of start time and end time
clip = mpe.VideoFileClip(video_file_path)
#prevent moviepy from automatically converting portrait to landscape
if clip.rotation == 90:
clip = clip.resize(clip.size[::-1])
clip.rotation = 0
clip.ffmpeg_params = ['-noautorotate'] #doesn't seem to do anything
# trim clip
final_clip = clip.subclip(t_start = int(start_time_seconds))
return final_clip, start_time_seconds
def trim_end(new_end_time, video_file_path, video_clip, start):
new_end_time = datetime.strptime(new_end_time, '%Y-%m-%d %H:%M:%S')
video_creation_datetime = videotimestamp(video_file_path)
end_time_seconds = (new_end_time - video_creation_datetime).total_seconds() \
- start
clip = video_clip
if clip.rotation == 90:
clip = clip.resize(clip.size[::-1])
clip.rotation = 0
clip.ffmpeg_params = ['-noautorotate'] #doesn't seem to do anything
# trim clip
final_clip = clip.subclip(t_start = 0, t_end = int(end_time_seconds))
return final_clip
def trim_video(new_start_time, new_end_time, video_file_path):
t1 = datetime.strptime(new_start_time, '%Y-%m-%d %H:%M:%S')
t2 = datetime.strptime(new_end_time, '%Y-%m-%d %H:%M:%S')
if t1 < t2:
clip, start = trim_start(new_start_time, video_file_path)
clip = trim_end(new_end_time, video_file_path, clip, start)
save_video_clip(clip, "trim_test.mp4")
else:
raise CustomError
class CustomError(Exception):
pass
def save_video_clip(video_clip, file_name):
"""saves videoclip into file with optimal settings for youtube"""
video_clip.ffmpeg_params = ['-noautorotate'] #doesn't seem to do anything
# recommended settings for youtube
video_clip.write_videofile(filename = file_name, \
codec = "libx264", audio_codec = "aac")
#bitrate = 10 Mbps for 30 FPS and 15 Mbps for 60 fps
| true |
48a4bf5ef07f827810d9d235e43c07bbd8054274 | Python | whtahy/leetcode | /python/0011. maxArea.py | UTF-8 | 394 | 2.890625 | 3 | [
"CC0-1.0"
] | permissive | class Solution:
def maxArea(self, ls):
n = len(ls) - 1
v, left, right = [], 0, n
while 0 <= left < right <= n:
h = min(ls[left], ls[right])
v += [h * (right - left)]
while ls[left] <= h and left < right:
left += 1
while ls[right] <= h and left < right:
right -= 1
return max(v)
| true |
e9b5aab46944b29ff2df06c73fc98cefa8a93a53 | Python | gustavoPu/Algoritmos-de-Buscas | /buscas.py | UTF-8 | 8,324 | 3.171875 | 3 | [] | no_license | import networkx as nx
import matplotlib
import matplotlib.pyplot as plt
import os
matplotlib.use('Agg')
class Buscas(object):
"""
Classe de buscas para utlizar buscas cegas
"""
def __init__(self):
self.initial_node = ''
self.finish_node = ''
self.nodes = {}
self.edges_cost = {}
self.__node_sons = {}
def __getitem__(self, item):
return {"largura": self.busca_largura(),
"profunda": self.busca_profundidade(),
"dijkstra": self.busca_dijkstra(),
"gulosa": self.busca_gulosa(),
"estrela": self.busca_a_estrela()
}[
item]
def reset_values(self):
self.initial_node = ''
self.finish_node = ''
self.nodes = {}
self.edges_cost = {}
self.__node_sons = {}
def __generate_node_sons(self):
for n1, n2 in list(self.edges_cost.keys()):
if n1 not in self.__node_sons:
self.__node_sons[n1] = {n2: self.edges_cost[(n1, n2)]}
else:
self.__node_sons[n1].update({n2: self.edges_cost[(n1, n2)]})
def __generate_next_node(self, node, jump_node):
node_name = list(node.keys())[0]
node_childrens = self.__node_sons[node_name]
if node_name not in jump_node:
node_value = node[node_name][0]
path = node[node_name][1]
insert_sons_formated = [
{key: (
node_childrens[key] + node_value,
path + " " + node_name)}
for key in node_childrens
if key not in jump_node
]
else:
insert_sons_formated = []
return insert_sons_formated
def busca_largura(self):
self.__generate_node_sons()
next_node = self.initial_node
dict_node = {}
borda = [{n: (self.__node_sons[next_node][n], self.initial_node)} for n in self.__node_sons[next_node]]
visiteds = [self.initial_node]
while next_node != self.finish_node:
node = borda.pop(0)
insert_sons_formated = self.__generate_next_node(node, visiteds)
borda += insert_sons_formated
dict_node = node
next_node = list(node.keys())[0]
visiteds.append(next_node)
path = (dict_node[self.finish_node][1] + " " + self.finish_node).split()
cost = dict_node[self.finish_node][0]
return path, cost
def busca_profundidade(self):
self.__generate_node_sons()
next_node = self.initial_node
dict_node = {}
borda = [{n: (self.__node_sons[next_node][n], self.initial_node)} for n in self.__node_sons[next_node]]
visiteds = [self.initial_node]
while next_node != self.finish_node:
node = borda.pop()
insert_sons_formated = self.__generate_next_node(node, visiteds)
borda += insert_sons_formated
dict_node = node
next_node = list(node.keys())[0]
visiteds.append(next_node)
path = (dict_node[self.finish_node][1] + " " + self.finish_node).split()
cost = dict_node[self.finish_node][0]
return path, cost
def busca_dijkstra(self):
self.__generate_node_sons()
next_node = self.initial_node
dict_node = {}
borda = [{n: (self.__node_sons[next_node][n], self.initial_node)} for n in self.__node_sons[next_node]]
borda = sorted(borda, key=self.__sort_dijkstra)
visiteds = [self.initial_node]
while next_node != self.finish_node:
node = borda.pop(0)
insert_sons_formated = self.__generate_next_node(node, visiteds)
borda += insert_sons_formated
borda = sorted(borda, key=self.__sort_dijkstra)
dict_node = node
next_node = list(node.keys())[0]
visiteds.append(next_node)
path = (dict_node[self.finish_node][1] + " " + self.finish_node).split()
cost = dict_node[self.finish_node][0]
return path, cost
def busca_a_estrela(self):
self.__generate_node_sons()
next_node = self.initial_node
dict_node = {}
borda = [{n: (self.__node_sons[next_node][n], self.initial_node)} for n in
self.__node_sons[next_node]]
borda = sorted(borda, key=self.__sort_a_estrela)
visiteds = [self.initial_node]
while next_node != self.finish_node:
node = borda.pop(0)
insert_sons_formated = self.__generate_next_node(node, visiteds)
borda += insert_sons_formated
borda = sorted(borda, key=self.__sort_a_estrela)
dict_node = node
next_node = list(node.keys())[0]
visiteds.append(next_node)
path = (dict_node[self.finish_node][1] + " " + self.finish_node).split()
cost = dict_node[self.finish_node][0]
return path, cost
def busca_gulosa(self):
self.__generate_node_sons()
next_node = self.initial_node
dict_node = {}
borda = [{n: (self.__node_sons[next_node][n], self.initial_node)} for n in
self.__node_sons[next_node]]
borda = sorted(borda, key=self.__sort_gulosa)
visiteds = [self.initial_node]
while next_node != self.finish_node:
node = borda.pop(0)
insert_sons_formated = self.__generate_next_node(node, visiteds)
borda += insert_sons_formated
borda = sorted(borda, key=self.__sort_gulosa)
dict_node = node
next_node = list(node.keys())[0]
visiteds.append(next_node)
path = (dict_node[self.finish_node][1] + " " + self.finish_node).split()
cost = dict_node[self.finish_node][0]
return path, cost
def __sort_dijkstra(self, node_aux):
key = list(node_aux.keys())[0]
return node_aux[key][0]
def __sort_a_estrela(self, node_aux):
key = list(node_aux.keys())[0]
return node_aux[key][0] + self.nodes[key]
def __sort_gulosa(self, node_aux):
key = list(node_aux.keys())[0]
return self.nodes[key]
def gerar_grafico(self, caminho, nome, use_digraph):
if use_digraph:
graph = nx.DiGraph()
else:
graph = nx.Graph()
# Inicia a lista com as duas primeiras edges
nos_resultados = [(caminho[0], caminho[1])]
# Continua a lista de edges a partir do terceiro elemento em diante de 2 em 2
for r in range(2, len(caminho), 2):
nos_resultados.append((caminho[r - 1], caminho[r]))
nos_resultados.append((caminho[r], caminho[r - 1]))
# Insere os nós no objeto
for node in list(self.nodes.keys()):
graph.add_node(node)
# lista para pular os nós de mesmo par já inseridos na lista de Edges
# Exemplo: (1, 2) ele irá pular o (2, 1)
pular = []
for n1, n2 in list(self.edges_cost.keys()):
# Faz a verificação de pulo descrito acima
if (n1, n2) not in pular:
# Verifica se o edge é um caminho até o nó final, se for colore a linha de vermelho, se não colore de
# azul
if n1 in caminho and n2 in caminho:
color = 'r'
else:
color = 'b'
graph.add_edge(n1, n2, color=color, weight=self.edges_cost[(n1, n2)]/100)
pular.append((n2, n1))
# Cria o layout em que o grafo será plotado
pos = nx.kamada_kawai_layout(graph)
# cria um array com as cores de cada edge
colors = [graph[u][v]['color'] for u, v in graph.edges]
# desenha o grafo com as configurações feitas acima
nx.draw(graph, pos, edge_color=colors, width=1, with_labels=True)
# realiza umas configurações adicionais nos edges
nx.draw_networkx_edge_labels(graph, pos, edge_labels=self.edges_cost)
# verifica se o arquivo já existe com o mesmo nome e se existir exclui e então salva o novo.
if not os.path.isdir("static/files"):
os.mkdir("static/files")
plt.savefig("static/files/" + nome)
plt.close()
self.reset_values()
| true |
5424eb2723587d07c11cab3a888ffe0d092432ae | Python | chof747/awsremote | /src/aws_remote.py | UTF-8 | 5,170 | 2.625 | 3 | [
"BSD-3-Clause"
] | permissive | #!/usr/bin/env python3
# encoding: utf-8
'''
awsremote -- command line program to execute main aws tasks on a project
awsremote is a command line program which performs standard activities on aws
for specific cumbersome tasks like
- generating a snapshot and test image
- starting a test instance
@author: Christian Hofbauer
@copyright: 2018 Christian Hofbauer. All rights reserved.
@license: GPL
@contact: chof@gmx.at
@deffield updated: Sept. 2018
'''
import sys
import os
from datetime import datetime
from optparse import OptionParser
from optparse import OptParseError
from awsremote import AWSRemote
__all__ = []
__version__ = 0.1
__date__ = '2018-09-15'
__updated__ = '2018-09-15'
DEBUG = 0
TESTRUN = 0
PROFILE = 0
def main(argv=None):
'''Command line options.'''
program_name = os.path.basename(sys.argv[0])
program_version = "v0.1"
program_build_date = "%s" % __updated__
program_version_string = '%%prog %s (%s)' % (program_version, program_build_date)
program_usage = '''usage: awsremote [-p project_path] [-vvv] command -e environment
commands:
snapshot ..... create a new image from the production image, unlink the old one
create-env ... instantiate a new environment
terminate .... terminate an environment
login ........ login to an environmenet
start ........ start an existing environment
stop ......... stop a running environment
''' # optional - will be autogenerated by optparse
program_longdesc = '''''' # optional - give further explanation about what the program does
program_license = "Copyright 2018 Christian Hofbauer \
Licensed under the GPL"
if argv is None:
argv = sys.argv[1:]
try:
# setup option parser
parser = OptionParser(version=program_version_string, epilog=program_longdesc, description=program_license, usage=program_usage)
parser.add_option("-p", "--project", dest="projectPath", help="set the project path [default: %default]")
parser.add_option("-v", "--verbose", dest="verbose", action="count", help="set verbosity level [default: %default]")
#
parser.add_option("-n", "--name", dest="name", help="name of the AWS resource setup by the command (e.g. image name, EC2 Name")
parser.add_option("-e", "--environment", dest="environment", help="The environment which an action should be applied on (systemtest|production)")
parser.add_option("-r", "--replace", dest="replace", action="store_true", help="Replace instances for a specific environment")
# set defaults
parser.set_defaults(projectPath=".",
verbose=0,
name='',
environment='',
replace=False)
# process options
(opts, args) = parser.parse_args(argv)
command = args[0]
if DEBUG == 1:
if opts.verbose > 0:
print("verbosity level = %d " % opts.verbose)
if opts.projectPath:
print("projectPath = %s" % opts.projectPath)
print("command = %s" % command)
# MAIN BODY #
awsremote = AWSRemote(opts.projectPath, opts.verbose)
config = awsremote.config
if command == 'snapshot':
if opts.name != '':
imageName = opts.name
else:
imageName = "snapshot-{: %Y-%m-%dT%H-%M-%S}".format(datetime.now())
description = \
"Test Image as of {: %Y-%m-%d %H:%M:%S}".format(datetime.now())
config.log(config.INFO,
"creating snapshot: %s with description '%s'" % (imageName, description))
awsremote.makeAmiImage(imageName, description)
elif command == 'create-env':
awsremote.createInstanceFromAmi(opts.environment, opts.replace)
elif command == 'terminate':
awsremote.terminateInstance(opts.environment)
elif command == 'login':
awsremote.login(opts.environment)
elif command == 'start':
awsremote.startInstance(opts.environment)
elif command == 'stop':
awsremote.stopInstance(opts.environment)
except OptParseError as e:
indent = len(program_name) * " "
sys.stderr.write(program_name + ": " + repr(e) + "\n")
sys.stderr.write(indent + " for help use --help")
return 2
if __name__ == "__main__":
if DEBUG:
pass
if TESTRUN:
import doctest
doctest.testmod()
if PROFILE:
import cProfile
import pstats
profile_filename = 'awsremote_profile.txt'
cProfile.run('main()', profile_filename)
statsfile = open("profile_stats.txt", "wb")
p = pstats.Stats(profile_filename, stream=statsfile)
stats = p.strip_dirs().sort_stats('cumulative')
stats.print_stats()
statsfile.close()
sys.exit(0)
sys.exit(main()) | true |
ec6c4f411f3a90b4d44cdcd3964e5babbfa858d6 | Python | RagingPolo/proxitable | /citadel/CitBoard.py | UTF-8 | 950 | 3.453125 | 3 | [] | no_license | # ---------------------------------------------------------------------------- #
# CLASS CitBoard
#
# Maintains state of the citadel game board, board consists of 7 positions
# ---------------------------------------------------------------------------- #
class CitBoard( object ):
MIN = 0 # Lowest board position
MAX = 6 # Highest board position
MID = 3 # Starting board postion
# Start the board in the middle position
def __init__( self ):
self.__pos = CitBoard.MID
# Get the current board position
# @returns - position
def getPosition( self ):
return self.__pos
# If possible will move the board position one left
def moveLeft( self ):
if self.__pos > CitBoard.MIN:
self.__pos -= 1
# If possible will move the board position one right
def moveRight( self ):
if self.__pos < CitBoard.MAX:
self.__pos += 1
# ---------------------------------------------------------------------------- #
| true |
9ac402585c0b139b7a3500e93a5465f7b89cbb97 | Python | dsweed12/My-Projects | /Project II - Python MITx/Midter.py | UTF-8 | 1,624 | 3.671875 | 4 | [] | no_license | def closest_power(base, num):
guess=0
exp=1
while abs(base**guess - num) != 0:
if num > base**guess:
if abs(base**guess - num) <= abs(base**exp - num):
exp = guess
if base**guess > num:
if abs(base**guess - num) < abs(base**exp - num):
exp = guess
if abs(base**guess - num) > abs(base**exp - num):
break
guess += 1
return exp
def dict_invert(dic):
d = {}
for v in dic.values():
d[v] = []
for k, v in dic.items():
d[v].append(k)
d[v].sort()
return d
def max_val(t):
""" t, tuple or list
Each element of t is either an int, a tuple, or a list
No tuple or list is empty
Returns the maximum int in t or (recursively) in an element of t """
# Your code here
def openItem(term):
newList = []
for item in term:
if type(item) == int:
newList.append(item)
else:
newList += openItem(item)
return newList
sortingList = openItem(t)
maximum = sortingList[0]
for item in sortingList:
if maximum < item:
maximum = item
return maximum
def general_poly (L):
"""
L: a list of numbers (n0, n1, n2, ... nk)
Returns: a function, which when applied to a value x, returns the value
n0 * x^k + n1 * x^(k-1) + ... nk * x^0
"""
def func(x):
value = 0
k = len(L) - 1
for num in L:
value = value + num * (x ** k)
k -= 1
return value
return func | true |
482677038f67b6d69413b158b36ba02a2cf42e46 | Python | lksdsy/tulingxueyuan | /xuexi/data_type_base/bilibili_shipin.py | UTF-8 | 857 | 3.015625 | 3 | [] | no_license | '''
url = 'https://search.bilibili.com/all?keyword=%E8%A7%86%E9%A2%91&from_source=banner_search&page=3'
'''
import requests
from lxml import etree
def getInfo(start_page,end_page):
headers = {
'User-Agent': 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19'
}
for i in range(start_page,end_page):
url = 'https://search.bilibili.com/all?keyword=%E8%A7%86%E9%A2%91&from_source=banner_search&page={}'.format(i)
res = requests.get(url,headers=headers)
# print(res)
html = etree.HTML(res.text)
srcs = html.xpath('//ul[@class="video-contain clearfix"]/li/a/@href')
titles = html.xpath('//ul[@class="video-contain clearfix"]/li/a/@title')
print(srcs,titles)
if __name__ == '__main__':
getInfo(1,2) | true |
adb970c03ec395503cba600c6394ff02cebede9e | Python | Rajeev70133/PyPractice | /NearestValueOfAny.py | UTF-8 | 4,202 | 4.0625 | 4 | [] | no_license | # Find the nearest value to the given one.
#
# You have a list of values as set form and need to find the nearest one
#
# For example,we have the following set of numbers:
# 4, 7, 10, 11, 12, 17, and we need to find the nearest value to the number 9.
# If we sort this set in the ascending order, THEN the:
# left: of number 9 will be number 7, AND
# right: will be number 10. BUT
# THEN 10 is closer than 7, which means that the correct answer is 10.
#
# A few clarifications:
#
# If 2 numbers are at the same distance, you need to choose the smallest one;
# The set of numbers is always non-empty, i.e. the size is >=1;
# The given value can be in this set, which means that it’s the answer;
# The set can contain both positive and negative numbers, but they are always integers;
# The set isn’t sorted and consists of unique numbers.
# Input: Two arguments. A list of values in the set form. The sought value is an int.
# Output: Int.
#
# def nearest_value(values):
# return = lkjhgvc
#
# if __name__ == '__main__':
# print("Example:")
# print(nearest_value({4, 7, 10, 11, 12, 17}, 9))
#
# # These "asserts" are used for self-checking and not for an auto-testing
# assert nearest_value({4, 7, 10, 11, 12, 17}, 9) == 10
# assert nearest_value({4, 7, 10, 11, 12, 17}, 8) == 7
# assert nearest_value({4, 8, 10, 11, 12, 17}, 9) == 8
# assert nearest_value({4, 9, 10, 11, 12, 17}, 9) == 9
# assert nearest_value({4, 7, 10, 11, 12, 17}, 0) == 4
# assert nearest_value({4, 7, 10, 11, 12, 17}, 100) == 17
# assert nearest_value({5, 10, 8, 12, 89, 100}, 7) == 8
# assert nearest_value({-1, 2, 3}, 0) == -1
# print("Coding complete? Click 'Check' to earn cool rewards!")
#
# # using abs() + list comprehension
# diff _of_number_and_values_of_nearest_values = [abs(ele) for ele in values]
from typing import List, Any
#
import a
def nearest_value(values: set, numb: int) -> int:
a = {}
# values = values() ....typo err
# values = : List[Any] = list(values)
# # anyvardiff= [abs()]
values = list(values)
values.sort()
# diff is absolute number of numb for the val list
diff = [abs(forloop_itterator - numb) for forloop_itterator in values]
return values[diff.index(min(diff))]
if __name__ == '__main__':
print("Example:")
print(nearest_value({4, 7, 10, 11, 12, 17}, 8))
# 100 is numb
# These "asserts" are used for self-checking and not for an auto-testing
assert nearest_value({4, 7, 10, 11, 12, 17}, 9) == 10
assert nearest_value({4, 7, 10, 11, 12, 17}, 8) == 7
assert nearest_value({4, 8, 10, 11, 12, 17}, 9) == 8
assert nearest_value({4, 9, 10, 11, 12, 17}, 9) == 9
assert nearest_value({4, 7, 10, 11, 12, 17}, 0) == 4
assert nearest_value({4, 7, 10, 11, 12, 17}, 100) == 17
assert nearest_value({5, 10, 8, 12, 89, 100}, 7) == 8
assert nearest_value({-1, 2, 3}, 0) == -1
print("Coding complete? Click 'Check' to earn cool rewards!")
#
# def nearest_value(values: set, numb: int) -> int:
# # values = values() ....typo err
# # values = : List[Any] = list(values)
# # # anyvardiff= [abs()]
# values = list(values)
# values.sort()
# # diff is absolute number of numb for the val list
#
# diff = [abs(forloop_itterator - numb) for forloop_itterator in values]
#
# return values[diff.index(min(diff))]
#
#
# if __name__ == '__main__':
# print("Example:")
# near_value_in = {4, 7, 10, 11, 12, 17}
# near_value_of = {9}
# print(nearest_value(near_value_in, near_value_of))
# # 100 is number
#
# # These "asserts" are used for self-checking and not for an auto-testing
# assert nearest_value({4, 7, 10, 11, 12, 17}, 9) == 10
# assert nearest_value({4, 7, 10, 11, 12, 17}, 8) == 7
# assert nearest_value({4, 8, 10, 11, 12, 17}, 9) == 8
# assert nearest_value({4, 9, 10, 11, 12, 17}, 9) == 9
# assert nearest_value({4, 7, 10, 11, 12, 17}, 0) == 4
# assert nearest_value({4, 7, 10, 11, 12, 17}, 100) == 17
# assert nearest_value({5, 10, 8, 12, 89, 100}, 7) == 8
# assert nearest_value({-1, 2, 3}, 0) == -1
# print("Coding complete? Click 'Check' to earn cool rewards!")
| true |
9d22b888cd17b28effb22662faf8bf944514e230 | Python | nasseh101/bumble-swiping-bot | /bumble_bot.py | UTF-8 | 1,809 | 2.75 | 3 | [] | no_license | from selenium import webdriver
from time import sleep
from secrets import email, password
class BumbleBot():
def __init__(self):
self.driver = webdriver.Chrome()
def login(self):
self.driver.get("https://bumble.com/")
# Waiting for page to load
sleep(3)
signin_btn = self.driver.find_element_by_xpath('//*[@id="page"]/div/div/div[1]/div/div[2]/div/div/div/div[2]/div[1]/div/div[2]/a')
signin_btn.click()
sleep(3)
fb_btn = self.driver.find_element_by_xpath('//*[@id="main"]/div/div[1]/div[2]/main/div/div[2]/form/div[1]/div')
fb_btn.click()
base_window = self.driver.window_handles[0]
self.driver.switch_to_window(self.driver.window_handles[1])
email_in = self.driver.find_element_by_xpath('//*[@id="email"]')
email_in.send_keys(email)
pw_in = self.driver.find_element_by_xpath('//*[@id="pass"]')
pw_in.send_keys(password)
login_btn = self.driver.find_element_by_xpath('//*[@id="u_0_0"]')
login_btn.click()
self.driver.switch_to_window(base_window)
# Delay to allow for Login
sleep(4)
def like(self):
like_btn = self.driver.find_element_by_xpath('//*[@id="main"]/div/div[1]/main/div[2]/div/div/span/div[2]/div/div[2]/div/div[3]/div')
like_btn.click()
def dislike(self):
dislike_btn = self.driver.find_element_by_xpath('//*[@id="main"]/div/div[1]/main/div[2]/div/div/span/div[2]/div/div[2]/div/div[1]')
dislike_btn.click()
def handle_match_popup(self):
cls_btn = self.driver.find_element_by_xpath('//*[@id="main"]/div/div[1]/main/div[2]/article/div/footer/div/div[2]/div')
cls_btn.click()
def auto_swipe(self):
while(True):
sleep(1)
try:
self.like()
except:
self.handle_match_popup()
# bot = BumbleBot()
# bot.login()
# bot.auto_swipe() | true |
6b2c2abbc67a9e574d5c6770a97d4bbf5716be71 | Python | AaronCheng820/PythonCode | /VerilogTestbenchGen/VerilogTestbenchGen.py | UTF-8 | 7,922 | 2.65625 | 3 | [] | no_license | # ----------------------------------------------------------
# coding=utf-8
# Copyright © 2021 Komorebi660 All rights reserved.
# ----------------------------------------------------------
WRITE_FILE_NAME = 'VerilogTestbenchGen/testbench_module.txt'
READ_FILE_NAME = 'VerilogTestbenchGen/module_port.txt'
TESTBENCH_MODULE_NAME = 'test_'
INST_MODULE_NAME = 'inst_'
LINE_LENTH_1 = 20
LINE_LENTH_2 = 15
LINE_LENTH_3 = 30
f_out = open(WRITE_FILE_NAME, 'w+')
f_out.write('`timescale 1ns / 1ps \n')
f_out.write('/*------------------------------------------------\n')
f_out.write('Testbench file made by VerilogTestbenchGen.py\n')
f_out.write('------------------------------------------------*/\n\n\n')
# generate ports
start = 0
line_number = 0
with open(READ_FILE_NAME, 'r') as f:
while True:
line_input = f.readline()
line_number += 1
line_temp = line_input.split()
lenth = len(line_temp)
# read a empty line doesn't mean the module defination is over.
if lenth == 0:
continue
# module is over.
elif line_temp[0] == ');':
break
elif line_temp[0] == 'module(':
print(f'Can not find module name in line {line_number}.')
exit(0)
elif line_temp[0] == 'module':
# the start of a module
start = 1
# delete '(' in the module name
module_name = line_temp[1].replace('(', '')
# input module error
if len(module_name) == 0:
print(f'Can not find module name in line {line_number}.')
exit(0)
line_output = 'module '
line_output += TESTBENCH_MODULE_NAME+module_name
line_output += '();\n'
f_out.write(line_output)
elif line_temp[0] == 'input':
if start == 0:
continue
line_output = 'reg '
if lenth < 2:
print(f"Can not find input port name in line {line_number}.")
exit(0)
elif lenth == 2 and line_temp[1] == ',':
print(f"Can not find output port name in line {line_number}.")
exit(0)
for i in range(1, lenth):
# ignore 'wire' or 'reg'
if line_temp[i] == 'wire':
continue
elif line_temp[i] == 'reg':
continue
# if the last word is ','
elif i == lenth-2 and line_temp[lenth-1] == ',':
line_output += ' '*(LINE_LENTH_1-len(line_output))
line_output += line_temp[i]+';'
break
# if it is the last word
elif i == lenth-1:
line_output += ' '*(LINE_LENTH_1-len(line_output))
# there may not have a ',' in the last word
line_output += line_temp[i].replace(',', '')+';'
else:
line_output += ' '+line_temp[i]
f_out.write('\n'+line_output)
elif line_temp[0] == 'output':
if start == 0:
continue
line_output = 'wire'
if lenth < 2:
print(f"Can not find output port name in line {line_number}.")
exit(0)
elif lenth == 2 and line_temp[1] == ',':
print(f"Can not find output port name in line {line_number}.")
exit(0)
for i in range(1, lenth):
# ignore 'wire' or 'reg'
if line_temp[i] == 'wire':
continue
elif line_temp[i] == 'reg':
continue
# if the last word is ','
elif i == lenth-2 and line_temp[lenth-1] == ',':
line_output += ' '*(LINE_LENTH_1-len(line_output))
line_output += line_temp[i]+';'
break
# if it is the last word
elif i == lenth-1:
line_output += ' '*(LINE_LENTH_1-len(line_output))
# there may not have a ',' in the last word
line_output += line_temp[i].replace(',', '')+';'
else:
line_output += ' '+line_temp[i]
f_out.write('\n'+line_output)
else:
continue
f.close()
# generate signals
f_out.write('\n\n\ninitial\n')
f_out.write('begin')
start = 0
with open(READ_FILE_NAME, 'r') as f:
while True:
line_input = f.readline()
line_temp = line_input.split()
lenth = len(line_temp)
# read a empty line doesn't mean the module defination is over.
if lenth == 0:
continue
# module is over.
if line_temp[0] == ');':
break
# the start of a module
elif line_temp[0] == 'module':
start = 1
# generate input signal
elif line_temp[0] == 'input':
if start == 0:
continue
# get the last word
line_output = line_temp[lenth-1]
# if the last word is ','
if line_output == ',':
line_output = '\t'+line_temp[lenth-2]
line_output += ' '*(LINE_LENTH_2-len(line_output))
line_output = line_output+'=\'d0;'
else:
line_output = '\t'+line_output.replace(',', '')
line_output += ' '*(LINE_LENTH_2-len(line_output))
line_output = line_output+'=\'d0;'
f_out.write('\n'+line_output)
else:
continue
f.close()
f_out.write('\nend\n')
# instant module
start = 0
with open(READ_FILE_NAME, 'r') as f:
while True:
line_input = f.readline()
line_temp = line_input.split()
lenth = len(line_temp)
# read a empty line doesn't mean the module defination is over.
if (lenth == 0):
continue
# module is over.
elif line_temp[0] == ');':
f_out.write('\n);')
break
# the start of a module
elif line_temp[0] == 'module':
start = 1
# delete '(' in the module name
module_name = line_temp[1].replace('(', '')
line_output = module_name+" "
line_output += INST_MODULE_NAME+module_name
line_output += '\n('
f_out.write('\n\n'+line_output)
elif line_temp[0] == 'input' or line_temp[0] == 'output':
if start == 0:
continue
# get the last word
line_output = line_temp[lenth-1]
# if the last word is ','
if line_output == ',':
line_output = line_temp[lenth-2]
line_output = '\t.'+line_output+'('+line_output+'),'
# if the last letter of the last word is ','
elif line_output[len(line_output)-1] == ',':
line_output = line_output.replace(',', '')
line_output = '\t.'+line_output+'('+line_output+'),'
else:
line_output = '\t.'+line_output+'('+line_output+')'
# add scripts of the ports
line_output += ' '*(LINE_LENTH_3-len(line_output))
line_output += '//'
for i in range(0, lenth-1):
# ignore 'wire' or 'reg'
if line_temp[i] == 'wire':
continue
elif line_temp[i] == 'reg':
continue
else:
# if the last word is ','
if i == lenth-2 and line_temp[lenth-1] == ',':
continue
else:
line_output += ' '+line_temp[i]
f_out.write('\n'+line_output)
else:
continue
f.close()
f_out.write('\n\nendmodule')
f_out.close()
| true |
4277407138e9753482b7f5abe50624c2457209bb | Python | AbeHandler/WordNet-Word2Vec | /barcharter_adjusted.py | UTF-8 | 3,541 | 3.078125 | 3 | [] | no_license | """
Bar chart demo with pairs of bars grouped for easy comparison.
"""
import numpy as np
import sys
import re
import math
lines = []
def isIt(s, p):
if len(re.findall(p, s)) > 0:
return True
return False
for line in sys.stdin:
lines.append(line.replace("\n", ""))
def lessThanGreaterThanK(l, k):
try:
if (int(l.split(",")[4]) <= k and int(l.split(",")[4]) > floor[k]):
return True
return False
except ValueError:
pass
syn = [l for l in lines if isIt(l, "^syn")]
hypo = [l for l in lines if isIt(l, "^hypo")]
hyper = [l for l in lines if isIt(l, "^hyper")]
holo = [l for l in lines if isIt(l, "^holo")]
mero = [l for l in lines if isIt(l, "^mero")]
n_groups = 5
ks = [200, 400, 600, 800, 1000]
floor = {}
floor[200] = 0
floor[400] = 200
floor[600] = 400
floor[800] = 600
floor[1000] = 800
count_syn = []
count_hyper = []
count_hypo = []
count_holo = []
count_mero = []
base = 10
for k in ks:
count_syn.append(len([s for s in syn if lessThanGreaterThanK(s, k)]))
for k in ks:
count_hyper.append(len([s for s in hyper if lessThanGreaterThanK(s, k)]))
for k in ks:
count_hypo.append(len([s for s in hypo if lessThanGreaterThanK(s, k)]))
for k in ks:
count_holo.append(len([s for s in holo if lessThanGreaterThanK(s, k)]))
for k in ks:
count_mero.append(len([s for s in mero if lessThanGreaterThanK(s, k)]))
syn = 0.128765837896
hypo = 0.599908659263
hyper = 0.125228424687
mero = 0.100856732318
holo = 0.0452403458359
max_val = max([syn, hypo, hyper, mero, holo])
print max_val
count_syn = tuple([math.log((1/(syn / max_val)) * s, 10) for s in count_syn])
count_hyper = tuple([math.log((1/(hyper / max_val)) * s, 10) for s in count_hyper])
count_hypo = tuple([math.log((1/(hypo / max_val)) * s, 10) for s in count_hypo])
count_holo = tuple([math.log((1/(holo / max_val)) * s, 10) for s in count_holo])
count_mero = tuple([math.log((1/(mero / max_val)) * s, 10) for s in count_mero])
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.1
opacity = 0.4
error_config = {'ecolor': '0.3'}
rects1 = plt.bar(index + .15, count_syn, bar_width,
alpha=opacity,
color='blue',
label='synonyms')
rects2 = plt.bar(index + .3, count_hyper, bar_width,
alpha=opacity,
color='red',
label='hypernyms')
rects3 = plt.bar(index + .45, count_hypo, bar_width,
alpha=opacity,
color='purple',
label='hyponyms')
rects4 = plt.bar(index + .6, count_holo, bar_width,
alpha=opacity,
color='green',
label='holonyms')
rects5 = plt.bar(index + .75, count_mero, bar_width,
alpha=opacity,
color='orange',
label='meronyms')
plt.xlabel('K')
plt.ylabel('Log 10 of adjusted count')
plt.title('Semantic Similarity in Word2Vec Compared To WordNet -- Adjusted')
plt.xticks(index + bar_width * 5, ('<200', '200-400', '400-600', '600-800', '>800'))
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.tick_params(
axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom='off', # ticks along the bottom edge are off
top='off', # ticks along the top edge are off
labelbottom='on')
plt.tight_layout()
plt.savefig('Adjusted.png', bbox_inches='tight', pad_inches=.4) | true |
c14bd8f15d8bb397f883fd9519f71f86da5cd5b4 | Python | keurfonluu/My-Daily-Dose-of-Python | /Solutions/8-two-sum.py | UTF-8 | 524 | 4.125 | 4 | [] | no_license | #%% [markdown]
# You are given a list of numbers, and a target number k. Return whether or not there are two numbers in the list that add up to k.
# Try to do it in a single pass of the list.
#
# Example
# ```
# Given [4, 7, 1 , -3, 2] and k = 5,
# return true since 4 + 1 = 5.
# ```
#%%
def two_sum(l, k):
s = set(l) # No space complexity constraint
for x in l:
if -(x-k) in s: # Searching a value in a set is O(1)
return True
return False
print(two_sum([4,7,1,-3,2], 5)) | true |
11e8f6d4ca5693fd95bd26eeda5221edf753f6c6 | Python | zhouzhengde/china_stock_calendar | /china_stock_calendar/data.py | UTF-8 | 488 | 3.046875 | 3 | [] | no_license | import csv
import os
from pandas.tseries.holiday import Holiday
# parse holiday.csv
HOLIDAY_FILE = 'holiday.csv'
datafilepath = os.path.join(os.path.dirname(__file__), HOLIDAY_FILE)
reader = csv.reader(open(datafilepath, 'r'))
# take holiday info and set result set.
holiday_set = []
i = 0
for item in reader:
dayStr = str(item[0])
day = Holiday("Holiday_" + dayStr, year= int(dayStr[:4]), month= int(dayStr[4:6]), day= int(dayStr[6:]))
holiday_set.insert(i, day)
i += 1 | true |
25cab9e049ece38932bd015dc8d8fedec94e0fec | Python | Penguinwizzard/w3x-to-vmf | /lib/mpyq/mpyq_compression.py | UTF-8 | 3,608 | 3.375 | 3 | [
"BSD-2-Clause"
] | permissive | import zlib
import bz2
class UnsupportedCompressionAlgorithm(Exception):
def __init__(self, algorithmName, compression_type):
self.name = algorithmName
self.used_algorithms = []
self.compression_type = compression_type
for algorithm in ( ("IMA ADPCM STEREO", 0b10000000),
("IMA ADPCM MONO", 0b01000000),
("bzip", 0b00010000),
("Imploded", 0b00001000),
("zlib", 0b00000010),
("Huffman", 0b00000001)):
name, flag = algorithm
if (compression_type & flag) != 0:
self.used_algorithms.append(name)
def __str__(self):
return (
"The algorithm is not yet supported: {0}\n"
"A complete list of algorithms used in this sector: "
"{1}".format(self.name, ", ".join(self.used_algorithms) )
)
def decompress(data, strict = True):
"""Read the compression type and decompress file data."""
compression_type = ord(data[0:1])
data = data[1:]
## Compression type is actually a mask that contains data about which
## compression algorithms are used. A sector can be compressed using
## several compression algorithms.
otherTypes = 0x10 | 0x8 | 0x2 | 0x1 | 0x80 | 0x40
#print(bin(compression_type), bin(otherTypes))
## A little check to give the program more room for exceptions.
## Can be useful for debugging, might be removed later.
## Flags:
## IMA ADPCM stereo: 0b10000000
## IMA ADPCM mono: 0b01000000
## Unused: 0b00100000
## bzip: 0b00010000
## Imploded: 0b00001000
## Unused: 0b00000100
## zlib: 0b00000010
## Huffman: 0b00000001
## If any of those bits are set, something is not entirely correct
if strict and compression_type & ~otherTypes != 0:
raise RuntimeError("Compression Type has flags set which should not be set: {0},"
"can only handle the following flags: {1}".format(bin(compression_type), bin(otherTypes)))
if compression_type & 0x10:
#print("Bz2 decompression...")
data = bz2.decompress(data)
## The Implode check might not belong here. According to documentation,
## compressed data cannot be imploded, and vice versa.
if compression_type & 0x8: # 0b00001000
raise UnsupportedCompressionAlgorithm("Implode", compression_type)
if compression_type & 0x2:
#print("zlib decompression...")
try:
data = zlib.decompress(data, 15)
except zlib.error:
## Sometimes, the regular zlib decompress method fails due to invalid
## or truncated data. When that happens, it is very likely that decompressobj
## is able to decompress the data.
#print("Regular zlib decompress method failed. Using decompressObj.")
zlib_decompressObj = zlib.decompressobj()
data = zlib_decompressObj.decompress(data)
if compression_type & 0x1:
raise UnsupportedCompressionAlgorithm("Huffman", compression_type)
if compression_type & 0x80:
raise UnsupportedCompressionAlgorithm("IMA ADPCM stereo", compression_type)
if compression_type & 0x40:
raise UnsupportedCompressionAlgorithm("IMA ADPCM mono", compression_type)
return data
| true |
8238c492cf68b24d654fed10c249f8511e0a017a | Python | vijay97bk/PythonProblems | /Functional programs/Distance.py | UTF-8 | 683 | 4.0625 | 4 | [] | no_license | '''
date = '06/04/2021'
modified_date = '07/04/2021'
author = 'Vijay Kshirasagar'
description = 'Write a program Distance.py that takes two integer command-line arguments x and y and
prints the Euclidean distance from the point (x, y) to the origin (0, 0). The formulae to
calculate distance = sqrt(x*x + y*y). Use Math.power function'
'''
import math
def CalculateDistance(x,y):
# calculating distance
distance= math.sqrt(pow(x,2)+pow(y,2))
# print distance
print(distance)
try:
#taking inputs x and y
x=int(input('enter x value: '))
y=int(input('enter y value: '))
CalculateDistance(x,y)
except Exception as e:
print(e) | true |
afcb628299aee466186629071873af0a34f40c68 | Python | ashjambhulkar/objectoriented | /LeetCodePremium/524.longest-word-in-dictionary-through-deleting.py | UTF-8 | 1,367 | 4.25 | 4 | [] | no_license | #
# @lc app=leetcode id=524 lang=python3
#
# [524] Longest Word in Dictionary through Deleting
#
# @lc code=start
# Let's check whether each word is a subsequence of S individually by "best" order(largest size, then lexicographically smallest.) Then if we find a match, we know the word being considered must be the best possible answer, since better answers were already considered beforehand.
# Let's figure out how to check if a needle (word) is a subsequence of a haystack (S). This is a classic problem with the following solution: walk through S, keeping track of the position (i) of the needle that indicates that word[i:] still remains to be matched to S at this point in time. Whenever word[i] matches the current character in S, we only have to match word[i+1:], so we increment i. At the end of this process, i == len(word) if and only if we've matched every character in word to some character in S in order of our walk.
class Solution:
def findLongestWord(self, S, D):
D.sort(key=lambda x: (-len(x), x))
for word in D:
i = 0
for c in S:
if i < len(word) and word[i] == c:
i += 1
if i == len(word):
return word
return ""
s = "abpcplea"
d = ["ale", "apple", "monkey", "plea"]
print(Solution().findLongestWord(s,d))
# @lc code=end
| true |
109d0f872ccd88d9ae0fe14bc17a9fe82b60a123 | Python | fhirschmann/penchy | /penchy/jobs/elements.py | UTF-8 | 5,139 | 2.859375 | 3 | [
"MIT"
] | permissive | """
This module provides the foundation of job elements.
.. moduleauthor:: Michael Markert <markert.michael@googlemail.com>
:copyright: PenchY Developers 2011-2012, see AUTHORS
:license: MIT License, see LICENSE
"""
import logging
from collections import defaultdict
from penchy.compat import path
from penchy.jobs.dependency import Pipeline
from penchy.jobs.typecheck import Types
log = logging.getLogger(__name__)
class PipelineElement(object):
"""
This class is the base class for all objects participating in the
transformation pipeline.
A PipelineElement must have the following attributes:
- ``out``, a dictionary that maps logical names for output to actual.
- ``inputs`` a :class:`~penchy.jobs.typecheck.Types` that describes the
necessary inputs and their types for the element
- ``outputs`` a :class:`~penchy.jobs.typecheck.Types` that describes the
output with a logical name and its types
A PipelineElement must have the following methods:
- ``_run(**kwargs)``, to run the element on kwargs, kwargs has to have the
types that ``input`` describes
A :class:`PipelineElement` must call ``PipelineElement.__init__`` on its
initialization.
"""
DEPENDENCIES = set()
inputs = Types()
outputs = Types()
def __init__(self):
self.reset()
self.hooks = []
def run(self, **kwargs):
"""
Run element with hooks.
"""
self.inputs.check_input(kwargs)
for hook in self.hooks:
hook.setup()
self._run(**kwargs)
for hook in self.hooks:
hook.teardown()
def reset(self):
"""
Reset state of element.
Resets
- element.out
"""
self.out = defaultdict(list)
def __rshift__(self, other):
p = Pipeline(self)
return p >> other
def _run(self, **kwargs): # pragma: no cover
"""
Run the actual Element on the arguments.
"""
raise NotImplementedError("PipelineElements must implement this")
@property
def _output_names(self):
"""
Return the set of output names
:returns: the output names
:rtype: set
"""
return self.outputs.names
def __repr__(self):
return self.__class__.__name__
class NotRunnable(object):
"""
This represents a pipeline element that can't be run.
"""
def run(self):
msg = "{0} can't be run!".format(self.__class__.__name__)
log.error(msg)
raise ValueError(msg)
class Filter(PipelineElement):
"""
This represents a Filter of the pipeline.
A Filter receives and processes data.
"""
pass
class SystemFilter(Filter):
"""
This represents a Filter of the pipeline that needs access to the system.
Additionally to :class:`Filter` it receives additionally an input named
``:environment:`` that describes the execution environment.
"""
pass
class Tool(NotRunnable, PipelineElement):
"""
This represents a Tool of the pipeline.
A Tool modifies the JVM on which it runs, so that data about that run is
gathered. Hprof, for example, is a Tool.
"""
def __init__(self, name=None):
"""
:param name: descriptive name of this tool
:type name: str
"""
super(Tool, self).__init__()
self.name = name
@property
def arguments(self): # pragma: no cover
"""
The arguments the jvm has to include to use the tool.
"""
raise NotImplementedError("Tools must implement this")
def __str__(self): # pragma: no cover
return self.name
class Workload(NotRunnable, PipelineElement):
"""
This represents a Workload of the pipeline.
A Workload is code that the JVM should execute. Typically it provides the
classpath (via its dependencies) and the complete commandline arguments to
call it correctly. The DaCapo benchmark suite is a workload (with a
benchmark specified).
A workload has at least three exported values:
- `stdout`, the path to the file that contains the output on stdout
- `stderr`, the path to the file that contains the output on stderr
- `exit_code`, the exitcode as int
"""
outputs = Types(('stdout', list, path),
('stderr', list, path),
('exit_code', list, int))
def __init__(self, timeout=0, name=None):
"""
:param timeout: timeout (in seconds) after which this workload should
be terminated
:type timeout: int
:param name: descriptive name of this workload
:type name: str
"""
super(Workload, self).__init__()
self.timeout = timeout
self.name = name
def __str__(self): # pragma: no cover
return self.name
@property
def arguments(self): # pragma: no cover
"""
The arguments the jvm has to include to execute the workloads.
"""
raise NotImplementedError("Workloads must implement this")
| true |
530a9001f33f38b0615d1f3b10cf148d1eec01e1 | Python | dheysonmendes/python-blueedtec | /Exercicios/aula06_exercicioss.py | UTF-8 | 4,354 | 4.6875 | 5 | [] | no_license | # Exercícios
# 1. Faça um programa, com uma função que necessite de três argumentos, e que forneça a
# soma desses três argumentos.
def soma(a, b, c):
soma = a + b + c
print(f'A soma é {soma}.')
a = int(input('Digite o primeiro numero: '))
b = int(input('Digite o segundo numero: '))
c = int(input('Digite o terceiro numero: '))
soma(a,b,c)
#---------------------------------------------------------------------------------------------
# 2. Faça um programa, com uma função que necessite de um argumento. A função retorna
# o valor de caractere ‘P’, se seu argumento for positivo, ‘N’, se seu argumento for
# negativo e ‘0’ se for 0
def valor(a):
if a > 0:
print('P')
elif a < 0:
print('N')
else:
print('0')
a= int(input('Digite um numero: '))
valor(a)
#---------------------------------------------------------------------------------------------
# 3. Faça um programa com uma função chamada somaImposto. A função possui dois
# parâmetros formais: taxaImposto, que é a quantia de imposto sobre vendas expressa em
# porcentagem e custo, que é o custo de um item antes do imposto. A função “altera” o
# valor de custo para incluir o imposto sobre vendas.
def somaImposto(taxaImposto, Custo):
return (1 + taxaImposto/100)*Custo
t = float(input('Digite a taxa de imposto: '))
c = float(input('Digite o custo: '))
print('Valor com imposto:', somaImposto(t,c))
#---------------------------------------------------------------------------------------------
# 4. Faça um programa que calcule o salário de um colaborador na empresa XYZ. O salário
# é pago conforme a quantidade de horas trabalhadas. Quando um funcionário trabalha
# mais de 40 horas ele recebe um adicional de 1.5 nas horas extras trabalhadas.
#Duvida no valor pago por horas trabalhadas.
#---------------------------------------------------------------------------------------------
# 5. Faça um programa que calcule através de uma função o IMC de uma pessoa que tenha
# 1,68 e pese 75kg.
def imc(peso, altura):
imc = peso / altura**2
print(f'Sua de massa corporal é: {imc:.1f}')
peso = float(input('Digite seu peso: '))
altura = float(input('Digite sua altura: '))
imc(peso,altura)
#---------------------------------------------------------------------------------------------
# 6. Escreva uma função que, dado um número nota representando a nota de um estudante,
# converte o valor de nota para um conceito (A, B, C, D, E e F).
# Nota Conceito
# >=9.0 A
# >=8.0 B
# >=7.0 C
# >=6.0 D
# # <=4.0 F
def nota(n):
if n >= 9.0:
print('Sua nota foi A')
if n < 9 and n >= 8.0:
print('Sua nota foi B')
if n < 8 and n >= 7.0:
print('Sua nota foi C')
if n < 7 and n >= 6.0:
print('Sua nota foi D')
if n < 6:
print('Sua nota foi F')
n = float(input('Digite sua nota: '))
nota(n)
#---------------------------------------------------------------------------------------------
# 7. Escreva uma função que recebe dois parâmetros e imprime o menor dos dois. Se eles
# # forem iguais, imprima que eles são iguais.
def maiormenor(a,b):
if a > b:
print('O primeiro é maior.')
elif b > a:
print('O segundo é maior.')
else:
print('Os numeros são iguais.')
a = float(input('Digite o primeiro numero: '))
b = float(input('Digite o segundo numero: '))
maiormenor(a,b)
#---------------------------------------------------------------------------------------------
# DESAFIO - Data com mês por extenso. Construa uma função que receba uma data no
# formato DD/MM/AAAA e devolva uma string no formato D de mesPorExtenso de AAAA.
# Opcionalmente, valide a data e retorne NULL caso a data seja inválida. Considere que
# Fevereiro tem 28 dias e que a cada 4 anos temos ano bisexto, sendo que nesses casos Fevereiro
# terá 29 dias
def datas(dia,mes,ano):
meses = ('zero', 'Janeiro',' Fevereiro', 'Marco',' Abril', 'Maio', 'Junho', 'Julho', 'Agosto',
'Setembro', 'Outubro', 'Novembro', 'Dezembro')
print(f'Você digitou a data de {dia} de {meses[mes]} de {ano}.')
dia = int(input('Digite o dia: '))
mes = int(input('Digite o mês: '))
ano = int(input('Digite o ano: '))
datas(dia,mes,ano)
| true |
8321bc22a2bb18c49641473ae4002afbb42e91b6 | Python | quanqinle/my-python | /batch_rename_files.py | UTF-8 | 591 | 3.09375 | 3 | [] | no_license | #coding:utf-8
# 批量重命名文件
import os
def rename_files():
# windows系统,则c:\\mydir
# Linux系统,'/home/quanql/old'
for filename in os.listdir('.'):
if filename[-2: ] == 'py':
#过滤掉改名的.py文件
continue
# 文件名替换规则:去掉空格
name = filename.replace(' ', '')
# 选择名字中需要保留的部分
new_name = name[20: 30] + name[-4:]
os.rename(filename, new_name)
def main():
rename_files()
if __name__ == "__main__":
main() | true |
e9e092781ffa2577ba9607735f4a6d9beed71b1b | Python | nashid/iclr2019-learning-to-represent-edits | /diff_representation/asdl/syntax_tree.py | UTF-8 | 13,739 | 2.515625 | 3 | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | permissive | # coding=utf-8
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from collections import OrderedDict
from typing import List, Tuple, Dict, Union
try:
from cStringIO import StringIO
except:
from io import StringIO
import json
from .grammar import *
class AbstractSyntaxNode(object):
def __init__(self, production, realized_fields=None, id=-1):
# this field is a unique identification of the node, but it's not used
# when comparing two ASTs.
self.id = id
self.production = production
# a child is essentially a *realized_field*
self.fields = []
# record its parent field to which it's attached
self.parent_field = None
# used in decoding, record the time step when this node was created
self.created_time = 0
if realized_fields:
assert len(realized_fields) == len(self.production.fields)
for field in realized_fields:
self.add_child(field)
else:
for field in self.production.fields:
self.add_child(RealizedField(field))
def add_child(self, realized_field):
# if isinstance(realized_field.value, AbstractSyntaxTree):
# realized_field.value.parent = self
self.fields.append(realized_field)
realized_field.parent_node = self
def __getitem__(self, field_name):
for field in self.fields:
if field.name == field_name: return field
raise KeyError
@property
def is_pre_terminal(self):
return all(not f.type.is_composite for f in self.fields)
def sanity_check(self):
if len(self.production.fields) != len(self.fields):
raise ValueError('filed number must match')
for field, realized_field in zip(self.production.fields, self.fields):
assert field == realized_field.field
for child in self.fields:
for child_val in child.as_value_list:
if isinstance(child_val, AbstractSyntaxNode):
child_val.sanity_check()
def copy(self):
new_tree = AbstractSyntaxNode(self.production, id=self.id)
new_tree.created_time = self.created_time
for i, old_field in enumerate(self.fields):
new_field = new_tree.fields[i]
new_field._not_single_cardinality_finished = old_field._not_single_cardinality_finished
if old_field.type.is_composite:
for value in old_field.as_value_list:
new_field.add_value(value.copy())
else:
for value in old_field.as_value_list:
new_field.add_value(value)
return new_tree
def to_string(self, sb=None):
is_root = False
if sb is None:
is_root = True
sb = StringIO()
sb.write('(')
sb.write(self.production.constructor.name)
for field in self.fields:
sb.write(' ')
sb.write('(')
sb.write(field.type.name)
sb.write(Field.get_cardinality_repr(field.cardinality))
sb.write('-')
sb.write(field.name)
if field.value is not None:
for val_node in field.as_value_list:
sb.write(' ')
if field.type.is_composite:
val_node.to_string(sb)
else:
sb.write(str(val_node).replace(' ', '-SPACE-'))
sb.write(')') # of field
sb.write(')') # of node
if is_root:
return sb.getvalue()
def __hash__(self):
code = hash(self.production)
for field in self.fields:
code = code + 37 * hash(field)
return code
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
# if self.created_time != other.created_time:
# return False
if self.production != other.production:
return False
if len(self.fields) != len(other.fields):
return False
for i in range(len(self.fields)):
if self.fields[i] != other.fields[i]: return False
return True
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return repr(self.production)
@property
def descendant_nodes(self):
def _visit(node):
if isinstance(node, AbstractSyntaxNode):
yield node
for field in node.fields:
for field_val in field.as_value_list:
yield from _visit(field_val)
yield from _visit(self)
@property
def descendant_nodes_and_tokens(self):
def _visit(node):
if isinstance(node, AbstractSyntaxNode):
yield node
for field in node.fields:
for field_val in field.as_value_list:
yield from _visit(field_val)
else:
yield node
yield from _visit(self)
@property
def descendant_tokens(self):
def _visit(node):
if isinstance(node, AbstractSyntaxNode):
for field in node.fields:
for field_val in field.as_value_list:
yield from _visit(field_val)
else:
yield node
yield from _visit(self)
@property
def size(self):
node_num = 1
for field in self.fields:
for val in field.as_value_list:
if isinstance(val, AbstractSyntaxNode):
node_num += val.size
else: node_num += 1
return node_num
@property
def depth(self):
return 1 + max(max(val.depth) for val in field.as_value_list for field in self.fields)
class SyntaxToken(object):
"""represent a terminal token on an AST"""
def __init__(self, type, value, position=-1, id=-1):
self.id = id
self.type = type
self.value = value
self.position = position
# record its parent field to which it's attached
self.parent_field = None
@property
def size(self):
return 1
@property
def depth(self):
return 0
def copy(self):
return SyntaxToken(self.type, self.value, position=self.position, id=self.id)
def __hash__(self):
code = hash(self.type) + 37 * hash(self.value)
return code
def __repr__(self):
return repr(self.value)
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.type == other.type and self.value == other.value
def __ne__(self, other):
return not self.__eq__(other)
class AbstractSyntaxTree(object):
def __init__(self, root_node: AbstractSyntaxNode):
self.root_node = root_node
self.adjacency_list: List[Tuple[int, int]] = None
self.id2node: Dict[int, Union[AbstractSyntaxNode, SyntaxToken]] = None
self.syntax_tokens_and_ids: List[Tuple[int, SyntaxToken]] = None
self._get_properties()
def _get_properties(self):
"""assign numerical indices to index each node"""
id2nodes = OrderedDict()
syntax_token_position2id = OrderedDict()
terminal_tokens_list = []
adj_list = []
def _index_sub_tree(root_node, parent_node):
if parent_node:
adj_list.append((parent_node.id, root_node.id))
id2nodes[root_node.id] = root_node
if isinstance(root_node, AbstractSyntaxNode):
for field in root_node.fields:
for field_val in field.as_value_list:
_index_sub_tree(field_val, root_node)
else:
# it's a syntax token
terminal_tokens_list.append((root_node.id, root_node))
syntax_token_position2id[root_node.position] = root_node.id
_index_sub_tree(self.root_node, None)
self.adjacency_list = adj_list
self.id2node = id2nodes
self.syntax_tokens_and_ids = terminal_tokens_list
self.syntax_token_position2id = syntax_token_position2id
self.syntax_tokens_set = {token: id for id, token in terminal_tokens_list}
self.node_num = len(id2nodes)
# this property are used for training and beam search, to get ids of syntax tokens
# given their surface values
syntax_token_value2ids = dict()
for id, token in self.syntax_tokens_and_ids:
syntax_token_value2ids.setdefault(token.value, []).append(id)
self.syntax_token_value2ids = syntax_token_value2ids
self._init_sibling_adjacency_list()
def _init_sibling_adjacency_list(self):
next_siblings = []
def _travel(node):
if isinstance(node, AbstractSyntaxNode):
child_nodes = []
for field in node.fields:
for val in field.as_value_list:
child_nodes.append(val)
for i in range(len(child_nodes) - 1):
left_node = child_nodes[i]
right_node = child_nodes[i + 1]
next_siblings.append((left_node.id, right_node.id))
for child_node in child_nodes:
_travel(child_node)
_travel(self.root_node)
setattr(self, 'next_siblings_adjacency_list', next_siblings)
@property
def syntax_tokens(self) -> List[SyntaxToken]:
return [token for id, token in self.syntax_tokens_and_ids]
@property
def descendant_nodes(self) -> List[AbstractSyntaxNode]:
for node_id, node in self.id2node.items():
if isinstance(node, AbstractSyntaxNode):
yield node_id, node
def is_syntax_token(self, token):
if isinstance(token, int):
return isinstance(self.id2node[token], SyntaxToken)
else:
return token in self.syntax_tokens_set
def find_node(self, query_node: AbstractSyntaxNode, return_id=True):
search_results = []
for node_id, node in self.descendant_nodes:
if node.production == query_node.production:
if node == query_node:
if return_id:
search_results.append((node_id, node))
else:
search_results.append(node)
return search_results
def copy(self):
ast_copy = AbstractSyntaxTree(root_node=self.root_node.copy())
return ast_copy
class RealizedField(Field):
"""wrapper of field realized with values"""
def __init__(self, field, value=None, parent=None):
super(RealizedField, self).__init__(field.name, field.type, field.cardinality)
# record its parent AST node
self.parent_node = None
# FIXME: hack, return the field as a property
self.field = field
# initialize value to correct type
if self.cardinality == 'multiple':
self.value = []
if value is not None:
for child_node in value:
self.add_value(child_node)
else:
self.value = None
# note the value could be 0!
if value is not None: self.add_value(value)
# properties only used in decoding, record if the field is finished generating
# when card in [optional, multiple]
self._not_single_cardinality_finished = False
def add_value(self, value):
value.parent_field = self
if self.cardinality == 'multiple':
self.value.append(value)
else:
self.value = value
def remove(self, value):
"""remove a value from the field"""
if self.cardinality in ('single', 'optional'):
if self.value == value:
self.value = None
else:
raise ValueError(f'{value} is not a value of the field {self}')
else:
tgt_idx = self.value.index(value)
self.value.pop(tgt_idx)
def replace(self, value, new_value):
"""replace an old field value with a new one"""
if self.cardinality == 'multiple':
tgt_idx = self.value.index(value)
new_value.parent_field = self
self.value[tgt_idx] = new_value
else:
assert self.value == value
new_value.parent_field = self
self.value = new_value
@property
def as_value_list(self):
"""get value as an iterable"""
if self.cardinality == 'multiple': return self.value
elif self.value is not None: return [self.value]
else: return []
@property
def value_count(self):
return len(self.as_value_list)
@property
def finished(self):
if self.cardinality == 'single':
if self.value is None: return False
else: return True
elif self.cardinality == 'optional' and self.value is not None:
return True
else:
if self._not_single_cardinality_finished: return True
else: return False
def set_finish(self):
# assert self.cardinality in ('optional', 'multiple')
self._not_single_cardinality_finished = True
def __eq__(self, other):
if super(RealizedField, self).__eq__(other):
if type(other) == Field: return True # FIXME: hack, Field and RealizedField can compare!
if self.value == other.value: return True
else: return False
else: return False
| true |
fe88b213d75297757588b2f5d97ca7f4f741509a | Python | jd2207/pythonSandbox | /ManuFacturingLine/operations/scanSerialNum.py | UTF-8 | 1,108 | 2.71875 | 3 | [] | no_license | import factoryStation, factoryOperation
import utilities
from operations.operationResult import opResultSuccess, opResultAbort
class scanSerialNum(factoryOperation.factoryOperation):
'''Prompt user to scan or enter the serial number'''
def __init__(self, factoryStation):
self.name = 'scanSerialNum'
self.description = scanSerialNum.__doc__
super(scanSerialNum, self).__init__(factoryStation )
def do(self):
serNum = utilities.serialNumber().getFromUser()
if not serNum.getSN().lower() == 'q':
self.factoryStation.serNum = serNum
self.printToLog('Scanned serial number is %s' % serNum.getSN(), 5)
return opResultSuccess()
else:
return opResultAbort()
# -------------------------------------------------
# Testing
# -------------------------------------------------
if __name__ == "__main__":
fs = factoryStation.factoryStation() # default factoryStation object
fo = scanSerialNum(fs)
fs.operations.append(fo)
# Perform over and over on different devices
fs.deviceLoop(False) # no log collection
| true |
7cf71ab96a35f0518214710bf74e927410dd92aa | Python | nwilming/decim | /decim/immuno_scripts/tsplot_pupil_triallock.py | UTF-8 | 1,227 | 2.5625 | 3 | [] | no_license | import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
# DATA
df = pd.read_csv('/Users/kenohagena/Documents/immuno/da/decim/g_pupilframes/cpf12_all.csv',
header=[0, 1, 2],
index_col=[0, 1, 2, 3],
dtype=np.float64)
# TRANSFORM DATA
clean = df.loc[(df.pupil.parameter.blink == 0) & (df.pupil.parameter.all_artifacts < .2)]
data = clean.pupil.triallock.groupby(level=[0]).mean()
data = data.T
data = pd.DataFrame(data.stack()).reset_index(level=['name', 'subject'])
data.columns = ['name', 'subject', 'value']
data.subject = data.subject.astype(int)
data.name = data.name.astype(float)
# PLOT
f, ax = plt.subplots(figsize=(9, 6))
sns.set_context('notebook', font_scale=1.5)
sns.tsplot(data=data, time='name', unit='subject', value='value', ci=[0, 100], err_style='unit_traces')
ax.axvline(1000, color='black', alpha=.3) # grating shown
ax.axvline(3000, color='black', alpha=.3) # end of choice trial
ax.axvline(3500, color='black', alpha=.3) # next point shown
ax.set_xlabel('Time (ms)')
ax.set_ylabel('Pupilsize (normalized)')
ax.set_title('Pupilsize grating locked')
sns.despine()
f.savefig('gl_p_triallock_12_c.png', dpi=160)
| true |
e0b2d5e6b717a0e6288eee8115a6b760a9da7a2d | Python | lsx0304good/sli0304_crawler | /spider_pracs/request_module.py | UTF-8 | 617 | 2.625 | 3 | [] | no_license | import requests
from fake_useragent import UserAgent
''' POST
url = "https://fanyi.baidu.com/sug"
headers = {
"User-Agent": UserAgent().random
}
data = {"kw": "apple"}
resp: requests.Response = requests.post(url, data=data)
assert resp.status_code == 200
print(resp.content) # byte
print(resp.text) # string
print(resp.json()) # json
'''
url = "https://tieba.baidu.com/f"
headers = {
"User-Agent": UserAgent().random
}
params = {
"ie": "utf-8",
"kw": "Python",
"pn": "50",
}
resp: requests.Response = requests.get(url, params=params)
assert resp.status_code == 200
print(resp.text) | true |
ba8a61092e243c45b742e256d6e75afcef52446a | Python | sasakishun/atcoder | /KEYENCE2019/B.py | UTF-8 | 563 | 2.828125 | 3 | [] | no_license | s = list(input())
removed = False
removing = False
for i in range(len(s)):
last = list("keyence")
j = i
while j < len(s):
if s[j] == last[0]:
del last[0]
if not last:
print("YES")
exit()
else:
j += 1
break
j += 1
# 残り文字がlast = enceみたいになるので
# sの末尾がlast = enceになっていればOK
if i == 0 and j + len(last) <= len(s) and s[len(s)-len(last):] == last:
print("YES")
exit()
print("NO") | true |
b6dab730109d83fb8d6053093ae35a50b268a5ee | Python | DerekWeiChao/KeepTalkingAndNobodyExplodes | /mainint.py | UTF-8 | 10,994 | 3.125 | 3 | [] | no_license | import sys
import string
serial = None
parallel = None
batteries = None
on = 1
def intro():
print("Welcome to the Bomb Defusal Manual\n")
input("To continue, press Enter\n")
menu()
def menu():
serial = int(input("Enter the last digit of the serial number: "))
serialVowel = input("Does the serial number contain a vowel[Y/N]: ")
parallel = input("Is there a parallel port? (Y/N): ").upper()
batteries = int(input("Enter the number of batteries: "))
while on == 1:
print("1: Simple Wires")
print("2: Button")
print("3: Simon Says")
print("4: Word Panel")
print("5: Morse Code")
print("6: Complicated Wires")
print("7: Wire Sequence")
print("8: Passwords")
print("0: Reset")
print("10: Exit")
choice = int(input("Please select a module: "))
if choice == 10:
return
elif choice == 1: #done
simpleWires()
elif choice == 2: #done
pressButton()
elif choice == 3: #done
simonSays()
elif choice == 4: #TODO
wordPanel()
elif choice == 5: #TODO
morseCode()
elif choice == 6: #TODO
complicatedWires()
elif choice == 7: #TODO
wireSequence()
elif choice == 8: #done
passwords()
elif choice == 0:
resetData()
#Tested with success
def simpleWires():
numWires = int(input("Enter the number of wires: "))
if(numWires == 3):
redWire = int(input("Red wires: "))
if redWire == 0:
input("Cut 2nd wire\n")
return
lastWire = input("Last wire color: ")
if lastWire == "white" or lastWire == "White":
input("Cut last wire\n")
return
blueWire = int(input("Blue wires: "))
if blueWire > 1:
input("Cut last blue")
return
else:
input("Cut last wire")
return
elif numWires == 4:
redWire = int(input("Red wires: "))
if redWire == 0:
lastWire = input("Last wire color: ")
if lastWire == "yellow" or lastWire == "Yellow":
input("Cut the first wire")
return
else:
if serial%2 == 1:
input("Cut last red")
return
blueWire = int(input("Blue Wires: "))
if blueWire == 1:
input("Cut the first wire")
return
yellowWire = int(input("Yellow Wires: "))
if yellowWire < 2:
input("Cut the second wire")
return
else:
input("Cut the last wire")
return
elif numWires == 5:
lastWire = input("Last wire color: ")
if lastWire == "Black" or lastWire == "black":
if serial%2 == odd:
input("Cut the 4th wire")
return
else:
input("Cut the 1st wire")
return
redWire = int(input("Red Wires: "))
if redWire == 1:
yellowWire = int(input("Yellow Wires: "))
if yellowWire >= 2:
input("Cut the 1st wire")
return
blackWire = int(input("Black Wires: "))
if blackWire == 0:
input("Cut second wire")
return
else:
input("Cut first wire")
return
elif numWires == 6:
yellowWire = int(input("Yellow Wires: "))
if yellowWire == 0:
if serial%2 == 1:
input("Cut 3rd wire")
return
elif yellowWire == 1:
whiteWire = int(input("White wires: "))
if whiteWire >= 2:
input("Cut the 4th wire")
return
redWire = int(input("Red Wires: "))
if redWire == 0:
input("Cut the last wire")
return
else:
input("Cut the 4th wire")
return
def pressButton():
buttonColor = input("Button color: ").lower()
buttonWord = input("Button: ").lower()
if buttonWord == "detonate":
if batteries > 1:
input("Tap the button")
return
if batteries >= 3 and (buttonColor == "blue" or buttonColor == "Blue"):
if buttonWord == "abort":
heldButton()
return
elif buttonWord == "frk":
input("Tap the button")
return
else:
heldButton()
return
def heldButton():
stripColor = input("Strip Color").lower()
if stripColor == "Blue" or stripColor == "blue":
input("Release on a 4")
return
elif stripColor == "Yellow" or stripColor == "yellow":
input("Release on a 5")
return
else:
input("Release on a 1")
return
def wordPanel():
switch = 1
locList = [
["Bottom Right Word: ","cee", "display", "hold on", "lead", "no", "says", "see", "there", "you are"],
["Bottom Left Word: ","", "leed", "reed", "they're"],
["Middle Right Word: ","blank", "read", "red", "their", "you", "your", "you're"],
["Middle Left Word: ","led", "nothing", "yes", "they are"],
["Top Right Word: ","c", "first", "okay"],["Top Left Word: ","ur"]
]
wordDict = {"blank":"wait, right, okay, middle, blank",
"done":"sure, uh huh, next, what?, your, ur, you're, hold, like, you, u, you are, uh uh, done",
"first":"left, okay, yes, middle, no, right, nothing, uhhh, wait, ready, blank, what, press, first",
"hold":"you are, u, done, uh uh, you, ur, sure, what?, you're, next, hold",
"left":"right, left",
"like":"you're, next, u, ur, hold, done, uh uh, what?, uh huh, you, like",
"middle":"blank, ready, okay, what, nothing, press, no, wait, left, middle",
"next":"what?, uh huh, uh uh, your, hold, sure, next"}
while switch == 1:
topWord = input("Enter word on top (for blank just press Enter): ").lower()
foundL = []
for l in locList:
if topWord in l:
foundL = l
keyWord = input(foundL[0]).lower()
while keyWord not in wordDict.keys():
keyWord = input("Error: Word spelled incorrectly, input again: ")
input(wordDict[keyWord])
done = input("Done?[Y/N]: ")
if done == "Y":
switch = 0
return
def morseCode():
morseDict = {"-":"3.532","....":"3.515","...-":"3.595","..-.":"3.555",
".-..":"3.542","-....":"3.600","-....-..":"3.572","-....-...":"3.575",
"-.....": "3.552"}
def complicatedWires():
pass
def wireSequence():
pass
#done
def passwords():
password = ["about","after","again","below","could",
"every","first","found","great","house",
"large","learn","never","other","place",
"plant","point","right","small","sound",
"spell","still","study","their","there",
"these","thing","think","three","water",
"where","which","world","would","write"]
temp = []
firstLetters = input("Enter the first set of letters: ").lower()
for letters in firstLetters:
for word in password:
if word[0] == letters:
temp.append(word)
password = temp
temp = []
if len(password) == 1:
str = password[0]
input(str)
return
secondLetters = input("Enter the second set of letters: ").lower()
for letters in secondLetters:
for word in password:
if word[1] == letters:
temp.append(word)
password = temp
temp = []
if len(password) == 1:
str = password[0]
input(str)
return
thirdLetters = input("Enter the third set of letters: ").lower()
for letters in thirdLetters:
for word in password:
if word[2] == letters:
temp.append(word)
password = temp
temp = []
if len(password) == 1:
str = password[0]
input(str)
return
fourthLetters = input("Enter the fourth set of letters: ").lower()
for letters in fourthLetters:
for word in password:
if word[3] == letters:
temp.append(word)
password = temp
temp = []
if len(password) == 1:
str = password[0]
input(str)
return
fifthLetters = input("Enter the fifth set of letters: ").lower()
for letters in fifthLetters:
for word in password:
if word[4] == letters:
temp.append(word)
password = temp
temp = []
if len(password) == 1:
str = password[0]
input(str)
return
input("Clearly something went wrong. Let's try that again.")
passwords()
def simonSays():
rbgyOdd = {"red":["blue", "yellow", "green"], "blue":["red", "green", "red"],
"green":["yellow", "blue", "yellow"], "yellow":["green", "red", "blue"]}
rbgyEven = {"red": ["blue", "red", "yellow"], "blue": ["yellow", "blue", "green"],
"green": ["green", "yellow", "blue"], "yellow": ["red", "green", "red"]}
strikes = 0
strike = ""
getIn = ""
solution = ""
done = True
while(done):
if serialVowel == "Y":
sequence = input("Enter color sequence: ").lower()
sequence = sequence.split(" ")
for word in sequence:
solution += rbgyOdd[word][strikes]
print(solution)
strike = input("Any errors in input?{Y/N}: ").lower()
if strike == "Y":
strikes += 1
getIn = input("Done?[Y/N]: ")
if getIn == "Y":
done = False
else:
sequence = input("Enter color sequence: ").lower()
sequence = sequence.split(" ")
for word in sequence:
solution += rbgyEven[word][strikes]
print(solution)
strike = input("Any errors in input?{Y/N}: ")
if strike == "Y":
strikes += 1
getIn = input("Done?[Y/N]: ")
if getIn == "Y":
done = False
return
def resetData():
serial = None
parallel = None
serial = int(input("Enter the last digit of the serial number: "))
parallel = input("Is there a parallel port? (Y/N): ")
parallel = parallel.upper()
batteries = int(input("Enter the number of batteries: "))
if __name__ == '__main__':
intro() | true |
2ab782e6b7b94796319aaac4f137dd1c0256661b | Python | whatbeg/DataScienceTools | /src/test/feature_engineeringSpec.py | UTF-8 | 2,321 | 3.140625 | 3 | [
"MIT"
] | permissive | # ==================================
# Author: whatbeg (Qiu Hu)
# Created by: 2017. 5
# Personal Site: http://whatbeg.com
# ==================================
import numpy as np
import src.main.feature_engineering as feng
class feature_engineeringSpec():
def __init__(self):
pass
def binarySearchSpec(self):
array = [18, 25, 30, 35, 40, 45, 50, 55, 60, 65]
assert feng.binary_search(7, array) == 0
# print ("feng.binary_search(7, array) == {}".format(feng.binary_search(7, array)))
assert feng.binary_search(20, array) == 1
assert feng.binary_search(80, array) == 10
assert feng.binary_search(-1, array) == 0
def bucketized_columnSpec(self):
column = [5, 29, 30, 43, 64, 89]
boundaries = [18, 25, 30, 35, 40, 45, 50, 55, 60, 65]
feature_column = feng.bucketized_column(column, boundaries)
assert feature_column == [0, 2, 2, 5, 9, 10]
def discretize_for_lookupTableSpec(self):
column = [1, 2, 3]
data_tensor = np.array([
[45, 3, 12, 2],
[3, 4, 5, 9],
[24, 6, 2, 9]
])
data_tensor = feng.discretize_for_lookupTable(data_tensor, column, 1)
assert (data_tensor == np.array([[45, 1, 3, 1], [3, 2, 2, 2], [24, 3, 1, 2]])).all()
def cross_columnSpec(self):
columns = np.array([
['lisa', 'doctor', 30],
['william', 'worker', 23],
['allen', 'lawyer', 20]
])
name_occupation = feng.cross_column(columns[:, :2], 100)
assert name_occupation.shape == (3, 1)
assert (name_occupation == np.array([[38], [22], [39]])).all()
name_occupation_salary = feng.cross_column(columns, 300)
assert (name_occupation_salary == np.array([[183], [95], [279]])).all()
def sparse_columnSpec(self):
column = np.array([1, 2, 3])
ret_column = feng.sparse_column(column, vocab_size=4)
# print(ret_column)
def doTest(self):
self.binarySearchSpec()
self.bucketized_columnSpec()
self.discretize_for_lookupTableSpec()
self.cross_columnSpec()
self.sparse_columnSpec()
print ("All Test Passed!")
if __name__ == '__main__':
feSpec = feature_engineeringSpec()
feSpec.doTest()
| true |
e4868979c87b29423279d52db8a9ca79f821c3bf | Python | jinrongchi/MapReduce | /Part2/mapper.py | UTF-8 | 701 | 3.203125 | 3 | [] | no_license | #!/usr/bin/env python
"""mapper.py"""
import sys
word_list = []
# input comes from STDIN (standard input)
for line in sys.stdin:
# remove leading and trailing whitespace
line = line.strip()
# split the line into words
words = line.split()
word_list.extend(words)
bigrams = [word_list[x:x+2] for x in range(len(word_list))]
# increase counters
for bigram in bigrams:
# write the results to STDOUT (standard output); what we output here will be the input for the Reduce step, i.e. the
# input for reducer.py
#
# tab-delimited; the trivial word count is 1
if(len(bigram) == 2):
bigram = bigram[0] + ' ' + bigram[1]
print ('%s\t%s' % (bigram,1))
| true |
8fe674a7e95c2cb063b6c635a454011b6ccec12d | Python | dicao425/algorithmExercise | /LeetCode/islandPerimeter.py | UTF-8 | 784 | 3.328125 | 3 | [] | no_license | #!/usr/bin/python
import sys
class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
result = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
result += self.dfs(grid, i + 1, j) + self.dfs(grid, i, j + 1) + self.dfs(grid, i - 1, j) + self.dfs(grid, i, j - 1)
return result
def dfs(self, grid, x, y):
if x < 0 or y < 0 or x >= len(grid) or y >= len(grid[0]) or grid[x][y] == 0:
return 1
return 0
def main():
aa = Solution()
print aa.islandPerimeter([[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]])
return 0
if __name__ == "__main__":
sys.exit(main())
| true |
87a768d1513bb211b038c9ef191a5e22f29d47fb | Python | patriquejarry/Apprendre-coder-avec-Python | /Module_6/UpyLaB 6.19.py | UTF-8 | 2,025 | 3.859375 | 4 | [] | no_license | import random
MY_PRECIOUS = 1
TRAP = -1
def create_map(size, trapsNbr):
""" fonction qui reçoit deux entiers en paramètres, size, compris entre 2 et 100, et trapsNbr,
de valeur strictement inférieure à size x size, et qui retourne un dictionnaire implémentant comme dans
l’exemple précédent une carte de taille size et dans laquelle figurent trapsNbr cases contenant un piège
(modélisé par la valeur -1) et une case contenant un trésor (modélisé par la valeur 1).
L’emplacement de ces cases sera aléatoire. """
my_map = {}
while len(my_map) < trapsNbr:
my_map.setdefault((random.randint(1, size), random.randint(1, size)), TRAP)
while len(my_map) < trapsNbr + 1:
my_map.setdefault((random.randint(1, size), random.randint(1, size)), MY_PRECIOUS)
return my_map
def play_game(map_size, treasure_map):
""" fonction qui reçoit un entier et une carte de taille map_size x map_size, telle que celles obtenues
grâce à la fonction create_map, et qui demande à l’utilisateur d’entrer les coordonnées d’une case,
jusqu’à tomber sur une case occupée. Si l’utilisateur a trouvé le trésor, la fonction retourne la valeur True,
sinon l’utilisateur est tombé sur un piège et la fonction retourne False. """
while True:
coord = input().split()
if len(coord) == 2 and coord[0].isdigit() and coord[1].isdigit():
i, j = int(coord[0]), int(coord[1])
if i in range(map_size + 1) and j in range(map_size + 1):
if (i, j) in treasure_map:
return treasure_map.get((i, j)) == MY_PRECIOUS
print(play_game(5, {(3, 4): -1, (4, 1): 1, (2, 3): -1, (1, 5): -1}))
# 4 2
# 4 4
# 1 3
# 4 4
# 3 1
# 4 4
# 4 3
# 1 1
# 3 1
# 3 2
# 2 1
# 4 3
# 1 2
# 4 1
# True
print(play_game(5, {(3, 4): -1, (4, 1): 1, (2, 3): -1, (1, 5): -1}))
# 4 7
# 4 3
# 2 5
# 2 3
# False
print(create_map(4, 5))
# {(3, 1): 1, (4, 2): -1, (1, 1): -1, (1, 4): -1, (2, 2): -1, (4, 4): -1}
| true |
f2388c100ade206bab2115208ee6d580ba83a942 | Python | tangshenhong/PycharmProjects | /socketExercise/server.py | UTF-8 | 424 | 2.6875 | 3 | [] | no_license | #-*- coding:utf-8 -*-
# @Time :2019/5/28 9:47
import socket
addr=('127.0.0.1',2020)
s=socket.socket()
s.bind(addr)
s.listen(5)
print('服务端进入等待状态')
conn,clientaddr=s.accept()
print('服务端开始服务了')
#1024表示每次最多接受1024个字节
recv=conn.recv(1024)
print('客户端给你发送了:',str(recv,encoding='utf8'))
reply=bytes('hello too',encoding='utf8')
conn.sendall(reply)
s.close()
| true |
e035f7ecdd0dfec2ea85b7366212fdd2ce9f9b23 | Python | dychangfeng/myscripts | /python_scripts/cruciform_DNA5.py | UTF-8 | 4,300 | 2.921875 | 3 | [] | no_license | #!/Users/Yun/anaconda2/bin/python
import re
import sys
import string
import argparse ## adding parameters
import operator ## use for the sorting tabl
from datetime import datetime
start_at=datetime.now()
## take two arguments, the fasta file and the number of processors to use
parser = argparse.ArgumentParser(description = """to find cruciform DNA""",formatter_class= argparse.RawTextHelpFormatter)
parser.add_argument('--fasta', '-f',
type= str,
help='''Input file in fasta format containing one or more
sequences. Use '-' to get the name of the file from stdin
''',
required= True)
args = parser.parse_args()
##-------------------------functions-------------------------
## inverted repeats are reverse complementary of each other
def comp(seq):
"""take a sequence and return the reverse complementary strand of this seq
input: a DNA sequence
output: the complementary of this seq"""
bases_dict = {'A':'T', 'T':'A', 'G':'C', 'C':'G', 'N':'O'}
##get the complementary if key is in the dict, otherwise return the base, set O base pair with N to remove NNNN in the genome
return(''.join(bases_dict.get(base, base) for base in seq[::-1]))
def get_cruci_list(seq_name, seq):
"""take a sequence and return the location, loop size, stem size of the cruciform DNA
todo: vectorize with numpy"""
cruci = []
pos = len(seq)-(5+12+1) ## the last position to check
max_loop =8
max_stem = 11
t = max_stem + max_loop ## starting point, t sit in the middle of the cruciform structure
while t < pos:
jump=False
for i in range(3,8,1): ## the even number loop
l=int(i/2)
for j in range(11, 5, -1): ## for stem 18 to 6
if i%2==0:
if seq[(t-j-l):(t-l)].upper() == comp(seq[(t+l):(t+l+j)].upper()):
cruci.append([seq_name, t-j-l,t+l+j, i, j, seq[t-j-l:t+j+l]])
#cruci_set.update([t+j, i]) ## add the start and the end position to the set, make sure it is unique
t = t + 2*j + i ## t=t+j+4+6 assume the small length?
jump=True
break
elif i%2!=0: #odd number loop
if seq[(t-j-l):(t-l)].upper() == comp(seq[(t+l+1):(t+l+1+j)].upper()):
cruci.append([seq_name, t-j-l,t+l+j+1, i, j, seq[t-j-l:t+j+l+1]]) ## add one extra base for the l=int(i/2) step
#cruci_set.update([t+j, i]) ## add the start and the end position to the set, make sure it is unique
t = t + 2*j + i ## t=t+j+4+6 assume the small length?
jump=True
break
if jump: ## find a match, stop looking for the smaller one
break # break from the loop scan
else: ## finish the for loop, add 1 to cursor
t+=1 # move the cursor 1 bp if didn't find any match
return(cruci)
##-------------------------------------read and process files line by line-----------------
if args.fasta == '-':
ref_seq_fh= sys.stdin
else:
ref_seq_fh= open(args.fasta)
cruci_all = []
ref_seq=[]
line= (ref_seq_fh.readline()).strip()
chr= re.sub('^>', '', line) ## get the chr name, remove the '>' sign
line= (ref_seq_fh.readline()).strip() # read another line
while True:
while line.startswith('>') is False:
## get the list of ref_seq for this chr
ref_seq.append(line)
line= (ref_seq_fh.readline()).strip()
if line == '':
break
ref_seq= ''.join(ref_seq) # join the sequence of the ref seq
cruci_all.extend(get_cruci_list(chr, ref_seq)) ## extend the list of cruci to all cruci
chr= re.sub('^>', '', line)
ref_seq= [] ## clear the ref_seq
line= (ref_seq_fh.readline()).strip() ## read a new line that it does not start with a ">"
if line == '':
break
ref_seq_fh.close() ## close the handle when done
#cruci_final= sorted(cruci_all, key=operator.itemgetter(0,1,2)) # sort by name, start and end position
for line in cruci_all:
line= '\t'.join([str(x) for x in line])
print(line)
total_time=datetime.now()-start_at
print(total_time)
sys.exit() | true |
c66a26f926168f46890ff516b5df22e5f1999bd4 | Python | thylakoids/sudoku | /sudoku.py | UTF-8 | 9,006 | 3.28125 | 3 | [] | no_license | import unittest
import numpy as np
import copy
def valid_type(type):
if type in (int, np.int, np.int8, np.int16, np.int32, np.int64):
return True
else:
return False
class sudoPoint():
"""point in a sudoku
Possible state of the point in a sudoku.
0 : not sure.
-1: error.
"""
def __init__(self, num=0):
self._avaliable = set(range(1, 10))
self.avaliable = num
@property
def avaliable(self):
if len(self._avaliable) == 0: # which will not occur here
return -1
if len(self._avaliable) == 1:
return list(self._avaliable)[0]
else:
return 0
@avaliable.setter
def avaliable(self, num):
if valid_type(type(num)) and num >= 0 and num <= 9:
if num == 0:
return
else:
self._avaliable = set([num])
else:
raise(TypeError('num should in in the range of 0~9'))
def exclude(self, exclusion):
"""exclude
:param exclusion: int or array
"""
if self.avaliable == 0:
if isinstance(exclusion, int):
exclusion = [exclusion]
self._avaliable = self._avaliable.difference(exclusion)
class sudoku():
"""sudoku"""
def __init__(self):
# using 9*9 numpy array to represent sudoku data, 0 means empty square.
self.candidate = np.array([sudoPoint()] * 81).reshape([9, 9])
@property
def sudo(self):
return self.getSudoFromCandidate(self.candidate)
@sudo.setter
def sudo(self, sudo):
# require: 9*9 numpy array&int&>=0&<=9
if isinstance(sudo, np.ndarray) and sudo.shape == (9, 9):
if valid_type(sudo.dtype.type) and sudo.min() >= 0 and sudo.max() <= 9:
for i in range(9):
for j in range(9):
self.candidate[i, j] = sudoPoint(sudo[i, j])
else:
raise(TypeError('Input data for sudo be int and in the range of 0~9'))
else:
raise(TypeError('Input data for sudo should be 9*9 np.ndarray'))
@staticmethod
def getSudoFromCandidate(candidate):
sudo = np.empty([9, 9])
for i in range(9):
for j in range(9):
sudo[i, j] = candidate[i, j].avaliable
return sudo
@staticmethod
def _checkState(data):
data_nonzero = data[np.nonzero(data)]
unique, counts = np.unique(data_nonzero, return_counts=True)
if len(counts) >= 1 and counts.max() >= 2:
return -1
elif len(unique) < 9:
return 0
else:
return 1
@classmethod
def checkStateSudo(cls, sudo)->int:
"""check current state of sudoku
solution:
1. if has nonzero repeat number, return -1
2. if no repeat and has 0, return 0
3. if no repeat and no 0, return 1
Returns:
int: 1: solved
0: to be solved
-1:something went wrong
"""
state = 1
for i in range(9):
data_line = sudo[i, :]
data_column = sudo[:, i]
a = int(np.floor(i / 3))
b = i % 3
data_block = sudo[a * 3:a * 3 + 3, b * 3:b * 3 + 3]
for data in [data_line, data_column, data_block]:
_state = cls._checkState(data)
if _state == -1:
# print(data)
return _state
elif _state == 0:
state = 0
return state
@classmethod
def checkStateCandidate(cls, candidate):
return cls.checkStateSudo(cls.getSudoFromCandidate(candidate))
@classmethod
def exclude(cls, candidate):
sudo = cls.getSudoFromCandidate(candidate)
for i in range(9):
# line
exclusion = np.unique(sudo[i, :])
for j in range(9):
candidate[i, j].exclude(exclusion)
# column
exclusion = np.unique(sudo[:, i])
for j in range(9):
candidate[j, i].exclude(exclusion)
# block
a = int(np.floor(i / 3))
b = i % 3
exclusion = np.unique(sudo[a * 3:a * 3 + 3, b * 3:b * 3 + 3])
# print(exclusion)
for l in range(a * 3, a * 3 + 3):
for c in range(b * 3, b * 3 + 3):
candidate[l, c].exclude(exclusion)
return candidate
@classmethod
def guess(cls, candidate):
len_candidate = np.array([len(x._avaliable) for x in
candidate.flatten()]).reshape([9, 9])
l, c = np.where(len_candidate == len_candidate[len_candidate > 1].min())
_avaliable1 = candidate[l[0], c[0]]._avaliable
_avaliable2 = set([_avaliable1.pop()])
candidate1 = copy.deepcopy(candidate)
candidate1[l[0], c[0]]._avaliable = _avaliable1
candidate2 = copy.deepcopy(candidate)
candidate2[l[0], c[0]]._avaliable = _avaliable2
return candidate1, candidate2
@classmethod
def solve(cls, candidate):
"""may have multi solution!! need improve
Args:
candidate (TYPE): Description
Returns:
TYPE: Description
"""
candidate = cls.exclude(candidate)
sudo = cls.getSudoFromCandidate(candidate)
state = cls.checkStateSudo(sudo)
if state == 1:
return sudo
elif state == -1:
return -1
else:
candidate1, candidate2 = cls.guess(candidate)
solution1 = cls.solve(candidate1)
if isinstance(solution1, np.ndarray):
return solution1
else:
solution2 = cls.solve(candidate2)
if isinstance(solution2, np.ndarray):
return solution2
else:
return -1
class testSuduku(unittest.TestCase):
"""testSuduku"""
mysudo = sudoku()
sudo_solved = np.array([[7, 3, 5, 6, 1, 4, 8, 9, 2],
[8, 4, 2, 9, 7, 3, 5, 6, 1],
[9, 6, 1, 2, 8, 5, 3, 7, 4],
[2, 8, 6, 3, 4, 9, 1, 5, 7],
[4, 1, 3, 8, 5, 7, 9, 2, 6],
[5, 7, 9, 1, 2, 6, 4, 3, 8],
[1, 5, 7, 4, 9, 2, 6, 8, 3],
[6, 9, 4, 7, 3, 8, 2, 1, 5],
[3, 2, 8, 5, 6, 1, 7, 4, 9]]).astype(int)
sudo_tobesolved = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 3, 0, 8, 5],
[0, 0, 1, 0, 2, 0, 0, 0, 0],
[0, 0, 0, 5, 0, 7, 0, 0, 0],
[0, 0, 4, 0, 0, 0, 0, 0, 0],
[0, 9, 0, 0, 0, 0, 0, 0, 0],
[5, 0, 0, 0, 0, 0, 0, 7, 3],
[0, 0, 2, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 4, 0, 0, 0, 9]]).astype(int)
sudo_error = np.array([[1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 3, 0, 8, 5],
[0, 0, 1, 0, 2, 0, 0, 0, 0],
[0, 0, 0, 5, 0, 7, 0, 0, 0],
[0, 0, 4, 0, 0, 0, 0, 0, 0],
[0, 9, 0, 0, 0, 0, 0, 0, 0],
[5, 0, 0, 0, 0, 0, 0, 7, 3],
[0, 0, 2, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 4, 0, 0, 0, 9]]).astype(int)
def test_setter(self):
self.mysudo.sudo = np.random.randint(1, 9, (9, 9)).astype(int)
with self.assertRaises(TypeError):
self.mysudo.sudo = np.random.randint(1, 9, (9, 9)).astype(float)
def test_checkState(self):
self.mysudo.sudo = self.sudo_solved
self.assertEqual(self.mysudo.checkStateSudo(self.mysudo.sudo), 1)
self.mysudo.sudo = self.sudo_tobesolved
self.assertEqual(self.mysudo.checkStateSudo(self.mysudo.sudo), 0)
self.mysudo.sudo = self.sudo_error
self.assertEqual(self.mysudo.checkStateSudo(self.mysudo.sudo), -1)
def test_exclude(self):
self.mysudo.sudo = self.sudo_tobesolved
self.mysudo.exclude(self.mysudo.candidate)
self.assertEqual(self.mysudo.candidate[2, 7]._avaliable, set([3, 4, 6, 9]))
def test_guess(self):
self.mysudo.sudo = self.sudo_tobesolved
self.mysudo.exclude(self.mysudo.candidate)
self.mysudo.guess(self.mysudo.candidate)
def test_solve(self):
self.mysudo.sudo = self.sudo_tobesolved
solution = self.mysudo.solve(self.mysudo.candidate)
print(solution)
if __name__ == '__main__':
unittest.main()
# print(x.candidate)
# mysudo = sudoku()
# mysudo.sudo = np.random.randint(1, 9, (9, 9)).astype(int)
| true |
3eea7008891680c6007f5f4f336a5737d3e53e15 | Python | charlesartbr/hackerrank-python | /solved.py | UTF-8 | 792 | 2.984375 | 3 | [] | no_license | import os
def count_solved(path):
solved = 0
for entry in os.listdir(path):
if entry.startswith('.'):
continue
fullpath = os.path.join(path, entry)
if os.path.isdir(fullpath):
if any(file.endswith('.py') for file in os.listdir(fullpath)):
solved += 1
solved += count_solved(fullpath)
return solved
solved = count_solved('.')
txt = 'challenges solved'
print(solved, txt)
with open("README.md", "r") as readme:
lines = []
for line in readme:
if txt in line:
lines.append('### **' + str(solved) + '** ' + txt + ':\n')
else:
lines.append(line)
with open("README.md", "w") as readme:
readme.writelines(lines)
| true |
4e102e6855e7c6ae24c3ffcd1adb64eafdd7d9eb | Python | Azezl/CodeForces_PY | /Problems_Difficulty_800/I_love_%username%.py | UTF-8 | 302 | 3.453125 | 3 | [] | no_license | n = int(input())
lst = (input()).split()
maxi = int(lst[0])
mini = int(lst[0])
amazing = 0
for i in range(1, n):
if int(lst[i]) > maxi:
amazing = amazing + 1
maxi = int(lst[i])
elif int(lst[i]) < mini:
amazing = amazing + 1
mini = int(lst[i])
print(amazing)
| true |
ead6d4efa3c718f194efb1e24c03fb72dc45aa03 | Python | nsirons/A32_SVV | /main/MOI.py | UTF-8 | 9,782 | 3.109375 | 3 | [] | no_license | from math import pi, sin, cos, atan2, sqrt, radians
def calculate_inertia_rotated_rectangle(width, height, angle):
return (width**3 * height * sin(angle)**2 * 1.0 ) / 12.
def calculate_inertia_circular_skin(radius, thickness):
return (pi * radius**3 * thickness)/2.
def calculate_inertia_steiner(original_inertia, area, arm):
return original_inertia + area*(arm)**2
def calculate_stiffener_positions(aileron):
length_flat_skin = sqrt( (aileron.height_aileron/2)**2 + (aileron.chord_aileron - aileron.height_aileron/2)**2 )
length_circular_skin = pi*aileron.height_aileron/2
angle_flat_skin = atan2(aileron.height_aileron/2, aileron.chord_aileron - aileron.height_aileron/2)
length_total_skin = 2*length_flat_skin + length_circular_skin
distance_between_stiffeners = length_total_skin / (aileron.stiffener_amount + 1)
stiffener_positions = []
current_length = 0
for i in range(1, aileron.stiffener_amount+1):
current_length += distance_between_stiffeners
position = []
if 0 <= current_length <= length_flat_skin:
x = aileron.chord_aileron - current_length*cos(angle_flat_skin)
y = current_length*sin(angle_flat_skin)
position = [x,y]
elif length_flat_skin < current_length <= (length_flat_skin + length_circular_skin):
current_angle = pi/2 + (current_length - length_flat_skin)/(2*pi*aileron.height_aileron/2)*2*pi
x = aileron.height_aileron/2 + aileron.height_aileron/2*cos(current_angle)
y = aileron.height_aileron/2*sin(current_angle)
position = [x,y]
elif (length_flat_skin + length_circular_skin) < current_length <= length_total_skin:
modified_current_length = length_total_skin - current_length
x = aileron.chord_aileron - modified_current_length*cos(angle_flat_skin)
y = modified_current_length*sin(-angle_flat_skin)
position = [x,y]
else:
position = [-1, -1]
stiffener_positions.append(position)
return stiffener_positions
def calculate_stiffener_inertia(aileron):
area_horizontal_part = aileron.stiffener_thickness*aileron.stiffener_width
arm_horizontal_part = (aileron.stiffener_height-0.5*aileron.stiffener_thickness)
area_vertical_part = (aileron.stiffener_height-aileron.stiffener_thickness)*aileron.stiffener_thickness
arm_vertical_part = (aileron.stiffener_height-aileron.stiffener_thickness)*0.5
centroid_x = 0.5*aileron.stiffener_width
centroid_y = (area_horizontal_part*arm_horizontal_part + area_vertical_part*arm_vertical_part) / (area_horizontal_part + area_vertical_part)
inertia_horizontal_part = calculate_inertia_rotated_rectangle(aileron.stiffener_width, aileron.stiffener_thickness, 0)
final_inertia_horizontal_part = calculate_inertia_steiner(inertia_horizontal_part, area_horizontal_part, (arm_horizontal_part-centroid_y))
inertia_vertical_part = calculate_inertia_rotated_rectangle(aileron.stiffener_thickness, (aileron.stiffener_height-aileron.stiffener_thickness), 0)
final_inertia_vertical_part = calculate_inertia_steiner(inertia_vertical_part, area_vertical_part, (arm_vertical_part - centroid_y))
inertia_stiffener = final_inertia_horizontal_part + final_inertia_vertical_part
return inertia_stiffener
def calculate_stiffener_inertia_yy(aileron):
inertia_horizontal_part = aileron.stiffener_width**3 * aileron.stiffener_thickness / 12
inertia_vertical_part = aileron.stiffener_thickness**3 * (aileron.stiffener_height - aileron.stiffener_thickness) /12
return inertia_horizontal_part + inertia_vertical_part
def calculate_inertia_zz(aileron):
width_angled_skin = sqrt( (aileron.height_aileron/2)**2 + (aileron.chord_aileron - aileron.height_aileron/2)**2 )
length_total_skin = width_angled_skin*2 + pi*(aileron.height_aileron/2)
angle_skin_top = -1* atan2(aileron.height_aileron/2, aileron.chord_aileron - aileron.height_aileron/2)
stiffener_area = aileron.stiffener_thickness*aileron.stiffener_width + (aileron.stiffener_height-aileron.stiffener_thickness)*aileron.stiffener_thickness
inertia_circular_skin = calculate_inertia_circular_skin(aileron.height_aileron/2., aileron.skin_thickness)
arm_circular_skin = 0
area_circular_skin = 0
final_inertia_circular_skin = calculate_inertia_steiner(inertia_circular_skin,area_circular_skin,arm_circular_skin)
inertia_spar = calculate_inertia_rotated_rectangle(aileron.height_aileron, aileron.spar_thickness, pi/2)
arm_spar = 0
area_spar = aileron.skin_thickness * aileron.height_aileron
final_inertia_spar = calculate_inertia_steiner(inertia_spar, area_spar, arm_spar)
inertia_flat_skin = calculate_inertia_rotated_rectangle(width_angled_skin, aileron.skin_thickness, angle_skin_top)
arm_flat_skin = aileron.height_aileron/4.
area_flat_skin = width_angled_skin * aileron.skin_thickness
final_inertia_flat_skin = calculate_inertia_steiner(inertia_flat_skin, area_flat_skin, arm_flat_skin)
inertia_stiffener = calculate_stiffener_inertia(aileron)
stiffener_positions = calculate_stiffener_positions(aileron)
final_inertia_stiffeners = 0
for x,arm in stiffener_positions:
final_inertia_stiffeners += calculate_inertia_steiner(inertia_stiffener,stiffener_area, arm)
total_inertia = final_inertia_stiffeners + final_inertia_circular_skin + final_inertia_flat_skin*2 + final_inertia_spar
return total_inertia
def calculate_zbar(aileron):
width_angled_skin = sqrt( (aileron.height_aileron/2)**2 + (aileron.chord_aileron - aileron.height_aileron/2)**2 )
length_total_skin = width_angled_skin*2 + pi*(aileron.height_aileron/2)
angle_skin_top = -1* atan2(aileron.height_aileron/2, aileron.chord_aileron - aileron.height_aileron/2)
area_stiffener = aileron.stiffener_thickness*aileron.stiffener_width + (aileron.stiffener_height-aileron.stiffener_thickness)*aileron.stiffener_thickness
area_flat_skin = aileron.skin_thickness * width_angled_skin
arm_flat_skin = (aileron.chord_aileron - aileron.height_aileron/2)/2 + aileron.height_aileron/2
area_circular_skin = pi*aileron.height_aileron/2 * aileron.skin_thickness
arm_circular_skin = aileron.height_aileron/2 - 2*aileron.height_aileron/2/pi
area_spar = aileron.height_aileron * aileron.spar_thickness
arm_spar = aileron.height_aileron/2
stiffener_positions = calculate_stiffener_positions(aileron)
stiffener_FMOA_sum = 0
for x,y in stiffener_positions:
stiffener_FMOA_sum += area_stiffener*x
centroid_x = (stiffener_FMOA_sum + area_circular_skin*arm_circular_skin + 2*(area_flat_skin*arm_flat_skin) + area_spar*arm_spar )/\
(aileron.stiffener_amount*area_stiffener + area_circular_skin + 2* area_flat_skin + area_spar)
return centroid_x - aileron.height_aileron/2
def calculate_inertia_yy(aileron):
width_angled_skin = sqrt( (aileron.height_aileron/2)**2 + (aileron.chord_aileron - aileron.height_aileron/2)**2 )
length_total_skin = width_angled_skin*2 + pi*(aileron.height_aileron/2)
angle_skin_top = -1* atan2(aileron.height_aileron/2, aileron.chord_aileron - aileron.height_aileron/2)
area_stiffener = aileron.stiffener_thickness*aileron.stiffener_width + (aileron.stiffener_height-aileron.stiffener_thickness)*aileron.stiffener_thickness
area_flat_skin = aileron.skin_thickness * width_angled_skin
arm_flat_skin = (aileron.chord_aileron - aileron.height_aileron/2)/2 + aileron.height_aileron/2
area_circular_skin = pi*aileron.height_aileron/2 * aileron.skin_thickness
arm_circular_skin = aileron.height_aileron/2 - 2*aileron.height_aileron/2/pi
area_spar = aileron.height_aileron * aileron.spar_thickness
arm_spar = aileron.height_aileron/2
stiffener_positions = calculate_stiffener_positions(aileron)
stiffener_FMOA_sum = 0
for x,y in stiffener_positions:
stiffener_FMOA_sum += area_stiffener*x
centroid_x = (stiffener_FMOA_sum + area_circular_skin*arm_circular_skin + 2*(area_flat_skin*arm_flat_skin) + area_spar*arm_spar )/\
(aileron.stiffener_amount*area_stiffener + area_circular_skin + 2* area_flat_skin + area_spar)
inertia_flat_skin = width_angled_skin**3 * aileron.skin_thickness * cos(angle_skin_top)**2 / 12
final_inertia_flat_skin = calculate_inertia_steiner(inertia_flat_skin, area_flat_skin, (arm_flat_skin - centroid_x))
inertia_spar = aileron.spar_thickness**3 * aileron.height_aileron / 12
final_inertia_spar = calculate_inertia_steiner(inertia_spar, area_spar, arm_spar - centroid_x)
inertia_circular_skin = ((pi*pi - 8) * aileron.height_aileron**3 * aileron.skin_thickness)/(2*pi)
final_inertia_circular_skin = calculate_inertia_steiner(inertia_circular_skin, area_circular_skin, arm_circular_skin - centroid_x)
inertia_stiffener = calculate_stiffener_inertia_yy(aileron)
final_inertia_stiffener = 0
for x,y in stiffener_positions:
final_inertia_stiffener += calculate_inertia_steiner(inertia_stiffener, area_stiffener, x-centroid_x)
return final_inertia_stiffener + final_inertia_spar + final_inertia_circular_skin + 2*final_inertia_flat_skin
def calculate_rotated_inertia(inertia_uu, inertia_vv, inertia_uv, angle):
inertia_zz = (inertia_uu + inertia_vv)/2. + (inertia_uu - inertia_vv)/2.*cos(radians(2*angle)) - inertia_uv*sin(radians(2*angle))
inertia_yy = (inertia_uu + inertia_vv)/2. - (inertia_uu-inertia_vv)/2.*cos(radians(2*angle)) + inertia_uv*sin(radians(2*angle))
inertia_zy = (inertia_uu - inertia_vv)/2.*sin(radians(2*angle)) + inertia_uv*cos(radians(2*angle))
return (inertia_zz, inertia_yy, inertia_zy)
| true |
592b57d742a4629d2c4f0f25685e28befca2be7c | Python | umaqsud/taverna-to-pig | /src/main/resources/templates/python_stream.st | UTF-8 | 249 | 2.671875 | 3 | [] | no_license | #!/usr/bin/python
import sys, os, string
for line in sys.stdin:
if len(line) == 0: continue
new_lines = os.popen("<command>" + line).readlines()
striped_lines = [x.strip() for x in new_lines]
print '%s' % (' '.join(striped_lines)) | true |
2f555f0b2e93aee1050b8464230172d3f21dbfdc | Python | NiteshTyagi/leetcode | /solutions/476. Number Complement.py | UTF-8 | 195 | 2.921875 | 3 | [] | no_license | class Solution:
import math
def findComplement(self, num: int) -> int:
nob = int(math.floor(math.log(num)/math.log(2))+1)
return ((1<<nob)-1)^num
| true |
9282dca6ec9ff2899e050223614c6d767f213e1c | Python | Rob-Valdez/threat-analyzer | /threats.py | UTF-8 | 1,808 | 3.984375 | 4 | [] | no_license | # This is a threat analysis tool
def main():
print_header()
threats_list = create_threat()
evaluated_threats_list = evaluate_threat(threats_list)
print_results(evaluated_threats_list)
def print_header():
print('------------------------------------------------------------------')
print(' Threat Analysis')
print('------------------------------------------------------------------')
print('')
def create_threat():
threats_list = []
active = True
while active:
message = input(
'\n'
'Enter a threat for analysis? [\'y\' to enter a threat or \'n\' to quit]\n'
).strip().lower()
if message == 'y':
threat = {
'name': input('What is the name of the threat?\n'),
'category': input('What initiates this threat? [human, equipment, environment]\n'),
'vector': input('What is the vector [pathway] of this threat?\n')
}
threats_list.append(threat)
elif message == 'n':
break
else:
print('That is not a valid option.')
return threats_list
def evaluate_threat(threats_list):
print('Let\'s evaluate the likelihood of each threat.')
evaluated_threats_list = []
for each in threats_list:
print('\nThreat: ', end='')
print(each['name'].title())
each['likelihood'] = input('What is the likelihood of this threat?\n')
evaluated_threats_list.append(each)
return evaluated_threats_list
def print_results(evaluated_threat_list):
print('\nHere are the results:')
for each in evaluated_threat_list:
print('')
for k, v in each.items():
print(f'{k}: {v}')
if __name__ == '__main__':
main()
| true |
d28658a3275ceb0e8cc3e2fc6d02e0451047b8bc | Python | mk1107/Python-LAB | /palindrome.py | UTF-8 | 323 | 4.6875 | 5 | [] | no_license | #Ask the user for a string and print out whether this string is a palindrome or not.
s=input("ENTER ANY STRING:- ")
x=len(s)
f=True
for i in range (0,int(x/2)-1):
if(s[i]!=s[x-1-i]):
f=False
break
if(f==True):
print("GIVEN STRING IS PALINDROME")
else:
print("GIVEN STRING IS NOT A PALINDROME") | true |
a69d4f55979adc963d3026b8e1029c616bce3133 | Python | thghu123/python-basic-example | /1105/1105_pm/if_test.py | UTF-8 | 151 | 3.921875 | 4 | [] | no_license | str = input('나이입력:')
age = int(str)
if(age>=20):
print("성인")
elif(age<15):
print("어린이")
else :
print("성인 아님")
| true |
0eef8a6f097d13c67f6c739487d45da798245099 | Python | selvamanikannan/freetest | /num.py | UTF-8 | 65 | 3.09375 | 3 | [] | no_license | st=""
for x in range(10**9):
st+=str(x)
print(st[int(input())]) | true |
824e79d5efb55bd08185f97fbb8a747477d7a096 | Python | ricardo-silveira/grafluence | /tools/preprocessing.py | UTF-8 | 1,497 | 2.65625 | 3 | [] | no_license | import json
import heapq
import contextlib2
def avoid_first_line(file_iterator):
first_line = True
for line in file_iterator:
if not first_line:
yield line
first_line = False
citation_path = "../data/APS/output/graph/citation_graphs/files.json"
#coauthorship_path = "../data/APS/output/graph/coauthorship_graphs/files.json"
all_files_citation = [x.replace("output/", "output/graph/") for x in json.load(open(citation_path))]
#all_files_coauthorship = [x.replace("output/", "output/graph/") for x in json.load(open(coauthorship_path))]
def external_merge(files_path):
filenames_year = {}
root_path = "../data/APS"
for file_path in files_path:
# selecting files for year
info = file_path.split("/")
year = info[3]
graph_path = "%s/%s" % (root_path, "/".join(info[:-1])+"/%s.txt" % year)
file_path = "%s/%s" % (root_path, file_path)
if graph_path not in filenames_year:
filenames_year[graph_path] = []
filenames_year[graph_path].append(file_path)
for graph_path, filenames in filenames_year.iteritems():
# merging files for each year
print graph_path
with contextlib2.ExitStack() as stack:
files = [avoid_first_line(stack.enter_context(open(fn))) for fn in filenames]
with open(graph_path, "w") as f:
f.writelines(heapq.merge(*files))
#external_merge(all_files_coauthorship)
external_merge(all_files_citation)
| true |
8ece97a89d94c9ff75b1929d02e94dd14aeaf088 | Python | StatistikChris/football_ai_standalone | /gui.py | UTF-8 | 2,060 | 3.0625 | 3 | [] | no_license | from tkinter import *
from tkinter.ttk import Combobox, Checkbutton
from tkinter import filedialog
from PIL import ImageTk, Image
#from tkinter import Menu
window = Tk()
window.title('welcome to the best program in the world')
# define size of window
window.geometry('1000x800')
# create text label
lbl = Label(window , text='hello', font=('Arial Bold', 50))
lbl.grid(column=0, row=0)
txt = Entry(window, width=10)
txt.grid(column=1, row=0)
txt.focus() # set focus to entry widget such that you can write right away
def clicked():
string = 'You did it !! You typed: "{}" !'.format(txt.get())
lbl.configure(text=string)
# adding a button widget
btn = Button(window, text ='click me if you can', bg='orange', fg='green',
command = clicked)
btn.grid(column=2, row=0)
# combo widget
combo = Combobox(window)
combo['values'] = (1,2,3,4,5, 'Text')
combo.current(1) # set the selected item
combo.grid(column=0, row=1)
combo_string = combo.get()
# heckbutto widget
chk_state = BooleanVar() # also IntVar available
chk_state.set(True) #set check state,
chk = Checkbutton(window, text='Choose', var=chk_state)
chk.grid(column=0, row=2)
# add radio buttons
selected = IntVar()
rad1 = Radiobutton(window,text='First', value=1, variable=selected)
rad2 = Radiobutton(window,text='Second', value=2, variable=selected)
rad3 = Radiobutton(window,text='Third', value=3, variable=selected)
rad1.grid(column=0, row=3)
rad2.grid(column=1, row=3)
rad3.grid(column=2, row=3)
# create button for filedialog
def clicked_2():
# filedialog
global image_file
image_file = filedialog.askopenfilename(filetypes = (("Image files","*.jpg"),("all files","*.*")))
btn_2 = Button(window, text ='Choose file for processing', bg='purple', fg='green',
command = clicked_2)
btn_2.grid(column=0, row=4)
# add menü bar
menu = Menu(window)
new_item = Menu(menu)
new_item.add_command(label='Reset')
new_item.add_separator()
new_item.add_command(label='Exit')
menu.add_cascade(label='Options', menu=new_item)
window.config(menu=menu)
window.mainloop()
| true |
0e8a11c5b5a95929c533597d79ee4f3d037c13e0 | Python | caulagi/shakuni | /app/bets/models.py | UTF-8 | 2,196 | 2.984375 | 3 | [
"MIT"
] | permissive | """
bets.models
Models relating to bets placed
"""
import datetime
from mongoengine import *
from decimal import Decimal
from app.groups.models import Group
from app.users.models import User
from app.matches.models import Match
from app.project.config import CURRENCIES
class GroupMatch(Document):
"""Associate each match with the group"""
group = ReferenceField(Group)
match = ReferenceField(Match)
cutoff = DateTimeField()
created = DateTimeField(default=datetime.datetime.now())
meta = {
'indexes': ['group', 'match']
}
def __str__(self):
return "%s: %s" % (self.match, self.group)
def time_remaining(self):
return self.cutoff - datetime.datetime.now()
def amount_bet(self, user):
"""If the user has bet any amount on this match,
return the amount, or 0"""
try:
return Bet.objects.get(group_match = self, user=user).amount
except Bet.DoesNotExist:
return Decimal(0)
class Bet(Document):
"""Bet that a user has placed"""
OUTCOME = (
(-1, 'Team 2 wins'),
(0, 'Draw'),
(1, 'Team 1 wins'),
)
group_match = ReferenceField(GroupMatch)
user = ReferenceField(User)
amount = DecimalField()
currency = StringField(max_length=3, choices=CURRENCIES)
outcome = IntField(choices=OUTCOME)
created = DateTimeField(default=datetime.datetime.now())
meta = {
'indexes': ['user']
}
def __str__(self):
return "%s: %s" % (self.bet, self.user)
def pot(self):
bets = Bet.objects(group_match = self.group_match)
return sum(map(lambda x: x.amount, bets))
class WinnerBet(Document):
"""Bet placed at the beginning of the tournament on who
will win the worldcup"""
user = ReferenceField(User)
team = ReferenceField(User)
amount = DecimalField()
currency = StringField(max_length=3, choices=CURRENCIES)
cutoff = DateTimeField()
created = DateTimeField(default=datetime.datetime.now())
meta = {
'indexes': ['user', 'team']
}
def __str__(self):
return u"%s: %s" % (str(self.user), str(self.team))
| true |
ccd12b358ea255629733e3381c0f145191364cf8 | Python | DefFoxPy/Codigo-Facilito-Pygame | /introduccion/surface.py | UTF-8 | 270 | 2.90625 | 3 | [
"MIT"
] | permissive | import pygame
import sys
pygame.init()
width = 400
height = 500
surface = pygame.display.set_mode((width, height))
pygame.display.set_caption('Hola Mundo!')
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
| true |
d2b9b7c7f887669aaec7386d2300e360cab3b6b8 | Python | leesein123/python | /웹크롤링/다중페이지검색2.py | UTF-8 | 774 | 2.828125 | 3 | [] | no_license | # coding:utf-8
from bs4 import BeautifulSoup
import urllib.request
import re
for n in range(0,10):
data ='https://www.clien.net/service/board/park?&od=T31&po=' + str(n)
req = urllib.request.Request(data)
data = urllib.request.urlopen(req).read()
page = data.decode('utf-8', 'ignore')
soup = BeautifulSoup(page, 'html5lib')
list = soup.findAll('a', attrs={'class':'list-subject'})
for item in list:
try:
title = item.text
if (re.search('아이폰', title)):
print(title.strip())
print('https://www.clien.net' + item['href'])
except:
pass
| true |
f76af92060c8838bb92bba5e951339cb9445a399 | Python | HanKKK1515/PycharmProjects | /运算符.py | UTF-8 | 1,991 | 4.09375 | 4 | [] | no_license | # a = 10
# a +=20 # a=a+20
# print(a)
# print(3>4 or 4<3 and 1==1)
'''逻辑运算
and 并且的意思,左右两顿的值必须都是真,运算结果才是真
or 或者的意思,左右两端有一个是真的,结果就是真,全部都是假,结果才是假
not 非的意思,原来是假,现在是真,非真即假, 非假即真
and or not 同时存在,先算括号,然后算not,然后算and,最后算or
'''
# print(1 < 2 and 3< 4 or 1>2)
# print(1 > 2 and 3 < 4 or 4> 5 and 2 > 2 or 9 < 9) # false
# x or y 如果x==0 那么就是y 否则就是x
# print(1 or 2)
# print(2 or 3)
# print(0 or 3)
# print(0 or 4)
# and跟or是反着来的
# print(1 and 2) # 2
# print(2 and 0) # 0
# print(0 and 3) # 0
# print(0 and 4) # 0
# count = 1
# n = 66
# while count <= 3:
# num = input('猜一下是多少:')
# if int(num) > n:
# print('猜大了')
# elif int(num) < n:
# print('猜小了')
# else:
# print('猜对啦')
# break
# print('你已经猜了%d次了' % count)
# count = count + 1
# else:
# print('蠢货啊蠢货')
# 求1-2+3-4+5....99所有数的和
# sum = 0
# count = 1
# while count <100:
# if count%2 ==0: # 奇数
# sum = sum - count
# else:
# sum = sum + count
# count = count + 1
# print(sum) # 计算结果等于50
# 登录 三次机会
# count = 1
# while count <= 3:
# username = input('请输入你的用户名:')
# password = input('请输入密码')
# if username == 'alex' and password == 'sb':
# print('登录成功')
# break
# else:
# print('登录失败')
# print('还剩余%d次机会' % (3 - count))
# count = count + 1
# else:
# print('蠢货啊')
while True:
fen = input("请输入成绩:")
if fen == "q":
break
elif int(fen)<60:
print("成绩不合格")
elif int(fen) > 70 and int(fen)<80:
print("合格")
else:
print("ddd")
| true |
9bdf713b59c9e08f6daf8e99b1d05a5763ed6e06 | Python | bhkangw/Python | /python_dictionary_basics_assignment.py | UTF-8 | 1,004 | 4.84375 | 5 | [] | no_license | # Assignment: Making and Reading from Dictionaries
# Create a dictionary containing some information about yourself.
# The keys should include name, age, country of birth, favorite language.
# Write a function that will print something like the following as it executes:
# My name is Anna
# My age is 101
# My country of birth is The United States
# My favorite language is Python
# There are two steps to this process, building a dictionary and then gathering all the data from it.
# Write a function that can take in and print out any dictionary keys and values.
bio = {
"name": "Brian",
"age": 27,
"country of birth": "The United States",
"favorite language": "Python",
}
def give_bio(obj):
for key,data in obj.iteritems():
print "My", key, "is", data
give_bio(bio)
# for reference, how to extract only the keys or only the values
def give_bio(obj):
for key in obj.iterkeys():
print key
give_bio(bio)
def give_bio(obj):
for values in obj.itervalues():
print values
give_bio(bio) | true |
d2d44649c3baa3706df1d04de5994d2b56f6ee39 | Python | pushp1997/Energy-Efficient-Task-Scheduling | /hybri_pso_bfo.py | UTF-8 | 11,169 | 2.78125 | 3 | [] | no_license | import random
import csv
import matplotlib.pyplot as plt
import math
rows=[]
with open("tasks.csv", 'r') as csvfile:
csvreader=csv.reader(csvfile)
for row in csvreader:
rows.append(row)
class Tasks:
task_no=0
exec_time=0
a=0.9
b=0.8
def calculateMakespan(task_list):
makespan=0
for i in range(no_of_processor):
time=0
wait_time=0
for j in range(len(task_list[i])):
time+=task[task_list[i][j]-1].exec_time+wait_time
wait_time+=task[task_list[i][j]-1].exec_time
if(makespan<time):
makespan=time
return makespan
def calculateEnergy(task_list):
energy=0
max_time=0
for i in range(no_of_processor):
time=0
for j in range(len(task_list[i])):
time+=task[task_list[i][j]-1].exec_time
if(max_time<time):
max_time=time
for i in range(no_of_processor):
time=0
for j in range(len(task_list[i])):
time+=task[task_list[i][j]-1].exec_time
energy+=(time*0.0010)+((max_time-time)*0.0002)
return energy
def createParticle():
for i in range(no_of_particle):
particles.append([])
for j in range(no_of_task):
processor=random.randint(1,no_of_processor)
particles[i].append(processor)
def createTaskList(particle):
task_list=[]
for i in range(no_of_processor):
task_list.append([])
for j in range(no_of_task):
if(particle[j]==i+1):
task_list[i].append(j+1);
makespan=calculateMakespan(task_list)
energy=calculateEnergy(task_list)
cost=(a*makespan)+(b*energy)
return cost
def createTaskList2(particle):
task_list=[]
for i in range(no_of_processor):
task_list.append([])
for j in range(no_of_task):
if(particle[j]==i+1):
task_list[i].append(j+1);
makespan=calculateMakespan(task_list)
return makespan
def createTaskList1(particle):
task_list=[]
for i in range(no_of_processor):
task_list.append([])
for j in range(no_of_task):
if(particle[j]==i+1):
task_list[i].append(j+1);
energy=calculateEnergy(task_list)
return energy
personal_best=[]
global_best=[]
no_of_task=int(input("Enter no. of tasks : "))
task=[Tasks() for i in range(no_of_task)]
for i in range(no_of_task):
task[i].task_no=rows[i][0]
task[i].exec_time=int(rows[i][1])
no_of_processor=int(input("Enter no. of processors : "))
if(no_of_processor>no_of_task):
no_of_processor=no_of_task
no_of_particle=20
particles=[]
particle=[]
createParticle()
optimal_makespan=999999999999
velocity=[]
for i in range(no_of_particle):
personal_best.append([])
for j in range(no_of_task):
personal_best[i].append(particles[i][j])
for i in range(no_of_particle):
makespan=createTaskList(particles[i])
if(optimal_makespan>makespan):
pos=i
optimal_makespan=makespan
for i in range(no_of_task):
global_best.append(particles[pos][i])
for i in range(no_of_particle):
velocity.append([])
for j in range(no_of_task):
x=random.randint(-1,1)
velocity[i].append(x)
no_of_iteration=10
makespan_list=[]
iteration_list=[]
count=1
while(count<=no_of_iteration):
w=0.5
c1=1
c2=2
for i in range(no_of_particle):
for j in range(no_of_task):
r1=random.random()
r2=random.random()
vel_cognitive=c1*r1*(personal_best[i][j]-particles[i][j])
vel_social=c2*r2*(global_best[j]-particles[i][j])
velocity[i][j]=w*velocity[i][j]+vel_cognitive+vel_social
for i in range(no_of_particle):
for j in range(no_of_task):
particles[i][j]=round(particles[i][j]+velocity[i][j])
if(particles[i][j]<1):
particles[i][j]=1
if(particles[i][j]>no_of_processor):
particles[i][j]=no_of_processor
min_makespan=optimal_makespan*100
for i in range(no_of_particle):
makespan=createTaskList(particles[i])
if(makespan<min_makespan):
min_makespan=makespan
if(makespan<optimal_makespan):
for j in range(no_of_task):
global_best[j]=particles[i][j]
optimal_makespan=makespan
personal_best_makespan=createTaskList(personal_best[i])
if(personal_best_makespan>makespan):
for j in range(no_of_task):
personal_best[i][j]=particles[i][j]
makespan_list.append(min_makespan/60)
iteration_list.append(count)
count=count+1
print("\n\nOptimal Task Assignment for PSO :\n\nTask\tProccessor\tExecution Time (in sec)")
for i in range(no_of_task):
print(" ",i+1,"\t ",global_best[i],"\t\t ",task[i].exec_time)
print("\nOptimal Makespan using PSO = ",round((createTaskList2(global_best)/60),2),"min(s)")
print("Optimal Energy using PSO = ",round(createTaskList1(global_best),2),"units")
plt.plot(iteration_list,makespan_list)
plt.xlabel('Iterations')
plt.ylabel('Makespan + Energy ')
plt.axis([1,no_of_iteration,0,optimal_makespan*2.5/60])
plt.show()
for i in range(no_of_particle):
for j in range(no_of_task):
particles[i][j]=personal_best[i][j]
no_of_bacteria=20
no_of_chemotactics=10
swim_length=4
no_of_reproductions=4
no_of_dispersals=2
step_size=1.45
probability_dispersal=0.25
d_attractant=-0.1
w_attractant=-0.2
h_repellant=0.1
w_repellant=-10
J_last=[]
J_health=[]
J=[]
makespan_list=[]
chemotactics_list=[]
count=1
def interact(x):
value=0
for i in range(no_of_bacteria):
for j in range(no_of_task):
value+=particles[x][j]-particles[i][j]
value=value**2
return value
def interaction(x):
attr=0
repel=0
for i in range(no_of_bacteria):
if(i!=x):
attr+=d_attractant*math.exp(w_attractant*interact(x))
repel+=h_repellant*math.exp(w_repellant*interact(x))
return attr+repel
for i in range(no_of_bacteria):
J_last.append(0)
J.append(0)
J_health.append(0)
def generateDirection():
direction=[]
for i in range(no_of_task):
x=random.randint(-1,1)
direction.append(x)
return direction
for i in range(no_of_bacteria):
J_health[i]=createTaskList(particles[i])
for l in range(no_of_dispersals):
for k in range(no_of_reproductions):
for j in range(no_of_chemotactics):
for i in range(no_of_bacteria):
J[i]=createTaskList(particles[i])
J_last[i]=J[i]
direction=generateDirection()
for m in range(no_of_task):
particles[i][m]=round(particles[i][m]+(step_size*direction[m]))
if(particles[i][m]<1):
particles[i][m]=1
if(particles[i][m]>no_of_processor):
particles[i][m]=no_of_processor
J[i]=createTaskList(particles[i])
if(J[i]<optimal_makespan):
optimal_makespan=J[i]
for m in range(no_of_task):
global_best[m]=particles[i][m]
personal_best[i][m]=particles[i][m]
if(J[i]<=J_last[i]):
J_last[i]=J[i]
J_health[i]+=J_last[i]
for m in range(no_of_task):
personal_best[i][m]=particles[i][m]
swim_count=0
for m in range(no_of_task):
particles[i][m]=round(particles[i][m]+(step_size*direction[m]))
if(particles[i][m]<1):
particles[i][m]=1
if(particles[i][m]>no_of_processor):
particles[i][m]=no_of_processor
while(swim_count<swim_length):
swim_count+=1
J[i]=createTaskList(particles[i])
if(J[i]<optimal_makespan):
for m in range(no_of_task):
global_best[m]=particles[i][m]
personal_best[i][m]=particles[i][m]
if(J[i]<=J_last[i]):
J_last[i]=J[i]
J_health[i]+=J_last[i]
for m in range(no_of_task):
personal_best[i][m]=particles[i][m]
for m in range(no_of_task):
particles[i][m]=round(particles[i][m]+(step_size*direction[m]))
if(particles[i][m]<1):
particles[i][m]=1
if(particles[i][m]>no_of_processor):
particles[i][m]=no_of_processor
makespan_list.append(createTaskList(global_best)/60)
chemotactics_list.append(count)
count+=1
for m in range(no_of_bacteria-1):
for n in range(no_of_bacteria-m-1):
if(J_health[n]>J_health[n+1]):
temp=J_health[n]
J_health[n]=J_health[n+1]
J_health[n+1]=temp
for x in range(no_of_task):
temp=particles[n][x]
particles[n][x]=particles[n+1][x]
kill=int(no_of_bacteria/2)
for m in range(kill):
for x in range(no_of_task):
particles[m+kill][x]=particles[m][x]
dispersal=int(no_of_bacteria*probability_dispersal)
for x in range(no_of_bacteria):
if(x%dispersal==0):
direction=generateDirection()
for m in range(no_of_task):
particles[x][m]=round(particles[x][m]+(step_size*direction[m]))
if(particles[x][m]<1):
particles[x][m]=1
if(particles[x][m]>no_of_processor):
particles[x][m]=no_of_processor
print("\n\nOptimal Task Assignment for Hybrid PSO-BFO :\n\nTask\tProccessor\tExecution Time (in sec)")
for i in range(no_of_task):
print(" ",i+1,"\t ",global_best[i],"\t\t ",task[i].exec_time)
print("\nOptimal Makespan using Hybrid PSO-BFO = ",round((createTaskList2(global_best)/60),2),"min(s)")
print("Optimal Energy using Hybrid PSO-BFO = ",round(createTaskList1(global_best),2),"units")
plt.plot(chemotactics_list,makespan_list)
plt.xlabel('Chemotactic Steps')
plt.ylabel('Makespan + Energy ')
plt.axis([1,count,0,optimal_makespan/30])
plt.show()
| true |
651da363085302e31fb1fbc011e2f31e0e29deca | Python | 00dbgpdnjs/rpa | /2_desktop/3_mouse_action.py | UTF-8 | 1,321 | 3.5625 | 4 | [] | no_license | import pyautogui
# pyautogui.sleep(3) # To move the mouse to the place you want ; To print the pos of the cursor of the place you want with the code just below ; ex) pos of file tap to click
# print(pyautogui.position())
# pyautogui.click(64, 17, duration=1) # Move to the coordinates [file tap] for 1s and click
# pyautogui.click() = pyautogui.mouseDown() + pyautogui.mouseUp() ; Can drag and drop or paint by using two codes seperately
# Two codes are same
# pyautogui.doubleClick()
# pyautogui.click(clicks=2)
# pyautogui.sleep(3) # Open mspaint
# pyautogui.click(clicks=500) # You can move the mouse as this code is run
# Paint a straight line on mspaint
# pyautogui.moveTo(200, 200)
# pyautogui.mouseDown()
# pyautogui.moveTo(300, 300)
# pyautogui.mouseUp()
# pyautogui.rightClick()
# pyautogui.middleClick()
# pyautogui.scroll(300) # 위로 +300
pyautogui.sleep(3) # Open a memo pad and put the cursor on top of the notepad.
print(pyautogui.position())
pyautogui.moveTo(1357, 65) # put the result of the code just above
# pyautogui.drag(100, 0) # +100
pyautogui.drag(100, 0, duration=0.25) # 컴퓨터가 동작 보다 빨라서 보통 0.25를 줌
# pyautogui.dragTo(1514, 349, duration=0.25) # Instead of the code just above, to move to the absolute coordinates.
| true |
a290410537507c8bf38abef2cb24581d637c0f21 | Python | NAMazitelli/CHIKKORITTEN_7.2 | /eb_turno.py | UTF-8 | 1,031 | 2.734375 | 3 | [] | no_license | #! /usr/bin/env python
# Clase Turno, Action, Movimiento, AutoAtaque
# Copyright (C) 2012 EGGBREAKER <eggbreaker@live.com.ar>
from eb_lectormapa import Mapa
class Turno():
ActionList = []
def __init__(self):
self.ActionList = []
def getLastAction(self):
if len(self.ActionList) == 0:
return None
return self.ActionList[-1].__class__.__name__
def addAction(self, Action):
self.ActionList.append(Action)
class Action():
#Target = None
Forced = False
def __init__(self, Forced = False):
self.Forced = Forced
class Movimiento(Action):
MovList = []
def __init__(self, Pos, Forced = False):
self.Forced = Forced
self.MovList.append(Pos)
def addPos(self, Pos):
self.MovList.append(Pos)
def isFirstMove(self):
return len(self.MovList) == 0
class AutoAtaque(Action):
def __init__(self, Char, Target, Forced = False):
self.Target = Target
self.Forced = Forced
| true |