uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
0cdb80cd77c39d262671d274
train
function
def drawStats(Htemps, Hbest, parametersSTR, titleName): fig2 = plt.figure(2,figsize=(9,6)) plt.subplot(1,1,1) # plt.semilogx(Htemps, Hbest, label=parametersSTR) plt.plot(Htemps, Hbest, label=parametersSTR) #plt.semilogy plt.title(titleName) plt.xlabel('Iterations') plt.ylabel('Distance') ...
def drawStats(Htemps, Hbest, parametersSTR, titleName):
fig2 = plt.figure(2,figsize=(9,6)) plt.subplot(1,1,1) # plt.semilogx(Htemps, Hbest, label=parametersSTR) plt.plot(Htemps, Hbest, label=parametersSTR) #plt.semilogy plt.title(titleName) plt.xlabel('Iterations') plt.ylabel('Distance') plt.legend()
PolArea)*100,1), iteration) ) plt.draw() plt.pause(pause) def dispRes(best_route, best_dist): print("Pos = {}".format(best_route)) print("Area = {}".format(best_dist)) def drawStats(Htemps, Hbest, parametersSTR, titleName):
64
64
102
15
49
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
drawStats
drawStats
71
79
71
71
748fdaea6f0fb54beceb2a4ecc73fbb95d377b4f
bigcode/the-stack
train
0d567f75b2fe8cac86f7c388
train
function
def aire(p1): l= length(p1[0],p1[1]) b= breath(p1[1],p1[2]) return l*b
def aire(p1):
l= length(p1[0],p1[1]) b= breath(p1[1],p1[2]) return l*b
D, pyclipper.PFT_EVENODD) return (clip!=[]) and (len(clip[0])==len(rect)) and all(list(map(lambda e:list(e) in clip[0], rect))) except pyclipper.ClipperException: return False def aire(p1):
64
64
38
5
58
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
aire
aire
157
160
157
157
2f6008b16b300307cbb3293029ad07fb2d0b7be8
bigcode/the-stack
train
88714999936096a613ccd1ca
train
function
def poly2list(polygone): polygonefig = list(polygone) polygonefig.append(polygonefig[0]) return polygonefig
def poly2list(polygone):
polygonefig = list(polygone) polygonefig.append(polygonefig[0]) return polygonefig
) =( ((50,50),(50,400),(220,310),(220,170),(330,170),(330,480),(450,480),(450,50)) , 116650) anglemin = 0.01 anglemax = 89.99 def poly2list(polygone):
64
64
39
8
55
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
poly2list
poly2list
40
43
40
40
a5241fca8de4faabadade486358399056897448e
bigcode/the-stack
train
8f5d5a9da43a5dc1401d14ac
train
function
def times(parameter,tu_velocity): new_velocity=[parameter*element for element in tu_velocity] return new_velocity
def times(parameter,tu_velocity):
new_velocity=[parameter*element for element in tu_velocity] return new_velocity
verifcontrainte(rect, polygone) if boolOK==True: nv['vit'] = final_velocity nv['pos'] = pos nv['fit'] = aire(post2rect(pos)) return nv else: return nv def times(parameter,tu_velocity):
64
64
25
7
56
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
times
times
207
209
207
207
7736327d15c9d3e8dcc005ea7f97bf0659e2b017
bigcode/the-stack
train
73fa343d4654de504ad8ca29
train
function
def breath(b,c): return abs(b[0]-c[0])
def breath(b,c):
return abs(b[0]-c[0])
: return False def aire(p1): l= length(p1[0],p1[1]) b= breath(p1[1],p1[2]) return l*b def length(a,b): return abs(a[1]-b[1]) def breath(b,c):
64
64
16
5
59
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
breath
breath
165
166
165
165
bb11d35b42072a477266463c4303b8b3d2af79b7
bigcode/the-stack
train
6d4f11be48eab47e87cbd1cc
train
function
def update(particle, bestParticle): nv = dict(particle) if (particle["fit"] > particle["bestfit"]): nv['bestpos'] = particle["pos"][:] nv['bestfit'] = particle["fit"] nv['bestvois'] = bestParticle["bestpos"][:] return nv
def update(particle, bestParticle):
nv = dict(particle) if (particle["fit"] > particle["bestfit"]): nv['bestpos'] = particle["pos"][:] nv['bestfit'] = particle["fit"] nv['bestvois'] = bestParticle["bestpos"][:] return nv
(lambda acc, e: bestPartic(acc,e),population[1:],population[0])) def bestPartic(p1,p2): if (p1["fit"] > p2["fit"]): return p1 else: return p2 def update(particle, bestParticle):
64
64
73
8
55
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
update
update
177
183
177
177
742fecd9f35edfa7eba7574d834e4418cb661f7e
bigcode/the-stack
train
2bd91261cc7db4416173a47b
train
function
def metropolis(ch1,dist1,ch2,dist2,T): global best_route, best_dist, x, y delta = dist1 - dist2 if delta <= 0: if dist1 <= best['fit']: best['bestfit'] = dist1 best['fit'] = dist1 best['bestpos'] = ch1[:] best['pos'] = ch1[:] return (ch1, dist1...
def metropolis(ch1,dist1,ch2,dist2,T):
global best_route, best_dist, x, y delta = dist1 - dist2 if delta <= 0: if dist1 <= best['fit']: best['bestfit'] = dist1 best['fit'] = dist1 best['bestpos'] = ch1[:] best['pos'] = ch1[:] return (ch1, dist1) else: if random.uniform(0...
(round(vel1[i] - vel2[i])) return vel def add_list(v1,v2): new=[] for i in range(len(v1)): new.append(v1[i]+v2[i]) return new def metropolis(ch1,dist1,ch2,dist2,T):
64
64
139
14
49
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
metropolis
metropolis
223
237
223
223
84966b9e3ef1c7598e96a62f0f03a39487193c14
bigcode/the-stack
train
6cda6dd152b7352e1b00aea0
train
function
def main_PSO(Nb_Cycles, Nb_Indiv, psi, c1, c2 ): global best Htemps = [] Hbest = [] pos = initPop(Nb_Indiv,polygone) best = getBest(pos) best_cycle = best polygonefig = poly2list(polygone) k=0 z=0 no_iteration=0 ltaboo=10 best_of_best=[0] best_of_best[0]=best.copy() ...
def main_PSO(Nb_Cycles, Nb_Indiv, psi, c1, c2 ):
global best Htemps = [] Hbest = [] pos = initPop(Nb_Indiv,polygone) best = getBest(pos) best_cycle = best polygonefig = poly2list(polygone) k=0 z=0 no_iteration=0 ltaboo=10 best_of_best=[0] best_of_best[0]=best.copy() for z in range(Nb_Cycles): pos=[updat...
(v1[i]+v2[i]) return new def metropolis(ch1,dist1,ch2,dist2,T): global best_route, best_dist, x, y delta = dist1 - dist2 if delta <= 0: if dist1 <= best['fit']: best['bestfit'] = dist1 best['fit'] = dist1 best['bestpos'] = ch1[:] best['pos'] = ch1...
173
173
579
22
151
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
main_PSO
main_PSO
239
281
239
239
6a52b2c1b8ba77888776766ced298bf44ed7db1d
bigcode/the-stack
train
e4327a288575157c53a67603
train
function
def initPop(nb,polygone): return [initUn(polygone) for i in range(nb)]
def initPop(nb,polygone):
return [initUn(polygone) for i in range(nb)]
[1]),min(e[1],acc[2]),max(e[1],acc[3])),lpoly[1:],(lpoly[0][0],lpoly[0][0],lpoly[0][1],lpoly[0][1])) def initPop(nb,polygone):
64
64
23
9
55
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
initPop
initPop
116
117
116
116
c8339128fd79093c2fb8246123676699d3880cf8
bigcode/the-stack
train
908bf418103ecfe8136d93f3
train
function
def dispRes(best_route, best_dist): print("Pos = {}".format(best_route)) print("Area = {}".format(best_dist))
def dispRes(best_route, best_dist):
print("Pos = {}".format(best_route)) print("Area = {}".format(best_dist))
Aire: {} Aire/Max: {}% Iteration: {}".format(round(aire(rectfig[:-1]), 2), round((aire(rectfig[:-1])/maxPolArea)*100,1), iteration) ) plt.draw() plt.pause(pause) def dispRes(best_route, best_dist):
64
64
29
9
55
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
dispRes
dispRes
67
69
67
67
50cf2c0cf5e41ab93b7729b36f5427f3ffbf554d
bigcode/the-stack
train
402e9b7182f480c070aa606d
train
function
def getBornes(polygone): lpoly = list(polygone) return reduce(lambda acc,e: (min(e[0],acc[0]),max(e[0],acc[1]),min(e[1],acc[2]),max(e[1],acc[3])),lpoly[1:],(lpoly[0][0],lpoly[0][0],lpoly[0][1],lpoly[0][1]))
def getBornes(polygone):
lpoly = list(polygone) return reduce(lambda acc,e: (min(e[0],acc[0]),max(e[0],acc[1]),min(e[1],acc[2]),max(e[1],acc[3])),lpoly[1:],(lpoly[0][0],lpoly[0][0],lpoly[0][1],lpoly[0][1]))
j = (i + 1) % n area += corners[i][0] * corners[j][1] area -= corners[j][0] * corners[i][1] area = abs(area) / 2.0 return area def getBornes(polygone):
64
64
93
8
55
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
getBornes
getBornes
112
114
112
112
ed4abe18681bc7c13960a8bc311459f361001350
bigcode/the-stack
train
beac640302740004e8118e10
train
function
def dessine(polyfig, rectfig , iteration, pause=0.01): global canv, codes canv.clear() codes = [Path.MOVETO] for i in range(len(polyfig) - 2): codes.append(Path.LINETO) codes.append(Path.CLOSEPOLY) path = Path(polyfig, codes) patch = patches.PathPatch(path, facecolor='orange', lw=2) ...
def dessine(polyfig, rectfig , iteration, pause=0.01):
global canv, codes canv.clear() codes = [Path.MOVETO] for i in range(len(polyfig) - 2): codes.append(Path.LINETO) codes.append(Path.CLOSEPOLY) path = Path(polyfig, codes) patch = patches.PathPatch(path, facecolor='orange', lw=2) canv.add_patch(patch) canv.autoscale_view() ...
min = 0.01 anglemax = 89.99 def poly2list(polygone): polygonefig = list(polygone) polygonefig.append(polygonefig[0]) return polygonefig def dessine(polyfig, rectfig , iteration, pause=0.01):
71
71
237
17
53
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
dessine
dessine
45
65
45
45
68e224517a7798ddeac30494bf31537894dc9d31
bigcode/the-stack
train
51601319ebb51358f60d323a
train
function
def drawBoxPlot(BoxPlotData, xValues, xLabel, titleName): fig3 = plt.figure(3,figsize=(6,6)) plt.subplot(1,1,1) sns.boxplot( x=xValues, y=BoxPlotData, palette="Blues") # plt.boxplot(BoxPlotData) # plt.xticks(range(1, len(BoxPlotData)+1), xLables) plt.title(titleName) plt.xlabel(xLabel) ...
def drawBoxPlot(BoxPlotData, xValues, xLabel, titleName):
fig3 = plt.figure(3,figsize=(6,6)) plt.subplot(1,1,1) sns.boxplot( x=xValues, y=BoxPlotData, palette="Blues") # plt.boxplot(BoxPlotData) # plt.xticks(range(1, len(BoxPlotData)+1), xLables) plt.title(titleName) plt.xlabel(xLabel) plt.ylabel('Percentage Area Best Rectangule') plt.legen...
parametersSTR) plt.plot(Htemps, Hbest, label=parametersSTR) #plt.semilogy plt.title(titleName) plt.xlabel('Iterations') plt.ylabel('Distance') plt.legend() def drawBoxPlot(BoxPlotData, xValues, xLabel, titleName):
64
64
120
18
46
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
drawBoxPlot
drawBoxPlot
81
90
81
81
411af6c6ccab688a13a81eda2f777f7a5d3ab9fd
bigcode/the-stack
train
94057dde9a729e16e449755b
train
function
def bestPartic(p1,p2): if (p1["fit"] > p2["fit"]): return p1 else: return p2
def bestPartic(p1,p2):
if (p1["fit"] > p2["fit"]): return p1 else: return p2
return abs(a[1]-b[1]) def breath(b,c): return abs(b[0]-c[0]) def getBest(population): return dict(reduce(lambda acc, e: bestPartic(acc,e),population[1:],population[0])) def bestPartic(p1,p2):
64
64
37
9
55
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
bestPartic
bestPartic
171
175
171
171
9e65d02b7d3e413cc729b606dc1b6196872030bf
bigcode/the-stack
train
074271d8006c77aa18596796
train
function
def PolygonArea(corners): n = len(corners) # of corners area = 0.0 for i in range(n): j = (i + 1) % n area += corners[i][0] * corners[j][1] area -= corners[j][0] * corners[i][1] area = abs(area) / 2.0 return area
def PolygonArea(corners):
n = len(corners) # of corners area = 0.0 for i in range(n): j = (i + 1) % n area += corners[i][0] * corners[j][1] area -= corners[j][0] * corners[i][1] area = abs(area) / 2.0 return area
temps, Hbest, label=parametersSTR) plt.plot(Nb_Cycles_LST, HComputationTime) #plt.semilogy plt.title(titleName) plt.xlabel('Iterations') plt.ylabel('Computation Time (s)') plt.legend() def PolygonArea(corners):
64
64
88
6
58
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
PolygonArea
PolygonArea
102
110
102
102
2fc991119b86645f611d3e002733f730bf1ac1c7
bigcode/the-stack
train
9a720df722178750bb6a7eef
train
function
def initUn(polygone): global xmin,xmax,ymin,ymax; anglemin = 1 anglemax = 89 boolOK = False while boolOK==False: xo=random.uniform(xmin,xmax) # centre point x coord yo=random.uniform(ymin,ymax) # cent...
def initUn(polygone):
global xmin,xmax,ymin,ymax; anglemin = 1 anglemax = 89 boolOK = False while boolOK==False: xo=random.uniform(xmin,xmax) # centre point x coord yo=random.uniform(ymin,ymax) # centre point y coord ...
[0]),max(e[0],acc[1]),min(e[1],acc[2]),max(e[1],acc[3])),lpoly[1:],(lpoly[0][0],lpoly[0][0],lpoly[0][1],lpoly[0][1])) def initPop(nb,polygone): return [initUn(polygone) for i in range(nb)] def initUn(polygone):
94
94
316
7
87
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
initUn
initUn
119
134
119
119
f9f639efcffc9eb8e40f88e14bea4c49ffb0a111
bigcode/the-stack
train
798eceefe0110a3370c77bd1
train
function
def minus(vel1,vel2): vel = [] for i in range(len(vel1)): vel.append(round(vel1[i] - vel2[i])) return vel
def minus(vel1,vel2):
vel = [] for i in range(len(vel1)): vel.append(round(vel1[i] - vel2[i])) return vel
nv['pos'] = pos nv['fit'] = aire(post2rect(pos)) return nv else: return nv def times(parameter,tu_velocity): new_velocity=[parameter*element for element in tu_velocity] return new_velocity def minus(vel1,vel2):
64
64
41
9
54
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
minus
minus
211
215
211
211
5ae116e89ef74fcc57439e374c294bcfe2c6cb6b
bigcode/the-stack
train
34834af85ef151c432a7f6ec
train
function
def post2rect(pos): xa, ya = pos[0], pos[1] # point A xo, yo = pos[2], pos[3] # point o angle = pos[-1] # angle in degree alpha = pi * angle / ...
def post2rect(pos):
xa, ya = pos[0], pos[1] # point A xo, yo = pos[2], pos[3] # point o angle = pos[-1] # angle in degree alpha = pi * angle / 180 ...
rect formed return {'vit': [0,0,0,0,0], 'pos': pos, 'fit': ev, 'bestfit': ev, 'bestpos': pos, 'bestvois': [0,0,0,0,0]} def post2rect(pos):
63
64
205
6
57
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
post2rect
post2rect
136
145
136
136
f2c30cc38ed29980ab72a7a64874b7d1548e2686
bigcode/the-stack
train
776592dff6945b15287c58be
train
function
def verifcontrainte(rect, polygone): try: pc = pyclipper.Pyclipper() pc.AddPath(polygone, pyclipper.PT_SUBJECT, True) pc.AddPath(rect, pyclipper.PT_CLIP, True) clip = pc.Execute(pyclipper.CT_INTERSECTION, pyclipper.PFT_EVENODD, pyclipper.PFT_EVENODD) return (clip!=[]) and (len(clip[0])==len(rect)) and all(li...
def verifcontrainte(rect, polygone):
try: pc = pyclipper.Pyclipper() pc.AddPath(polygone, pyclipper.PT_SUBJECT, True) pc.AddPath(rect, pyclipper.PT_CLIP, True) clip = pc.Execute(pyclipper.CT_INTERSECTION, pyclipper.PFT_EVENODD, pyclipper.PFT_EVENODD) return (clip!=[]) and (len(clip[0])==len(rect)) and all(list(map(lambda e:list(e) in clip[0], r...
- xd, 2*yo - yd # generating point b return ((round(xa),round(ya)),(round(xb),round(yb)),(round(xc),round(yc)),(round(xd),round(yd))) def verifcontrainte(rect, polygone):
64
64
139
11
53
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
verifcontrainte
verifcontrainte
147
155
147
147
a8ae0558dc5b3019f05ceb9622356004af998d0f
bigcode/the-stack
train
bb85f122f4a80498c0b9a137
train
function
def drawTimeVS(Nb_Cycles_LST, HComputationTime, titleName): fig4 = plt.figure(4,figsize=(9,6)) plt.subplot(1,1,1) # plt.semilogx(Htemps, Hbest, label=parametersSTR) plt.plot(Nb_Cycles_LST, HComputationTime) #plt.semilogy plt.title(titleName) plt.xlabel('Iterations') plt.ylabel('Computation...
def drawTimeVS(Nb_Cycles_LST, HComputationTime, titleName):
fig4 = plt.figure(4,figsize=(9,6)) plt.subplot(1,1,1) # plt.semilogx(Htemps, Hbest, label=parametersSTR) plt.plot(Nb_Cycles_LST, HComputationTime) #plt.semilogy plt.title(titleName) plt.xlabel('Iterations') plt.ylabel('Computation Time (s)') plt.legend()
plt.xticks(range(1, len(BoxPlotData)+1), xLables) plt.title(titleName) plt.xlabel(xLabel) plt.ylabel('Percentage Area Best Rectangule') plt.legend() def drawTimeVS(Nb_Cycles_LST, HComputationTime, titleName):
64
64
111
19
45
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
drawTimeVS
drawTimeVS
92
100
92
92
de20780fd017e33e01b7bb5b6b60a0455fb7aebb
bigcode/the-stack
train
138d989ee06093449be8a6f6
train
function
def getBest(population): return dict(reduce(lambda acc, e: bestPartic(acc,e),population[1:],population[0]))
def getBest(population):
return dict(reduce(lambda acc, e: bestPartic(acc,e),population[1:],population[0]))
0],p1[1]) b= breath(p1[1],p1[2]) return l*b def length(a,b): return abs(a[1]-b[1]) def breath(b,c): return abs(b[0]-c[0]) def getBest(population):
64
64
29
6
58
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
getBest
getBest
168
169
168
168
8df5701d7491e813eabea95bc53b31a8a404312d
bigcode/the-stack
train
da07dec953f9cfe9eb842665
train
function
def add_list(v1,v2): new=[] for i in range(len(v1)): new.append(v1[i]+v2[i]) return new
def add_list(v1,v2):
new=[] for i in range(len(v1)): new.append(v1[i]+v2[i]) return new
=[parameter*element for element in tu_velocity] return new_velocity def minus(vel1,vel2): vel = [] for i in range(len(vel1)): vel.append(round(vel1[i] - vel2[i])) return vel def add_list(v1,v2):
64
64
35
8
55
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
add_list
add_list
217
221
217
217
1c328cbc0900daa8158d02d43cb46fcd3b7038b6
bigcode/the-stack
train
9e580bfbb6bdd58cebd2f142
train
function
def move(particle,psi,c1,c2): nv= dict(particle) tu_velocity1= particle['vit'] tu_velocity1= times(psi,tu_velocity1) tu_loc_velocity= minus(particle['bestpos'],particle['pos']) tu_loc_velocity= times(c1*random.uniform(0,1),tu_loc_velocity) tu_gro_velocity= minus(particle['bestvois'],particle['po...
def move(particle,psi,c1,c2):
nv= dict(particle) tu_velocity1= particle['vit'] tu_velocity1= times(psi,tu_velocity1) tu_loc_velocity= minus(particle['bestpos'],particle['pos']) tu_loc_velocity= times(c1*random.uniform(0,1),tu_loc_velocity) tu_gro_velocity= minus(particle['bestvois'],particle['pos']) tu_gro_velocity= time...
Particle): nv = dict(particle) if (particle["fit"] > particle["bestfit"]): nv['bestpos'] = particle["pos"][:] nv['bestfit'] = particle["fit"] nv['bestvois'] = bestParticle["bestpos"][:] return nv def move(particle,psi,c1,c2):
78
78
263
11
66
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
move
move
185
205
185
185
c6348ac04eccf6aefad21d12e27d2529248bc571
bigcode/the-stack
train
bdd8aa6264964a4bab9c663b
train
function
def length(a,b): return abs(a[1]-b[1])
def length(a,b):
return abs(a[1]-b[1])
) in clip[0], rect))) except pyclipper.ClipperException: return False def aire(p1): l= length(p1[0],p1[1]) b= breath(p1[1],p1[2]) return l*b def length(a,b):
64
64
16
5
58
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
surface_PSO_TuckeyBOX.py
Python
length
length
162
163
162
162
272380adb1b7116cd9c4fd661e22bce07dfc0490
bigcode/the-stack
train
3f0ba8e76e1d6c2a5362f2ee
train
function
def find_parent(x): if parent[x] != x: parent[x] = find_parent(parent[x]) return parent[x]
def find_parent(x):
if parent[x] != x: parent[x] = find_parent(parent[x]) return parent[x]
9a import sys def input(): return sys.stdin.readline().rstrip() def union(x,y): x = find_parent(x) y = find_parent(y) if x < y: parent[y] = x else: parent[x] = y def find_parent(x):
64
64
28
5
58
jungyoonoh/baekjoon-1
solution/disjoint_set/1976/main.py
Python
find_parent
find_parent
18
21
18
18
1ebaa61a229a3974641380e8d5cdb405aa77c040
bigcode/the-stack
train
feb05b3c43fdc7e26fab6974
train
function
def union(x,y): x = find_parent(x) y = find_parent(y) if x < y: parent[y] = x else: parent[x] = y
def union(x,y):
x = find_parent(x) y = find_parent(y) if x < y: parent[y] = x else: parent[x] = y
ored by : gusdn3477 # Co-authored by : - # Link : http://boj.kr/a5ab5f0d45ed4e5584f0444987ba6c9a import sys def input(): return sys.stdin.readline().rstrip() def union(x,y):
64
64
42
5
59
jungyoonoh/baekjoon-1
solution/disjoint_set/1976/main.py
Python
union
union
10
16
10
10
df7e19c2f5d3b66d6eeebd94ef09aeacd17f1df6
bigcode/the-stack
train
85e7512fbe7f2c6515f13dd1
train
function
def input(): return sys.stdin.readline().rstrip()
def input():
return sys.stdin.readline().rstrip()
# Authored by : gusdn3477 # Co-authored by : - # Link : http://boj.kr/a5ab5f0d45ed4e5584f0444987ba6c9a import sys def input():
53
64
11
3
49
jungyoonoh/baekjoon-1
solution/disjoint_set/1976/main.py
Python
input
input
7
8
7
7
16057458236da0a05bb230d8bec20f84a03f1dac
bigcode/the-stack
train
17685b8e7f3536c94d0f20d8
train
class
class Credentials: def __init__(self, file_loc: str) -> None: """Read config file and parse it into a dictionary""" conf = configparser.RawConfigParser() conf.read(file_loc) self.config = conf self.file_loc = file_loc def get_config(self) -> configparser.RawConfi...
class Credentials:
def __init__(self, file_loc: str) -> None: """Read config file and parse it into a dictionary""" conf = configparser.RawConfigParser() conf.read(file_loc) self.config = conf self.file_loc = file_loc def get_config(self) -> configparser.RawConfigParser: ""...
import configparser from typing import Dict class Credentials:
12
64
210
3
8
mustartt/pixiv-bot
credentials.py
Python
Credentials
Credentials
4
29
4
4
53bf598222f166676fa3a95a603696e453eb032b
bigcode/the-stack
train
01b8c95445f10dc44a4b801a
train
class
class coot_molprobity_todo_list_gui(coot_extension_gui): data_keys = [ "rama", "rota", "cbeta", "probe" ] data_titles = { "rama" : "Ramachandran outliers", "rota" : "Rotamer outliers", "cbeta" : "C-beta outliers", "probe" : "Severe clashes" } data_names = { ...
class coot_molprobity_todo_list_gui(coot_extension_gui):
data_keys = [ "rama", "rota", "cbeta", "probe" ] data_titles = { "rama" : "Ramachandran outliers", "rota" : "Rotamer outliers", "cbeta" : "C-beta outliers", "probe" : "Severe clashes" } data_names = { "rama" : ["Chain", "Residue", "Name", "Score"], ...
def confirm_data(self, data): for data_key in self.data_keys : outlier_list = data.get(data_key) if outlier_list is not None and len(outlier_list) > 0 : return True return False def create_property_lists(self, data): import gtk for data_key in self.data_keys : outlier_list ...
231
231
773
16
214
dperl-sol/cctbx_project
cootbx/validation_lists.py
Python
coot_molprobity_todo_list_gui
coot_molprobity_todo_list_gui
65
131
65
65
4490fb41c85201f327eb9e32895ea58fa73a6bd2
bigcode/the-stack
train
56d499ba500ddd32c4aff160
train
function
def load_pkl(file_name): pkl = open(file_name, "rb") data = pickle.load(pkl) pkl.close() return data
def load_pkl(file_name):
pkl = open(file_name, "rb") data = pickle.load(pkl) pkl.close() return data
sys.stdout.flush() set_display_generic_object(object_number, 0) else : set_display_generic_object(object_number, 1) else : sys.stdout.flush() for object_number in range(n_objects): set_display_generic_object(object_number, 0) def load_pkl(file_name):
64
64
35
7
57
dperl-sol/cctbx_project
cootbx/validation_lists.py
Python
load_pkl
load_pkl
203
207
203
203
1455c64ff7d85f42b6099b7dd10e5a85ebcedb33
bigcode/the-stack
train
fd6c689405daae0b26b26459
train
class
class coot_extension_gui(object): def __init__(self, title): import gtk self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) scrolled_win = gtk.ScrolledWindow() self.outside_vbox = gtk.VBox(False, 2) self.inside_vbox = gtk.VBox(False, 0) self.window.set_title(title) self.inside_vbox.set_border_wi...
class coot_extension_gui(object):
def __init__(self, title): import gtk self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) scrolled_win = gtk.ScrolledWindow() self.outside_vbox = gtk.VBox(False, 2) self.inside_vbox = gtk.VBox(False, 0) self.window.set_title(title) self.inside_vbox.set_border_width(0) self.window.add(self.ou...
from __future__ import absolute_import, division, print_function from six.moves import cPickle as pickle from six.moves import range try : import gobject except ImportError : gobject = None import sys class coot_extension_gui(object):
57
142
475
7
49
dperl-sol/cctbx_project
cootbx/validation_lists.py
Python
coot_extension_gui
coot_extension_gui
11
62
11
11
68e90a7cec81f32f45a1cd2999a84e1a369a683f
bigcode/the-stack
train
96978cb16407400f5ebfa644
train
class
class rsc_todo_list_gui(coot_extension_gui): data_keys = ["by_res", "by_atom"] data_titles = ["Real-space correlation by residue", "Real-space correlation by atom"] data_names = {} data_types = {}
class rsc_todo_list_gui(coot_extension_gui):
data_keys = ["by_res", "by_atom"] data_titles = ["Real-space correlation by residue", "Real-space correlation by atom"] data_names = {} data_types = {}
(show_dots, overlaps_only) def toggle_all_probe_dots(self, *args): if self.dots2_btn is not None : self._overlaps_only = self.dots2_btn.get_active() self.toggle_probe_dots() class rsc_todo_list_gui(coot_extension_gui):
64
64
53
12
52
dperl-sol/cctbx_project
cootbx/validation_lists.py
Python
rsc_todo_list_gui
rsc_todo_list_gui
133
138
133
133
14b08320511e015dfd3dc57424a7d07738fb2e1f
bigcode/the-stack
train
ea45fb44cdca088e60d020a7
train
function
def show_probe_dots(show_dots, overlaps_only): import coot # import dependency n_objects = number_of_generic_objects() sys.stdout.flush() if show_dots : for object_number in range(n_objects): obj_name = generic_object_name(object_number) if overlaps_only and not obj_name in ["small overlap", "ba...
def show_probe_dots(show_dots, overlaps_only):
import coot # import dependency n_objects = number_of_generic_objects() sys.stdout.flush() if show_dots : for object_number in range(n_objects): obj_name = generic_object_name(object_number) if overlaps_only and not obj_name in ["small overlap", "bad overlap"] : sys.stdout.flush() ...
None : row = model[tree_iter] xyz = row[-1] if isinstance(xyz, tuple) and len(xyz) == 3 : set_rotation_centre(*xyz) set_zoom(30) graphics_draw() def show_probe_dots(show_dots, overlaps_only):
64
64
135
12
52
dperl-sol/cctbx_project
cootbx/validation_lists.py
Python
show_probe_dots
show_probe_dots
186
201
186
186
b51cc9cae5f1e3a6c80b87bd7d82b38b6f2ab20f
bigcode/the-stack
train
9bcc1396d00bc9d84125edad
train
class
class residue_properties_list(object): def __init__(self, columns, column_types, rows, box, default_size=(380,200)): assert len(columns) == (len(column_types) - 1) if (len(rows) > 0) and (len(rows[0]) != len(column_types)): raise RuntimeError("Wrong number of rows:\n%s" % str(rows[0])) import ...
class residue_properties_list(object):
def __init__(self, columns, column_types, rows, box, default_size=(380,200)): assert len(columns) == (len(column_types) - 1) if (len(rows) > 0) and (len(rows[0]) != len(column_types)): raise RuntimeError("Wrong number of rows:\n%s" % str(rows[0])) import gtk self.liststore = gtk.ListStore(...
self.dots2_btn.set_sensitive(True) else : self.dots2_btn.set_sensitive(False) show_probe_dots(show_dots, overlaps_only) def toggle_all_probe_dots(self, *args): if self.dots2_btn is not None : self._overlaps_only = self.dots2_btn.get_active() self.toggle_probe_dots() class rsc_to...
138
138
460
6
132
dperl-sol/cctbx_project
cootbx/validation_lists.py
Python
residue_properties_list
residue_properties_list
140
184
140
140
70e190dffdd22da2d8bc0d61b465957b8128c7e4
bigcode/the-stack
train
52e34193f92424992986121f
train
function
@bp.route("/logout") def logout(): """Clear the current session, including the stored user id.""" session.clear() return redirect(url_for("index"))
@bp.route("/logout") def logout():
"""Clear the current session, including the stored user id.""" session.clear() return redirect(url_for("index"))
error is None: # store the user id in a new session and return to the index session.clear() session["user_id"] = user.id return redirect(url_for("index")) flash(error) return render_template("auth/login.html") @bp.route("/logout") def logout():
64
64
34
9
55
fossabot/flask-tutorial
flaskr/auth/views.py
Python
logout
logout
112
116
112
113
052ad5d0e60e4e07b826b6c7d10a0205e2addc71
bigcode/the-stack
train
96ee4ee75ce41e1a6b04a6e5
train
function
def login_required(view): """View decorator that redirects anonymous users to the login page.""" @functools.wraps(view) def wrapped_view(**kwargs): if g.user is None: return redirect(url_for("auth.login")) return view(**kwargs) return wrapped_view
def login_required(view):
"""View decorator that redirects anonymous users to the login page.""" @functools.wraps(view) def wrapped_view(**kwargs): if g.user is None: return redirect(url_for("auth.login")) return view(**kwargs) return wrapped_view
redirect from flask import render_template from flask import request from flask import session from flask import url_for from werkzeug.exceptions import abort from flaskr import db from flaskr.auth.models import User bp = Blueprint("auth", __name__, url_prefix="/auth") def login_required(view):
64
64
61
5
59
fossabot/flask-tutorial
flaskr/auth/views.py
Python
login_required
login_required
19
29
19
19
09f283d6fd03293a729a6189012da770a2f42e86
bigcode/the-stack
train
2e15bc32f539f668f79d8aff
train
function
def get_profile(id, check_author=True): # user = User.query.filter_by(id=id).with_entities(User.username.label('username'), User.profile.label('profile')).first() # user.update({'username': user_attributes[0], 'profile' = }) user = User.query.get_or_404(id, f"User id {id} doesn't exist.") print(user.use...
def get_profile(id, check_author=True): # user = User.query.filter_by(id=id).with_entities(User.username.label('username'), User.profile.label('profile')).first() # user.update({'username': user_attributes[0], 'profile' = })
user = User.query.get_or_404(id, f"User id {id} doesn't exist.") print(user.username) print(g.user) if check_author and user != g.user: abort(403) return user
return view(**kwargs) return wrapped_view def get_profile(id, check_author=True): # user = User.query.filter_by(id=id).with_entities(User.username.label('username'), User.profile.label('profile')).first() # user.update({'username': user_attributes[0], 'profile' = })
64
64
103
53
10
fossabot/flask-tutorial
flaskr/auth/views.py
Python
get_profile
get_profile
32
41
32
34
41f9aa6e8c0cbd15c18756ec44838dc2294aea99
bigcode/the-stack
train
9c307d384cd5c35f19c8359b
train
function
@bp.route("/<int:id>/profile", methods=("GET", "POST")) @login_required def profile(id): """Update a user profile""" user = get_profile(id) if request.method == "POST": username = request.form["username"] profile = request.form["profile"] error = None if not username: ...
@bp.route("/<int:id>/profile", methods=("GET", "POST")) @login_required def profile(id):
"""Update a user profile""" user = get_profile(id) if request.method == "POST": username = request.form["username"] profile = request.form["profile"] error = None if not username: error = "Username is required" if not profile: error = "Prof...
("auth/login.html") @bp.route("/logout") def logout(): """Clear the current session, including the stored user id.""" session.clear() return redirect(url_for("index")) @bp.route("/<int:id>/profile", methods=("GET", "POST")) @login_required def profile(id):
63
64
147
24
39
fossabot/flask-tutorial
flaskr/auth/views.py
Python
profile
profile
119
144
119
121
d5252e8578fe0b4ae0a1a0d881fc6f350ff1145c
bigcode/the-stack
train
e671db90d86b1d188e6fc7cf
train
function
@bp.route("/login", methods=("GET", "POST")) def login(): """Log in a registered user by adding the user id to the session.""" if request.method == "POST": username = request.form["username"] password = request.form["password"] error = None user = User.query.filter_by(username=us...
@bp.route("/login", methods=("GET", "POST")) def login():
"""Log in a registered user by adding the user id to the session.""" if request.method == "POST": username = request.form["username"] password = request.form["password"] error = None user = User.query.filter_by(username=username).first() if user is None: erro...
go to the login page db.session.add(User(username=username, password=password, profile=profile)) db.session.commit() return redirect(url_for("auth.login")) flash(error) return render_template("auth/register.html") @bp.route("/login", methods=("GET", "POST")) def login(...
64
64
158
16
48
fossabot/flask-tutorial
flaskr/auth/views.py
Python
login
login
87
109
87
88
cf2e0fecce024f061375f502c1c8b31913e68e77
bigcode/the-stack
train
e7b1092fdd3312fce60a7da8
train
function
@bp.before_app_request def load_logged_in_user(): """If a user id is stored in the session, load the user object from the database into ``g.user``.""" user_id = session.get("user_id") g.user = User.query.get(user_id) if user_id is not None else None
@bp.before_app_request def load_logged_in_user():
"""If a user id is stored in the session, load the user object from the database into ``g.user``.""" user_id = session.get("user_id") g.user = User.query.get(user_id) if user_id is not None else None
= }) user = User.query.get_or_404(id, f"User id {id} doesn't exist.") print(user.username) print(g.user) if check_author and user != g.user: abort(403) return user @bp.before_app_request def load_logged_in_user():
64
64
68
12
51
fossabot/flask-tutorial
flaskr/auth/views.py
Python
load_logged_in_user
load_logged_in_user
44
49
44
45
15cca4f30b5999bdf63e10194ea0e693474dee64
bigcode/the-stack
train
02f1592be1cf3beac2d595fe
train
function
@bp.route("/register", methods=("GET", "POST")) def register(): """Register a new user. Validates that the username is not already taken. Hashes the password for security. """ if request.method == "POST": username = request.form["username"] password = request.form["password"] ...
@bp.route("/register", methods=("GET", "POST")) def register():
"""Register a new user. Validates that the username is not already taken. Hashes the password for security. """ if request.method == "POST": username = request.form["username"] password = request.form["password"] profile = request.form["profile"] error = None ...
stored in the session, load the user object from the database into ``g.user``.""" user_id = session.get("user_id") g.user = User.query.get(user_id) if user_id is not None else None @bp.route("/register", methods=("GET", "POST")) def register():
65
65
219
16
48
fossabot/flask-tutorial
flaskr/auth/views.py
Python
register
register
52
84
52
53
0b7d2d576fe0e70925b88ff64f64d3f51d003c9d
bigcode/the-stack
train
2aaa1c9c31839bfac01dacd3
train
function
def init_app(app): db.init_app(app)
def init_app(app):
db.init_app(app)
from .base import db def init_app(app):
11
64
11
5
5
chenx6/setu-server
setu_viewer/models/__init__.py
Python
init_app
init_app
4
5
4
4
f297b3517ea9dfb2cae9ff486b80419efffcd914
bigcode/the-stack
train
4d6a1954529920d20e285e06
train
function
def PreProcessData(train_df, test_df): # remove "Ticket" and "Cabin" fields train_df = train_df.drop(['Ticket', 'Cabin'], axis=1) test_df = test_df.drop(['Ticket', 'Cabin'], axis=1) combine = [train_df, test_df] # add title field for dataset in combine: dataset['Title'] = dataset.Name....
def PreProcessData(train_df, test_df): # remove "Ticket" and "Cabin" fields
train_df = train_df.drop(['Ticket', 'Cabin'], axis=1) test_df = test_df.drop(['Ticket', 'Cabin'], axis=1) combine = [train_df, test_df] # add title field for dataset in combine: dataset['Title'] = dataset.Name.str.extract(' ([A-Za-z]+)\.', expand=False) # remove "Name" and "PassengerID...
#!/usr/bin/python # # Preprocesses data, adapted from: # https://www.kaggle.com/startupsci/titanic-data-science-solutions # # Author: Chaney Lin # Date: April 2018 # import pandas as pd import numpy as np def PreProcessData(train_df, test_df): # remove "Ticket" and "Cabin" fields
86
256
1,169
23
62
clin-projects/kaggle-titanic
preprocess.py
Python
PreProcessData
PreProcessData
13
115
13
15
01fe848d15163ea757fb97f5d394e276abba01e4
bigcode/the-stack
train
1a702a1f38021a857ccdc515
train
class
class AaveInquirer(): def __init__( self, ethereum_manager: 'EthereumManager', database: 'DBHandler', premium: Optional[Premium], msg_aggregator: MessagesAggregator, ) -> None: self.ethereum = ethereum_manager self.database = database ...
class AaveInquirer():
def __init__( self, ethereum_manager: 'EthereumManager', database: 'DBHandler', premium: Optional[Premium], msg_aggregator: MessagesAggregator, ) -> None: self.ethereum = ethereum_manager self.database = database self.msg_aggreg...
total interest accrued for all Atoken of an address """ events: List[AaveEvent] total_earned_interest: Dict[Asset, Balance] total_lost: Dict[Asset, Balance] total_earned_liquidations: Dict[Asset, Balance] class AaveInquirer():
64
64
200
6
58
davbre/rotki
rotkehlchen/chain/ethereum/aave/common.py
Python
AaveInquirer
AaveInquirer
130
160
130
131
1bd9966826df0504bc13ae8fe2808b637b1d4121
bigcode/the-stack
train
ada9fccc8ba7b226c3fac762
train
class
class AaveBalances(NamedTuple): """The Aave balances per account. Using str for symbol since ETH is not a token""" lending: Dict[str, AaveLendingBalance] borrowing: Dict[str, AaveBorrowingBalance]
class AaveBalances(NamedTuple):
"""The Aave balances per account. Using str for symbol since ETH is not a token""" lending: Dict[str, AaveLendingBalance] borrowing: Dict[str, AaveBorrowingBalance]
[str, Dict[str, str]]]: return { 'balance': self.balance.serialize(), 'variable_apr': self.variable_apr.to_percentage(precision=2), 'stable_apr': self.stable_apr.to_percentage(precision=2), } class AaveBalances(NamedTuple):
64
64
52
8
56
davbre/rotki
rotkehlchen/chain/ethereum/aave/common.py
Python
AaveBalances
AaveBalances
50
53
50
50
9f253dd6ca0798832e4b666423ec5e6b99027b01
bigcode/the-stack
train
a2b3d2934e76315f558f752f
train
class
class AaveBorrowingBalance(NamedTuple): """A balance for Aave borrowing. Asset not included here since it's the key in the map that leads to this structure """ balance: Balance variable_apr: FVal stable_apr: FVal def serialize(self) -> Dict[str, Union[str, Dict[str, str]]]: return ...
class AaveBorrowingBalance(NamedTuple):
"""A balance for Aave borrowing. Asset not included here since it's the key in the map that leads to this structure """ balance: Balance variable_apr: FVal stable_apr: FVal def serialize(self) -> Dict[str, Union[str, Dict[str, str]]]: return { 'balance': self.balance.se...
Balance apy: FVal def serialize(self) -> Dict[str, Union[str, Dict[str, str]]]: return { 'balance': self.balance.serialize(), 'apy': self.apy.to_percentage(precision=2), } class AaveBorrowingBalance(NamedTuple):
64
64
126
10
54
davbre/rotki
rotkehlchen/chain/ethereum/aave/common.py
Python
AaveBorrowingBalance
AaveBorrowingBalance
33
47
33
33
64b807fbe8b7fe21de8b939311d47dfa6ab3bc8d
bigcode/the-stack
train
5f6ef93607b9bab690095afa
train
class
class AaveHistory(NamedTuple): """All events and total interest accrued for all Atoken of an address """ events: List[AaveEvent] total_earned_interest: Dict[Asset, Balance] total_lost: Dict[Asset, Balance] total_earned_liquidations: Dict[Asset, Balance]
class AaveHistory(NamedTuple):
"""All events and total interest accrued for all Atoken of an address """ events: List[AaveEvent] total_earned_interest: Dict[Asset, Balance] total_lost: Dict[Asset, Balance] total_earned_liquidations: Dict[Asset, Balance]
if symbol == 'ETH': reserve_address = AAVE_ETH_RESERVE_ADDRESS decimals = 18 else: token = EthereumToken(symbol) reserve_address = token.ethereum_address decimals = token.decimals return reserve_address, decimals class AaveHistory(NamedTuple):
64
64
71
8
55
davbre/rotki
rotkehlchen/chain/ethereum/aave/common.py
Python
AaveHistory
AaveHistory
121
127
121
121
8d91e38fd2e1a2cf2ee790ea47411742d0f6c345
bigcode/the-stack
train
a0e820512b533a4b6e0bde9d
train
function
def _get_reserve_address_decimals(symbol: str) -> Tuple[ChecksumEthAddress, int]: """Get the reserve address and the number of decimals for symbol""" if symbol == 'ETH': reserve_address = AAVE_ETH_RESERVE_ADDRESS decimals = 18 else: token = EthereumToken(symbol) reserve_addre...
def _get_reserve_address_decimals(symbol: str) -> Tuple[ChecksumEthAddress, int]:
"""Get the reserve address and the number of decimals for symbol""" if symbol == 'ETH': reserve_address = AAVE_ETH_RESERVE_ADDRESS decimals = 18 else: token = EthereumToken(symbol) reserve_address = token.ethereum_address decimals = token.decimals return reserve_...
33E2DDaE9': EthereumToken('AAVE'), } ASSET_TO_AAVE_RESERVE_ADDRESS = {v: k for k, v in AAVE_RESERVE_TO_ASSET.items()} def _get_reserve_address_decimals(symbol: str) -> Tuple[ChecksumEthAddress, int]:
63
64
91
21
42
davbre/rotki
rotkehlchen/chain/ethereum/aave/common.py
Python
_get_reserve_address_decimals
_get_reserve_address_decimals
108
118
108
108
16f9a5549f91e4306be0224b071a6dc70af2c5d7
bigcode/the-stack
train
fc7199a4a322dcadf24e2ad6
train
class
class AaveLendingBalance(NamedTuple): """A balance for Aave lending. Asset not included here since it's the key in the map that leads to this structure """ balance: Balance apy: FVal def serialize(self) -> Dict[str, Union[str, Dict[str, str]]]: return { 'balance': self.bala...
class AaveLendingBalance(NamedTuple):
"""A balance for Aave lending. Asset not included here since it's the key in the map that leads to this structure """ balance: Balance apy: FVal def serialize(self) -> Dict[str, Union[str, Dict[str, str]]]: return { 'balance': self.balance.serialize(), 'apy': se...
hlchen.typing import ChecksumEthAddress, Timestamp from rotkehlchen.user_messages import MessagesAggregator if TYPE_CHECKING: from rotkehlchen.chain.ethereum.manager import EthereumManager from rotkehlchen.db.dbhandler import DBHandler class AaveLendingBalance(NamedTuple):
64
64
96
10
53
davbre/rotki
rotkehlchen/chain/ethereum/aave/common.py
Python
AaveLendingBalance
AaveLendingBalance
18
30
18
18
fc67033a12fc594df629ec282f1b3db49669b38c
bigcode/the-stack
train
291755de64a489b58abb9933
train
class
class PostType(graphene_django.DjangoObjectType): """ A blog post. """ rendered = graphene.String( description=_("The rendered HTML of the post's Markdown content.") ) class Meta: only_fields = ( "author", "content", "published", ...
class PostType(graphene_django.DjangoObjectType):
""" A blog post. """ rendered = graphene.String( description=_("The rendered HTML of the post's Markdown content.") ) class Meta: only_fields = ( "author", "content", "published", "slug", "title", "updated"...
import graphene import graphene_django from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from cms.blog import models class PostType(graphene_django.DjangoObjectType):
43
64
84
12
30
UNCDarkside/DarksiteAPI
darksite/cms/blog/schema.py
Python
PostType
PostType
9
27
9
9
fe9a981c06ad1c1101df2f75c0c0ff21961b66c7
bigcode/the-stack
train
85a9051804da7498d37fd76e
train
class
class Query(graphene.ObjectType): post = graphene.Field( PostType, description=_("Query for a specific post."), slug=graphene.String( description=_("The unique slug identifying the post.") ), ) posts = graphene.List( PostType, description=_("Query for a li...
class Query(graphene.ObjectType):
post = graphene.Field( PostType, description=_("Query for a specific post."), slug=graphene.String( description=_("The unique slug identifying the post.") ), ) posts = graphene.List( PostType, description=_("Query for a list of posts.") ) @staticm...
description=_("The rendered HTML of the post's Markdown content.") ) class Meta: only_fields = ( "author", "content", "published", "slug", "title", "updated", ) model = models.Post class Query(graphene.Objec...
64
64
207
7
56
UNCDarkside/DarksiteAPI
darksite/cms/blog/schema.py
Python
Query
Query
30
66
30
30
373174fa8e58ae18f73c5b6a36b92badde03b006
bigcode/the-stack
train
75f911e9f1619cbd9f13f652
train
class
class EvoPy: """Main class of the EvoPy package.""" def __init__(self, fitness_function, individual_length, warm_start=None, generations=100, population_size=30, num_children=1, mean=0, std=1, maximize=False, strategy=Strategy.SINGLE_VARIANCE, random_seed=None, reporter=None, ...
class EvoPy:
"""Main class of the EvoPy package.""" def __init__(self, fitness_function, individual_length, warm_start=None, generations=100, population_size=30, num_children=1, mean=0, std=1, maximize=False, strategy=Strategy.SINGLE_VARIANCE, random_seed=None, reporter=None, ...
"""Module used for the execution of the evolutionary algorithm.""" import time import numpy as np from evopy.individual import Individual from evopy.progress_report import ProgressReport from evopy.strategy import Strategy from evopy.utils import random_with_seed class EvoPy:
56
256
950
4
51
evopy/evopy
evopy/evopy.py
Python
EvoPy
EvoPy
12
114
12
12
79a156b2bed0630f832e05204d5175c7181b5f6c
bigcode/the-stack
train
30ccd144bb1e039d80c7d90c
train
function
@pytest.fixture(scope='session') def imu_fields() -> List[str]: return [f'imu/{prefix}_{x}' for prefix, x in product(('acl', 'gyr'), 'xyz')]
@pytest.fixture(scope='session') def imu_fields() -> List[str]:
return [f'imu/{prefix}_{x}' for prefix, x in product(('acl', 'gyr'), 'xyz')]
0 config.ROI_CROP_RIGHT = 0 config.ROI_CROP_LEFT = 0 def add_augmentation_to_config(config: Config): config.AUGMENTATIONS = ['MULTIPLY', 'BLUR'] @pytest.fixture(scope='session') def imu_fields() -> List[str]:
64
64
41
14
50
tikisi/donkeycar
donkeycar/tests/test_train.py
Python
imu_fields
imu_fields
63
65
63
64
c4799086e5e69041775888ea21f3736cc5aa58ef
bigcode/the-stack
train
ab6720e4add7f9d83ec53d63
train
function
@pytest.fixture(scope='session') def car_dir(tmpdir_factory, base_config, imu_fields) -> str: """ Creating car dir with sub dirs and extracting tub """ car_dir = tmpdir_factory.mktemp('mycar') os.mkdir(os.path.join(car_dir, 'models')) # extract tub.tar.gz into car_dir/tub this_dir = os.path.dirname(...
@pytest.fixture(scope='session') def car_dir(tmpdir_factory, base_config, imu_fields) -> str:
""" Creating car dir with sub dirs and extracting tub """ car_dir = tmpdir_factory.mktemp('mycar') os.mkdir(os.path.join(car_dir, 'models')) # extract tub.tar.gz into car_dir/tub this_dir = os.path.dirname(os.path.abspath(__file__)) with tarfile.open(os.path.join(this_dir, 'tub', 'tub.tar.gz')) ...
ROI_CROP_RIGHT = 0 config.ROI_CROP_LEFT = 0 def add_augmentation_to_config(config: Config): config.AUGMENTATIONS = ['MULTIPLY', 'BLUR'] @pytest.fixture(scope='session') def imu_fields() -> List[str]: return [f'imu/{prefix}_{x}' for prefix, x in product(('acl', 'gyr'), 'xyz')] @pytest.fixture(scope='sess...
108
109
366
22
86
tikisi/donkeycar
donkeycar/tests/test_train.py
Python
car_dir
car_dir
68
98
68
69
87be658c1b214fda9381da92017940f71b488869
bigcode/the-stack
train
4aae85957254c2bf1e609897
train
function
@pytest.fixture(scope='session') def base_config() -> Config: """ Config for the test with relevant parameters""" cfg = Config() cfg.BATCH_SIZE = 64 cfg.TRAIN_TEST_SPLIT = 0.8 cfg.IMAGE_H = 120 cfg.IMAGE_W = 160 cfg.IMAGE_DEPTH = 3 cfg.PRINT_MODEL_SUMMARY = True cfg.EARLY_STOP_PATIEN...
@pytest.fixture(scope='session') def base_config() -> Config:
""" Config for the test with relevant parameters""" cfg = Config() cfg.BATCH_SIZE = 64 cfg.TRAIN_TEST_SPLIT = 0.8 cfg.IMAGE_H = 120 cfg.IMAGE_W = 160 cfg.IMAGE_DEPTH = 3 cfg.PRINT_MODEL_SUMMARY = True cfg.EARLY_STOP_PATIENCE = 1000 cfg.MAX_EPOCHS = 6 cfg.MODEL_CATEGORICAL_MAX...
car.utils import get_model_by_type, normalize_image, train_test_split Data = namedtuple('Data', ['type', 'name', 'convergence', 'pretrained', 'preprocess'], defaults=(None, ) * 5) @pytest.fixture(scope='session') def base_config() -> Config:
64
64
202
13
51
tikisi/donkeycar
donkeycar/tests/test_train.py
Python
base_config
base_config
20
39
20
21
a31c428eb51fc418530b019be8d7674c1dea6cf0
bigcode/the-stack
train
e7a7d221913537b116152784
train
function
@pytest.fixture(scope='session') def config(base_config, car_dir) -> Config: cfg = base_config cfg.MODELS_PATH = os.path.join(car_dir, 'models') cfg.DATA_PATH = os.path.join(car_dir, 'tub') cfg.DATA_PATH_ALL = os.path.join(car_dir, 'tub_full') return cfg
@pytest.fixture(scope='session') def config(base_config, car_dir) -> Config:
cfg = base_config cfg.MODELS_PATH = os.path.join(car_dir, 'models') cfg.DATA_PATH = os.path.join(car_dir, 'tub') cfg.DATA_PATH_ALL = os.path.join(car_dir, 'tub_full') return cfg
.SHOW_PLOT = False cfg.BEHAVIOR_LIST = ['Left_Lane', "Right_Lane"] cfg.NUM_LOCATIONS = 3 cfg.SEQUENCE_LENGTH = 3 return cfg @pytest.fixture(scope='session') def config(base_config, car_dir) -> Config:
64
64
74
17
46
tikisi/donkeycar
donkeycar/tests/test_train.py
Python
config
config
42
48
42
43
80d4f89d9aa197232bcbfac522ab98a025eff5c4
bigcode/the-stack
train
e3428c34115c1b3aeba70cbc
train
function
def add_transformation_to_config(config: Config): config.TRANSFORMATIONS = ['CROP'] config.ROI_CROP_TOP = 45 config.ROI_CROP_BOTTOM = 0 config.ROI_CROP_RIGHT = 0 config.ROI_CROP_LEFT = 0
def add_transformation_to_config(config: Config):
config.TRANSFORMATIONS = ['CROP'] config.ROI_CROP_TOP = 45 config.ROI_CROP_BOTTOM = 0 config.ROI_CROP_RIGHT = 0 config.ROI_CROP_LEFT = 0
base_config cfg.MODELS_PATH = os.path.join(car_dir, 'models') cfg.DATA_PATH = os.path.join(car_dir, 'tub') cfg.DATA_PATH_ALL = os.path.join(car_dir, 'tub_full') return cfg def add_transformation_to_config(config: Config):
64
64
65
10
53
tikisi/donkeycar
donkeycar/tests/test_train.py
Python
add_transformation_to_config
add_transformation_to_config
51
56
51
51
bfa2a565a0e79b1226fe723f0ad4af2f4cedbdb3
bigcode/the-stack
train
bd4ce66c938682e8a0755929
train
function
def add_augmentation_to_config(config: Config): config.AUGMENTATIONS = ['MULTIPLY', 'BLUR']
def add_augmentation_to_config(config: Config):
config.AUGMENTATIONS = ['MULTIPLY', 'BLUR']
config.TRANSFORMATIONS = ['CROP'] config.ROI_CROP_TOP = 45 config.ROI_CROP_BOTTOM = 0 config.ROI_CROP_RIGHT = 0 config.ROI_CROP_LEFT = 0 def add_augmentation_to_config(config: Config):
64
64
26
10
53
tikisi/donkeycar
donkeycar/tests/test_train.py
Python
add_augmentation_to_config
add_augmentation_to_config
59
60
59
59
8a774db29ae02991abf09f4af4f9ec8b104fb987
bigcode/the-stack
train
c22a7a1e4745ee26c2855ebd
train
function
@pytest.mark.skipif("GITHUB_ACTIONS" in os.environ, reason='Suppress training test in CI') @pytest.mark.parametrize('data', test_data) def test_train(config: Config, data: Data) -> None: """ Testing convergence of the linear an categorical models :param config: donkey config ...
@pytest.mark.skipif("GITHUB_ACTIONS" in os.environ, reason='Suppress training test in CI') @pytest.mark.parametrize('data', test_data) def test_train(config: Config, data: Data) -> None:
""" Testing convergence of the linear an categorical models :param config: donkey config :param data: test case data :return: None """ def pilot_path(name): pilot_name = f'pilot_{name}.h5' return os.path.join(config.MODELS_PATH, pilot_name) ...
, d9, d10, d11, d12] full_tub = ['imu', 'behavior', 'localizer'] @pytest.mark.skipif("GITHUB_ACTIONS" in os.environ, reason='Suppress training test in CI') @pytest.mark.parametrize('data', test_data) def test_train(config: Config, data: Data) -> None:
73
73
244
46
27
tikisi/donkeycar
donkeycar/tests/test_train.py
Python
test_train
test_train
120
146
120
123
05a1b65df76cb2ae797037c23c8f2dcb6199b661
bigcode/the-stack
train
290acb27b815cd92fbd71b8d
train
function
@pytest.mark.parametrize('model_type', model_types) @pytest.mark.parametrize('train_filter', filters) def test_training_pipeline(config: Config, model_type: str, train_filter: Callable[[TubRecord], bool]) -> None: """ Testing consistency of the model interfaces and data used in traini...
@pytest.mark.parametrize('model_type', model_types) @pytest.mark.parametrize('train_filter', filters) def test_training_pipeline(config: Config, model_type: str, train_filter: Callable[[TubRecord], bool]) -> None:
""" Testing consistency of the model interfaces and data used in training pipeline. :param config: donkey config :param model_type: test specification of model type :param train_filter: filter for records :return: None """ ...
ging assert loss[-1] < loss[0] * data.convergence filters = [lambda r: r.underlying['user/throttle'] > 0.5, lambda r: r.underlying['user/angle'] < 0, lambda r: r.underlying['user/throttle'] < 0.6 and r.underlying['user/angle'] > -0.5] model_types = ['linear', 'categorica...
171
171
570
46
125
tikisi/donkeycar
donkeycar/tests/test_train.py
Python
test_training_pipeline
test_training_pipeline
157
211
157
160
0e94bc8625b79e6dbbade5c009bf01afa3008180
bigcode/the-stack
train
dcf35a553abbdfac60078656
train
class
class ImageNet(ImageFolder): def __init__( self, root_dir: str, transforms: Callable = None, **kargs, ) -> None: self.transforms = transforms super().__init__(root_dir, transforms, loader=self._image_loader) def _image_loader(cls, path: str) -> np.ndarray: ...
class ImageNet(ImageFolder):
def __init__( self, root_dir: str, transforms: Callable = None, **kargs, ) -> None: self.transforms = transforms super().__init__(root_dir, transforms, loader=self._image_loader) def _image_loader(cls, path: str) -> np.ndarray: image = cv2.imread(path...
from typing import * import pytorch_lightning as pl from sklearn.model_selection import train_test_split from torch.utils.data import DataLoader, Subset from torchvision.datasets import ImageFolder import cv2 import numpy as np class ImageNet(ImageFolder):
54
64
145
6
47
rapidrabbit76/Classification-For-Everyone
datamodules/ImageNet.py
Python
ImageNet
ImageNet
11
30
11
11
b067723e2682a0ab56d476072894f01e00329e4c
bigcode/the-stack
train
ffe00b60ab178c2e519c2dad
train
function
def ImageNetDataModule(**kwargs): return ImageNetDataModuleBase(ImageNet, **kwargs)
def ImageNetDataModule(**kwargs):
return ImageNetDataModuleBase(ImageNet, **kwargs)
num_workers=self.hparams.num_workers, ) def test_dataloader(self) -> DataLoader: return DataLoader( self.test_ds, batch_size=self.hparams.batch_size, shuffle=False, num_workers=self.hparams.num_workers, ) def ImageNetDataModule(**k...
64
64
21
8
56
rapidrabbit76/Classification-For-Everyone
datamodules/ImageNet.py
Python
ImageNetDataModule
ImageNetDataModule
119
120
119
119
39265b122f285e1db125f46df4dd85f0d8fb7884
bigcode/the-stack
train
5801bc1a4edf4de85e6d7ec4
train
class
class ImageNetDataModuleBase(pl.LightningDataModule): def __init__( self, DATASET: ImageNet, root_dir: str, train_transforms: Callable, val_transforms: Callable, test_transforms: Callable, batch_size: int = 256, num_workers: int = 8, ): sup...
class ImageNetDataModuleBase(pl.LightningDataModule):
def __init__( self, DATASET: ImageNet, root_dir: str, train_transforms: Callable, val_transforms: Callable, test_transforms: Callable, batch_size: int = 256, num_workers: int = 8, ): super().__init__() self.save_hyperparameters( ...
): def __init__( self, root_dir: str, transforms: Callable = None, **kargs, ) -> None: self.transforms = transforms super().__init__(root_dir, transforms, loader=self._image_loader) def _image_loader(cls, path: str) -> np.ndarray: image = cv2.imread(p...
152
152
507
12
139
rapidrabbit76/Classification-For-Everyone
datamodules/ImageNet.py
Python
ImageNetDataModuleBase
ImageNetDataModuleBase
33
116
33
33
0f47d297f9255d0d9316361037be044d5aea2e0c
bigcode/the-stack
train
a7e0b6e853a6ca1c334ad406
train
class
class CommandServe(Command): """Start test server.""" name = "serve" doc_usage = "[options]" doc_purpose = "start the test webserver" logger = None cmd_options = ( { 'name': 'port', 'short': 'p', 'long': 'port', 'default': 8000, ...
class CommandServe(Command):
"""Start test server.""" name = "serve" doc_usage = "[options]" doc_purpose = "start the test webserver" logger = None cmd_options = ( { 'name': 'port', 'short': 'p', 'long': 'port', 'default': 8000, 'type': int, '...
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from __future__ import print_function import os import webbrowser try: from BaseHTTPServer import HTTPServer from SimpleHTTPServer im...
126
126
420
5
120
pellenilsson/nikola
nikola/plugins/command/serve.py
Python
CommandServe
CommandServe
41
96
41
41
f4061aef2e7be39f2418b5bdc5524451361f5aa2
bigcode/the-stack
train
9ef9891c17e5e8515355ec3d
train
class
class OurHTTPRequestHandler(SimpleHTTPRequestHandler): extensions_map = dict(SimpleHTTPRequestHandler.extensions_map) extensions_map[""] = "text/plain" # NOTICE: this is a patched version of send_head() to disable all sorts of # caching. `nikola serve` is a development server, hence caching should ...
class OurHTTPRequestHandler(SimpleHTTPRequestHandler):
extensions_map = dict(SimpleHTTPRequestHandler.extensions_map) extensions_map[""] = "text/plain" # NOTICE: this is a patched version of send_head() to disable all sorts of # caching. `nikola serve` is a development server, hence caching should # not happen to have access to the newest resources. ...
, options, args): """Start test server.""" self.logger = get_logger('serve', self.site.loghandlers) out_dir = self.site.config['OUTPUT_FOLDER'] if not os.path.isdir(out_dir): self.logger.error("Missing '{0}' folder?".format(out_dir)) else: os.chdir(out_dir...
209
209
697
8
201
pellenilsson/nikola
nikola/plugins/command/serve.py
Python
OurHTTPRequestHandler
OurHTTPRequestHandler
99
173
99
99
e4d06b221a543de412aa171e262797c7f42b4a0a
bigcode/the-stack
train
422c2de3fefb9bce1e79d81b
train
function
def get_parser(): """Argument parser.""" parser = argparse.ArgumentParser() parser.add_argument("datalist", type=str, help="Path to the list of audio files") parser.add_argument( "--num_dev", type=int_or_float_or_numstr, required=True, help="Number of samples to assign to...
def get_parser():
"""Argument parser.""" parser = argparse.ArgumentParser() parser.add_argument("datalist", type=str, help="Path to the list of audio files") parser.add_argument( "--num_dev", type=int_or_float_or_numstr, required=True, help="Number of samples to assign to the development s...
#!/usr/bin/env python # Copyright 2022 Shanghai Jiao Tong University (Authors: Wangyou Zhang) # Apache 2.0 import argparse import random from collections import defaultdict from pathlib import Path from split_train_dev import int_or_float_or_numstr, split_train_dev, split_train_dev_v2 def get_parser():
73
110
369
4
68
roshansh-cmu/espnet
egs2/aishell4/enh1/local/split_train_dev_by_column.py
Python
get_parser
get_parser
13
61
13
13
cf0d7d660c1edd5d835d6312761af2c82512bb24
bigcode/the-stack
train
dd5bee2120df31f9fbfd87d6
train
class
class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) password1 = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ( 'username', 'first_name', ...
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True) password1 = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', ...
from django import forms from django.contrib.auth.models import User from .models import UserProfile, Point from django.contrib.auth.forms import UserCreationForm, UserChangeForm from multiselectfield import MultiSelectField from fluent_comments.forms import CompactLabelsCommentForm class RegistrationForm(UserCreationF...
62
64
83
7
54
steventimberman/debateIt
debate/forms.py
Python
RegistrationForm
RegistrationForm
8
22
8
8
a54859fa2a327e9c7ef6d640679648ba2d896790
bigcode/the-stack
train
9c62fa36877ef0b0d7dc420d
train
class
class UserProfileRegForm(forms.ModelForm): image = forms.ImageField(required=False) city = forms.CharField(required=True) forms.CharField() favorite_topics = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=UserProfile.TOPIC_CHOICES) ...
class UserProfileRegForm(forms.ModelForm):
image = forms.ImageField(required=False) city = forms.CharField(required=True) forms.CharField() favorite_topics = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=UserProfile.TOPIC_CHOICES) class Meta: model = UserProfile...
self.cleaned_data['first_name'] # user.last_name = self.cleaned_data['last_name'] # user.email = self.cleaned_data['email'] # # if commit: # user.save() # # return user class UserProfileRegForm(forms.ModelForm):
64
64
87
9
54
steventimberman/debateIt
debate/forms.py
Python
UserProfileRegForm
UserProfileRegForm
35
50
35
35
bca80faf066c742d79f443f50d8d25ce7d0674a6
bigcode/the-stack
train
ce3a013dc9d9370bcd055334
train
class
class EditProfileForm(UserChangeForm): class Meta: model = User fields = ( 'email', 'first_name', 'last_name', 'password' )
class EditProfileForm(UserChangeForm):
class Meta: model = User fields = ( 'email', 'first_name', 'last_name', 'password' )
() favorite_topics = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=UserProfile.TOPIC_CHOICES) class Meta: model = UserProfile fields = ( 'image', 'city', 'favorite_topics' ) class...
64
64
41
8
56
steventimberman/debateIt
debate/forms.py
Python
EditProfileForm
EditProfileForm
53
61
53
53
89af4611507b8e6139bb6c02073a2f6d44c1de60
bigcode/the-stack
train
90a1d942b9fd644588a67641
train
class
class CommentForm(forms.ModelForm): class Meta: model = Point fields = ('claim',)
class CommentForm(forms.ModelForm):
class Meta: model = Point fields = ('claim',)
'image', 'city', 'favorite_topics' ) class EditProfileForm(UserChangeForm): class Meta: model = User fields = ( 'email', 'first_name', 'last_name', 'password' ) class CommentForm(forms.ModelForm):
63
64
23
7
56
steventimberman/debateIt
debate/forms.py
Python
CommentForm
CommentForm
65
69
65
66
f5caff1b46e7fefc27127068ee4054b6048d200e
bigcode/the-stack
train
20d4e8e622a7205f3b2768d1
train
class
class CommentForm(CompactLabelsCommentForm): """ The comment form to use """ def __init__(self, *args, **kwargs): super(CommentForm, self).__init__(*args, **kwargs) self.fields['url'].label = "Website" # Changed the label self.fields['name'] = User
class CommentForm(CompactLabelsCommentForm):
""" The comment form to use """ def __init__(self, *args, **kwargs): super(CommentForm, self).__init__(*args, **kwargs) self.fields['url'].label = "Website" # Changed the label self.fields['name'] = User
Meta: model = User fields = ( 'email', 'first_name', 'last_name', 'password' ) class CommentForm(forms.ModelForm): class Meta: model = Point fields = ('claim',) class CommentForm(CompactLabelsCommentForm):
64
64
73
9
55
steventimberman/debateIt
debate/forms.py
Python
CommentForm
CommentForm
72
80
72
72
0ce771390e1ac96a8f343ef461f80202f1ff9fb0
bigcode/the-stack
train
89812f45d44751c2ba191739
train
class
class FileMatcher(FileMatch): """A wrapper for Matched Files with an additional matching logic layer. Attributes ---------- _unique_strings (list): List of unique string artifacts that were found in the source file _unique_consts (list): List of unique numeric const artifacts that were foun...
class FileMatcher(FileMatch):
"""A wrapper for Matched Files with an additional matching logic layer. Attributes ---------- _unique_strings (list): List of unique string artifacts that were found in the source file _unique_consts (list): List of unique numeric const artifacts that were found in the source file _...
from core.file_layer import * from config.utils import * import config.anchor as anchor class FileMatcher(FileMatch):
26
256
4,118
6
19
CrackerCat/Karta
src/file_layer.py
Python
FileMatcher
FileMatcher
5
361
5
5
11f72d0c0427f2c07e45fe9ae87d1b332d1a4459
bigcode/the-stack
train
08108ece6405dbc8e10d41d8
train
class
class OpenApiArt(object): """Bundle and generate artifacts from OpenAPI files. Args ---- - api_files (list[str]): list of OpenAPI files that contain info and/or path keywords - protobuf_name (str): name of the .proto file that will be generated - artifact_dir (str): directory where artifa...
class OpenApiArt(object):
"""Bundle and generate artifacts from OpenAPI files. Args ---- - api_files (list[str]): list of OpenAPI files that contain info and/or path keywords - protobuf_name (str): name of the .proto file that will be generated - artifact_dir (str): directory where artifacts will be created. ...
import sys import os import importlib import shutil import yaml import subprocess import requests import platform class OpenApiArt(object):
31
256
2,230
6
24
Rangababu-R/openapiart
openapiart/openapiart.py
Python
OpenApiArt
OpenApiArt
11
281
11
11
b7e5e02e3fa7a9b0eb20f35caa3bc1c6aac0c54d
bigcode/the-stack
train
86d87204e569221e4ab80823
train
function
def index(request): return HttpResponse('Главная страница')
def index(request):
return HttpResponse('Главная страница')
from django.http import HttpResponse # Главная страница def index(request):
17
64
14
4
12
Capralg/yatube_project
yatube/posts/views.py
Python
index
index
4
5
4
4
fc1c9f4fc75e7aabbc7cfcdf5b35ed6d44825455
bigcode/the-stack
train
0b32e09760b531a871502321
train
function
def group_posts(request, pk): return HttpResponse(f'Какой-то пост {pk}')
def group_posts(request, pk):
return HttpResponse(f'Какой-то пост {pk}')
from django.http import HttpResponse # Главная страница def index(request): return HttpResponse('Главная страница') # Страница, на которой будут посты, отфильтрованные по группам def group_posts(request, pk):
53
64
20
7
45
Capralg/yatube_project
yatube/posts/views.py
Python
group_posts
group_posts
8
9
8
8
b0df5c3dba285eefca8f731eb39d3fc7951b5cbf
bigcode/the-stack
train
62a635aef9293c11155e8869
train
function
def buildMap(instructions): _Map_ = {} for row in instructions: if row[0] in _Map_: _Map_[row[0]].append(row[1]) else: _Map_[row[0]] = [row[1]] return _Map_
def buildMap(instructions):
_Map_ = {} for row in instructions: if row[0] in _Map_: _Map_[row[0]].append(row[1]) else: _Map_[row[0]] = [row[1]] return _Map_
('test.txt', 'r') as file: #with open('test2.txt', 'r') as file: with open('input.txt', 'r') as file: for line in file: newRow = line.strip().split(')') data.append(newRow) def buildMap(instructions):
64
64
65
6
58
fargetan/AoC
2019/Day06/main.py
Python
buildMap
buildMap
10
17
10
10
d4c14da2cfb3522aa366e21f9353c640d22ea9d4
bigcode/the-stack
train
f13c3b7226cbab4cc0866be5
train
function
def FindStarPath(starName, path): for star in starMap: parent = star if starName in starMap[parent]: path.append(parent) FindStarPath(parent, path)
def FindStarPath(starName, path):
for star in starMap: parent = star if starName in starMap[parent]: path.append(parent) FindStarPath(parent, path)
Next('COM', starMap, orbits, depth, depths) print(depths) total = 0 for item in depths: total += depths[item] print(total) # part 2 # Find the paths to each? # search for name def FindStarPath(starName, path):
64
64
44
10
53
fargetan/AoC
2019/Day06/main.py
Python
FindStarPath
FindStarPath
55
60
55
55
a55eac524f6e78555dc18fb970e0ca29c0c060a7
bigcode/the-stack
train
3be7e7d4f79a60ab0d5ab09c
train
function
def FindNext(starname, mapp, orbits, depth, depthDict): # increase level depth += 1 # get leaves stars = mapp[starname] # print(stars) # find next for star in stars: # if star has other orbitals, get those if star in mapp: FindNext(star, mapp, orbits, depth, depthDict) # if star does not...
def FindNext(starname, mapp, orbits, depth, depthDict): # increase level
depth += 1 # get leaves stars = mapp[starname] # print(stars) # find next for star in stars: # if star has other orbitals, get those if star in mapp: FindNext(star, mapp, orbits, depth, depthDict) # if star does not have orbitals, send back the depth depthDict[star] = depth
1]] return _Map_ starMap = buildMap(data) #print(starMap) if 'COM' in starMap: print('found') #recursion to get orbits def FindNext(starname, mapp, orbits, depth, depthDict): # increase level
64
64
120
23
40
fargetan/AoC
2019/Day06/main.py
Python
FindNext
FindNext
26
38
26
27
ce35566f335949262b0fb9ebb6a33590e6a45fbf
bigcode/the-stack
train
3d9800d18b5f932b06d57509
train
function
def test_alternative_file_list(): test_sample = [ "_rels/.rels", "xl/_rels/workbook.xml.rels", "xl/worksheets/worksheet2.xml", "xl/worksheets/worksheet3.xml", "xl/worksheets/worksheet1.xml", "xl/sharedStrings.xml", "xl/workbook.xml", "xl/styles.xml", ...
def test_alternative_file_list():
test_sample = [ "_rels/.rels", "xl/_rels/workbook.xml.rels", "xl/worksheets/worksheet2.xml", "xl/worksheets/worksheet3.xml", "xl/worksheets/worksheet1.xml", "xl/sharedStrings.xml", "xl/workbook.xml", "xl/styles.xml", "docProps/app.xml", ...
expected = [ "xl/worksheets/sheet2.xml", "xl/worksheets/sheet3.xml", "xl/worksheets/sheet1.xml", ] sheet_files = find_sheets(test_sample) eq_(sheet_files, expected) def test_alternative_file_list():
64
64
163
7
57
mobanbot/pyexcel-xlsxr
tests/test_messy_xlsx.py
Python
test_alternative_file_list
test_alternative_file_list
49
71
49
49
d19194781e889628a62171125275f3e72ce487a9
bigcode/the-stack
train
4037fd90d9bd83eaf280a5eb
train
function
def test_list_one(): test_sample = [ "_rels/.rels", "xl/_rels/workbook.xml.rels", "xl/worksheets/sheet2.xml", "xl/worksheets/sheet3.xml", "xl/worksheets/sheet1.xml", "xl/sharedStrings.xml", "xl/workbook.xml", "xl/styles.xml", "docProps/app.xml"...
def test_list_one():
test_sample = [ "_rels/.rels", "xl/_rels/workbook.xml.rels", "xl/worksheets/sheet2.xml", "xl/worksheets/sheet3.xml", "xl/worksheets/sheet1.xml", "xl/sharedStrings.xml", "xl/workbook.xml", "xl/styles.xml", "docProps/app.xml", "docProps/c...
"xl/worksheets/sheet.xml", "xl/worksheets/worksheet.xml", ] expected = [0, 1, 0, 0] actual = [get_sheet_index(file_name) for file_name in samples] eq_(actual, expected) def test_list_one():
64
64
161
5
59
mobanbot/pyexcel-xlsxr
tests/test_messy_xlsx.py
Python
test_list_one
test_list_one
24
46
24
24
27d1d194ea756a3cec1f8b0acb5db74e81b68444
bigcode/the-stack
train
4e9afb488d2cc06e03585715
train
function
def test_alternative_single_sheet(): test_sample = [ "_rels/.rels", "xl/_rels/workbook.xml.rels", "xl/worksheets/worksheet.xml", "xl/sharedStrings.xml", "xl/workbook.xml", "xl/styles.xml", "docProps/app.xml", "docProps/core.xml", "[Content_Type...
def test_alternative_single_sheet():
test_sample = [ "_rels/.rels", "xl/_rels/workbook.xml.rels", "xl/worksheets/worksheet.xml", "xl/sharedStrings.xml", "xl/workbook.xml", "xl/styles.xml", "docProps/app.xml", "docProps/core.xml", "[Content_Types].xml", ] expected = ["xl/w...
/styles.xml", "docProps/app.xml", "docProps/core.xml", "[Content_Types].xml", ] expected = ["xl/worksheets/sheet.xml"] sheet_files = find_sheets(test_sample) eq_(sheet_files, expected) def test_alternative_single_sheet():
64
64
113
7
57
mobanbot/pyexcel-xlsxr
tests/test_messy_xlsx.py
Python
test_alternative_single_sheet
test_alternative_single_sheet
93
109
93
93
bda93c9ee7f327788f264e95aba908e247f57639
bigcode/the-stack
train
d1001aa07c7931290f22658e
train
function
def test_parse_properties(): sample = b'<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><fileVersion appName="Calc"/><workbookPr backupFile="false" showObjects="all" date1904="false"/><workbookProtection/>' ...
def test_parse_properties():
sample = b'<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><fileVersion appName="Calc"/><workbookPr backupFile="false" showObjects="all" date1904="false"/><workbookProtection/>' properties = parse_book_prop...
MM:SS;@" numFmtId="166"/></numFmts><fonts count="4"><font><name val="Arial"/>' styles = parse_styles(sample) eq_(list(styles.values()), ["general", "dd/mm/yy", "h:mm:ss;@"]) def test_parse_properties():
63
64
108
5
58
mobanbot/pyexcel-xlsxr
tests/test_messy_xlsx.py
Python
test_parse_properties
test_parse_properties
137
140
137
137
ad5dec37ab007b60355736f2235917868e0a80ec
bigcode/the-stack
train
74ab4be6da089501e084949c
train
function
def test_parse_xfs_styles(): sample = b'<cellXfs count="3"><xf applyAlignment="false" applyBorder="false" applyFont="false" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="164" xfId="0"></xf><xf applyAlignment="false" applyBorder="false" applyFont="false" applyProtection="false" borderId="0" fi...
def test_parse_xfs_styles():
sample = b'<cellXfs count="3"><xf applyAlignment="false" applyBorder="false" applyFont="false" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="164" xfId="0"></xf><xf applyAlignment="false" applyBorder="false" applyFont="false" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId=...
heets><calcPr iterateCount="100" refMode="A1" iterate="false" iterateDelta="0.001"/>' properties = parse_book_properties(sample) eq_(properties, {"sheets": ["Sheet1", "Sheet2", "Sheet3"]}) def test_parse_xfs_styles():
64
64
203
7
57
mobanbot/pyexcel-xlsxr
tests/test_messy_xlsx.py
Python
test_parse_xfs_styles
test_parse_xfs_styles
149
152
149
149
145c2d105f718b6dd832d0a01813bd1aa5cb45f4
bigcode/the-stack
train
0288c87814106cd94f40f9fc
train
function
def test_parse_styles(): sample = b'<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><numFmts count="3"><numFmt formatCode="GENERAL" numFmtId="164"/><numFmt formatCode="DD/MM/YY" numFmtId="165"/><numFmt formatCode="H:MM:SS;@" numFmtId="166"/></numFmts><fonts count="4"><font><name val="A...
def test_parse_styles():
sample = b'<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><numFmts count="3"><numFmt formatCode="GENERAL" numFmtId="164"/><numFmt formatCode="DD/MM/YY" numFmtId="165"/><numFmt formatCode="H:MM:SS;@" numFmtId="166"/></numFmts><fonts count="4"><font><name val="Arial"/>' styles = par...
False} data = parse_row(xml_string, Book()) eq_( [cell for cell in data], [ datetime(year=2015, month=1, day=1), time(hour=13, minute=13, second=13), ], ) def test_parse_styles():
64
64
133
5
59
mobanbot/pyexcel-xlsxr
tests/test_messy_xlsx.py
Python
test_parse_styles
test_parse_styles
131
134
131
131
47b510f2ab47078a477faa2148c1e08e27f3bf02
bigcode/the-stack
train
dc353e85b5ae8f17c8d6346d
train
function
def test_get_sheet_index(): samples = [ "xl/worksheets/sheet1.xml", "xl/worksheets/worksheet2.xml", "xl/worksheets/sheet.xml", "xl/worksheets/worksheet.xml", ] expected = [0, 1, 0, 0] actual = [get_sheet_index(file_name) for file_name in samples] eq_(actual, expected)...
def test_get_sheet_index():
samples = [ "xl/worksheets/sheet1.xml", "xl/worksheets/worksheet2.xml", "xl/worksheets/sheet.xml", "xl/worksheets/worksheet.xml", ] expected = [0, 1, 0, 0] actual = [get_sheet_index(file_name) for file_name in samples] eq_(actual, expected)
_properties from pyexcel_xlsxr.messy_xlsx import parse_xfs_styles from pyexcel_xlsxr.messy_xlsx import parse_shared_strings from pyexcel_xlsxr.messy_xlsx import get_sheet_index from datetime import datetime, time def test_get_sheet_index():
64
64
92
6
57
mobanbot/pyexcel-xlsxr
tests/test_messy_xlsx.py
Python
test_get_sheet_index
test_get_sheet_index
12
21
12
12
ad0a20c4de8a60e0c2af44786e773b5a8ac91a0d
bigcode/the-stack
train
46934b2ce7f5318849b3d562
train
function
def test_parse_shared_strings(): sample = b'<sst count="2" uniqueCount="2" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><t>Date</t></si><si><t>Time</t></si></sst>' content = parse_shared_strings(sample) eq_(list(content), ["Date", "Time"])
def test_parse_shared_strings():
sample = b'<sst count="2" uniqueCount="2" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><t>Date</t></si><si><t>Time</t></si></sst>' content = parse_shared_strings(sample) eq_(list(content), ["Date", "Time"])
="0" fontId="0" numFmtId="166" xfId="0"></xf></cellXfs><cellStyles count="6">' xfs_styles = parse_xfs_styles(sample) eq_(xfs_styles, [164, 165, 166]) def test_parse_shared_strings():
64
64
80
6
58
mobanbot/pyexcel-xlsxr
tests/test_messy_xlsx.py
Python
test_parse_shared_strings
test_parse_shared_strings
155
158
155
155
2eec3289b6983aa0eef39d7f689f63fe8434e2d7
bigcode/the-stack
train
3143c71d356b7f6883e03297
train
function
def test_parse_row(): xml_string = b'<row collapsed="false" customFormat="false" customHeight="false" hidden="false" ht="12.75" outlineLevel="0" r="4"><c r="A4" s="1" t="n"><v>42005</v></c><c r="B4" s="2" t="n"><v>0.550844907407407</v></c></row>' # flake8: noqa class Book: def __init__(self): ...
def test_parse_row():
xml_string = b'<row collapsed="false" customFormat="false" customHeight="false" hidden="false" ht="12.75" outlineLevel="0" r="4"><c r="A4" s="1" t="n"><v>42005</v></c><c r="B4" s="2" t="n"><v>0.550844907407407</v></c></row>' # flake8: noqa class Book: def __init__(self): self.xfs_styles = ...
", "xl/styles.xml", "docProps/app.xml", "docProps/core.xml", "[Content_Types].xml", ] expected = ["xl/worksheets/worksheet.xml"] sheet_files = find_sheets(test_sample) eq_(sheet_files, expected) def test_parse_row():
66
66
223
5
61
mobanbot/pyexcel-xlsxr
tests/test_messy_xlsx.py
Python
test_parse_row
test_parse_row
112
128
112
112
5b6f4dab5ba243afbb3c4516d1802a61521a98c2
bigcode/the-stack
train
aada36349d90491dd5b80038
train
function
def test_single_sheet(): test_sample = [ "_rels/.rels", "xl/_rels/workbook.xml.rels", "xl/worksheets/sheet.xml", "xl/sharedStrings.xml", "xl/workbook.xml", "xl/styles.xml", "docProps/app.xml", "docProps/core.xml", "[Content_Types].xml", ] ...
def test_single_sheet():
test_sample = [ "_rels/.rels", "xl/_rels/workbook.xml.rels", "xl/worksheets/sheet.xml", "xl/sharedStrings.xml", "xl/workbook.xml", "xl/styles.xml", "docProps/app.xml", "docProps/core.xml", "[Content_Types].xml", ] expected = ["xl/works...
] expected = [ "xl/worksheets/worksheet2.xml", "xl/worksheets/worksheet3.xml", "xl/worksheets/worksheet1.xml", ] sheet_files = find_sheets(test_sample) eq_(sheet_files, expected) def test_single_sheet():
64
64
111
5
59
mobanbot/pyexcel-xlsxr
tests/test_messy_xlsx.py
Python
test_single_sheet
test_single_sheet
74
90
74
74
6a3422e373d1aa31e86e1dc584c0e1d77bb39e32
bigcode/the-stack
train
5faf194445e7a1d358bfdfad
train
function
def test_parse_sheet_properties(): sample = b'</bookViews><sheets><sheet name="Sheet1" sheetId="1" state="visible" r:id="rId2"/><sheet name="Sheet2" sheetId="2" state="visible" r:id="rId3"/><sheet name="Sheet3" sheetId="3" state="visible" r:id="rId4"/></sheets><calcPr iterateCount="100" refMode="A1" iterate="false"...
def test_parse_sheet_properties():
sample = b'</bookViews><sheets><sheet name="Sheet1" sheetId="1" state="visible" r:id="rId2"/><sheet name="Sheet2" sheetId="2" state="visible" r:id="rId3"/><sheet name="Sheet3" sheetId="3" state="visible" r:id="rId4"/></sheets><calcPr iterateCount="100" refMode="A1" iterate="false" iterateDelta="0.001"/>' proper...
Version appName="Calc"/><workbookPr backupFile="false" showObjects="all" date1904="false"/><workbookProtection/>' properties = parse_book_properties(sample) eq_(properties, {"date1904": False, "sheets": []}) def test_parse_sheet_properties():
64
64
143
6
58
mobanbot/pyexcel-xlsxr
tests/test_messy_xlsx.py
Python
test_parse_sheet_properties
test_parse_sheet_properties
143
146
143
143
6525f8c63d03aa97bf735c8c25da228518fc5756
bigcode/the-stack
train
76e7241d33193878f914047a
train
class
class Site(OpinionSite): def __init__(self): super(Site, self).__init__() self.court_id = self.__module__ self.url = 'http://court-url.gov/some-path.html' # Complete this variable if you create a backscraper. self.back_scrape_iterable = None # if a POST, use these tw...
class Site(OpinionSite):
def __init__(self): super(Site, self).__init__() self.court_id = self.__module__ self.url = 'http://court-url.gov/some-path.html' # Complete this variable if you create a backscraper. self.back_scrape_iterable = None # if a POST, use these two attributes, otherwise, ...
"""Scraper for [Full name of court] CourtID: [unique abbreviation to be used by software/filesystem] Court Short Name: [standard abbreviation used in citations] Author: Reviewer: History: YYYY-MM-DD: Created by XXX """ from datetime import datetime from lxml import html from juriscraper.OpinionSite import OpinionSi...
90
256
1,731
6
83
brianwc/juriscraper
opinions/opinion_template.py
Python
Site
Site
17
241
17
17
86995982a3969a68c2cbc4c9dead7e3383cd142b
bigcode/the-stack
train
9c70e1675c2ad328f5152b5d
train
function
def write_credentials_file(sub_id, token): folder = os.path.dirname(__file__) path = os.path.join(folder, 'credentials_real.json') credentials = { 'subscriptionid': sub_id, 'authorization_header': 'Bearer {}'.format(token), } with open(path, 'w') as f: f.write(json.dumps(cre...
def write_credentials_file(sub_id, token):
folder = os.path.dirname(__file__) path = os.path.join(folder, 'credentials_real.json') credentials = { 'subscriptionid': sub_id, 'authorization_header': 'Bearer {}'.format(token), } with open(path, 'w') as f: f.write(json.dumps(credentials)) return path
# print('tenants: {}'.format(tenants)) # subs = get_subscription_ids(auth_header) # print('subs: {}'.format(subs)) # for now just ask the user to type it return input('Enter subscription id:') def write_credentials_file(sub_id, token):
63
64
78
9
55
HydAu/AzureSDKForPython
azure-common/testutils/create_credentials_file.py
Python
write_credentials_file
write_credentials_file
79
90
79
79
f99c228784c605c5d92f5ad9b28417fe4d3a8739
bigcode/the-stack
train
db84eba004e2a23e9fe5100a
train
function
def choose_subscription(auth_header): # TODO: this doesn't work, we'll need ADAL for this # tenants = get_tenant_ids(auth_header) # print('tenants: {}'.format(tenants)) # subs = get_subscription_ids(auth_header) # print('subs: {}'.format(subs)) # for now just ask the user to type it return...
def choose_subscription(auth_header): # TODO: this doesn't work, we'll need ADAL for this # tenants = get_tenant_ids(auth_header) # print('tenants: {}'.format(tenants)) # subs = get_subscription_ids(auth_header) # print('subs: {}'.format(subs)) # for now just ask the user to type it
return input('Enter subscription id:')
def choose_subscription(auth_header): # TODO: this doesn't work, we'll need ADAL for this # tenants = get_tenant_ids(auth_header) # print('tenants: {}'.format(tenants)) # subs = get_subscription_ids(auth_header) # print('subs: {}'.format(subs)) # for now just ask the user to type it
78
64
86
78
0
HydAu/AzureSDKForPython
azure-common/testutils/create_credentials_file.py
Python
choose_subscription
choose_subscription
67
76
67
75
a17184e1b7a7a64b29bcbcf6180d6d770d634179
bigcode/the-stack
train
6533287c18f77abade40e2b8
train
function
def get_tenant_ids(auth_header): response = requests.get( "{}/tenants?api-version={}".format(front_url, front_api_version), headers={ 'Authorization': auth_header, } ).json() ids = [item['tenantId'] for item in response['value']] return ids
def get_tenant_ids(auth_header):
response = requests.get( "{}/tenants?api-version={}".format(front_url, front_api_version), headers={ 'Authorization': auth_header, } ).json() ids = [item['tenantId'] for item in response['value']] return ids
'password': password, 'resource': resource, } response = requests.post(token_url, data=payload).json() return response['access_token'] front_url = "https://management.azure.com" front_api_version = "2014-01-01" def get_tenant_ids(auth_header):
64
64
68
8
56
HydAu/AzureSDKForPython
azure-common/testutils/create_credentials_file.py
Python
get_tenant_ids
get_tenant_ids
43
52
43
43
bbfb9a9e33204447c65f55160f9e2398f91573fd
bigcode/the-stack
train
9649849694d2a45c95265626
train
function
def get_subscription_ids(auth_header): response = requests.get( "{}/subscriptions?api-version={}".format(front_url, front_api_version), headers={ 'Authorization': auth_header, } ).json() ids = [item['subscriptionId'] for item in response['value']] return ids
def get_subscription_ids(auth_header):
response = requests.get( "{}/subscriptions?api-version={}".format(front_url, front_api_version), headers={ 'Authorization': auth_header, } ).json() ids = [item['subscriptionId'] for item in response['value']] return ids
requests.get( "{}/tenants?api-version={}".format(front_url, front_api_version), headers={ 'Authorization': auth_header, } ).json() ids = [item['tenantId'] for item in response['value']] return ids def get_subscription_ids(auth_header):
64
64
66
7
56
HydAu/AzureSDKForPython
azure-common/testutils/create_credentials_file.py
Python
get_subscription_ids
get_subscription_ids
55
64
55
55
c19bd49403cc05759f236463c60425c2e559f864
bigcode/the-stack
train
f13525890859c026156427ab
train
function
def get_token(username, password): # the client id we can borrow from azure xplat cli client_id = '04b07795-8ddb-461a-bbee-02f9e1bf7b46' grant_type = 'password' resource = 'https://management.core.windows.net/' token_url = 'https://login.windows.net/common/oauth2/token' payload = { 'gr...
def get_token(username, password): # the client id we can borrow from azure xplat cli
client_id = '04b07795-8ddb-461a-bbee-02f9e1bf7b46' grant_type = 'password' resource = 'https://management.core.windows.net/' token_url = 'https://login.windows.net/common/oauth2/token' payload = { 'grant_type': grant_type, 'client_id': client_id, 'username': username, ...
you to create a new # password on first login. import argparse import json import os.path import requests import getpass try: input = raw_input except: pass def get_token(username, password): # the client id we can borrow from azure xplat cli
64
64
144
22
41
HydAu/AzureSDKForPython
azure-common/testutils/create_credentials_file.py
Python
get_token
get_token
22
37
22
23
8d122299d653c28b32532367ea28bd6f8816f26e
bigcode/the-stack
train
6aaa1ab9f61ce9a44f8a47b7
train
class
class MyOp(Op): def __init__(self, name, dmap=None, x=None): self.name = name if dmap is None: dmap = {} self.destroy_map = dmap self.x = x def make_node(self, *inputs): inputs = list(map(as_variable, inputs)) for input in inputs: if not ...
class MyOp(Op):
def __init__(self, name, dmap=None, x=None): self.name = name if dmap is None: dmap = {} self.destroy_map = dmap self.x = x def make_node(self, *inputs): inputs = list(map(as_variable, inputs)) for input in inputs: if not isinstance(input....
("not a Variable", x) return x class MyType(Type): def filter(self, data): return data def __eq__(self, other): return isinstance(other, MyType) def __hash__(self): return hash(MyType) def MyVariable(name): return Variable(MyType(), None, None, name=name) class MyOp(Op...
80
80
267
5
75
intel/Theano-dev
theano/gof/tests/test_opt.py
Python
MyOp
MyOp
37
70
37
38
c3dc8f4067c0e8235ee6c3dfd31dbb67c5bd2940
bigcode/the-stack
train
616f9023b87a31dd5243ef66
train
function
def as_variable(x): if not isinstance(x, Variable): raise TypeError("not a Variable", x) return x
def as_variable(x):
if not isinstance(x, Variable): raise TypeError("not a Variable", x) return x
Optimizer, PatternSub, TopoOptimizer, OpSub, MergeOptimizer, config, theano, EquilibriumOptimizer, logging, pre_constant_merge, pre_greedy_local_optimizer) from theano.gof.fg import FunctionGraph from theano import tensor as T def as_v...
64
64
28
5
58
intel/Theano-dev
theano/gof/tests/test_opt.py
Python
as_variable
as_variable
15
18
15
15
c05abb11958b4bb25d89d6fcd875c914dee17511
bigcode/the-stack
train
35808539f0e8a4e1747da9f1
train
function
def PatternOptimizer(p1, p2, ign=False): return OpKeyOptimizer(PatternSub(p1, p2), ignore_newtrees=ign)
def PatternOptimizer(p1, p2, ign=False):
return OpKeyOptimizer(PatternSub(p1, p2), ignore_newtrees=ign)
x=1) op_z = MyOp('OpZ', x=1) def inputs(): x = MyVariable('x') y = MyVariable('y') z = MyVariable('z') return x, y, z def PatternOptimizer(p1, p2, ign=False):
64
64
32
12
51
intel/Theano-dev
theano/gof/tests/test_opt.py
Python
PatternOptimizer
PatternOptimizer
92
93
92
92
10d067373e2ca063a5e2406e4a43601aba1dd2bb
bigcode/the-stack
train
29387ee4a9110193aaf92a28
train
function
def MyVariable(name): return Variable(MyType(), None, None, name=name)
def MyVariable(name):
return Variable(MyType(), None, None, name=name)
TypeError("not a Variable", x) return x class MyType(Type): def filter(self, data): return data def __eq__(self, other): return isinstance(other, MyType) def __hash__(self): return hash(MyType) def MyVariable(name):
64
64
18
5
59
intel/Theano-dev
theano/gof/tests/test_opt.py
Python
MyVariable
MyVariable
33
34
33
33
e359d8adf94756a87c0b93275ff82e3a28f0e387
bigcode/the-stack
train
e23672061a8ec612f3d48c7a
train
class
class TestPatternOptimizer: def test_replace_output(self): # replacing the whole graph x, y, z = inputs() e = op1(op2(x, y), z) g = FunctionGraph([x, y, z], [e]) PatternOptimizer((op1, (op2, '1', '2'), '3'), (op4, '3', '2')).optimize(g) asser...
class TestPatternOptimizer:
def test_replace_output(self): # replacing the whole graph x, y, z = inputs() e = op1(op2(x, y), z) g = FunctionGraph([x, y, z], [e]) PatternOptimizer((op1, (op2, '1', '2'), '3'), (op4, '3', '2')).optimize(g) assert str(g) == "[Op4(z, y)]" ...
return rval def __hash__(self): # return hash(self.x if self.x is not None else id(self)) ^ hash(self.name) if self.x is not None: return hash(self.x) else: return id(self) op1 = MyOp('Op1') op2 = MyOp('Op2') op3 = MyOp('Op3') op4 = MyOp('Op4') op5 = MyOp('...
256
256
1,899
5
251
intel/Theano-dev
theano/gof/tests/test_opt.py
Python
TestPatternOptimizer
TestPatternOptimizer
100
264
100
101
a35a135daa5ba23ad7971fa6a6ade87e23ab5946
bigcode/the-stack
train