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
39f83d666b38d259d16eb542
train
function
def onehist(x,xlabel='',fontsize=12): """ Script that plots the histogram of x with the corresponding xlabel. """ pylab.clf() pylab.rcParams.update({'font.size': fontsize}) pylab.hist(x,histtype='stepfilled') pylab.legend() #### Change the X-axis appropriately #### pylab.xlabel(xlabel) pylab.ylabel('Number'...
def onehist(x,xlabel='',fontsize=12):
""" Script that plots the histogram of x with the corresponding xlabel. """ pylab.clf() pylab.rcParams.update({'font.size': fontsize}) pylab.hist(x,histtype='stepfilled') pylab.legend() #### Change the X-axis appropriately #### pylab.xlabel(xlabel) pylab.ylabel('Number') pylab.draw() pylab.show()
as a pyplot object or plot it on the screen :param param: grmonty spectrum file """ s = sed.SED() s.grmonty(spec) pylab.plot(s.lognu, s.ll) pylab.show() def onehist(x,xlabel='',fontsize=12):
62
64
97
11
51
rsnemmen/nemmen
nmmn/plots.py
Python
onehist
onehist
26
39
26
26
6cd3627e1ea66254ca6bb606e2fa4b9c7420d383
bigcode/the-stack
train
c82d2844aa04e5cd8adb4a44
train
function
def symlog(x, C=1./numpy.log(10.)): """ Applies a modified logarithm function to x that handles negative values while maintaining continuity across zero. This function solves a very concrete problem: how to handle data that spans a huge range and has also negative values? log10 will fail. This is the answer. The t...
def symlog(x, C=1./numpy.log(10.)):
""" Applies a modified logarithm function to x that handles negative values while maintaining continuity across zero. This function solves a very concrete problem: how to handle data that spans a huge range and has also negative values? log10 will fail. This is the answer. The transformation is defined in an artic...
ysd[0]],'k--') # -1sd histy.plot([xax[0],xax[1]],[ysd[-1],ysd[-1]],'k--') # +1sd def symlog(x, C=1./numpy.log(10.)):
64
64
203
16
47
rsnemmen/nemmen
nmmn/plots.py
Python
symlog
symlog
953
972
953
953
d7ef8c8bff60a41240fb0e7c88f75a1c2c311804
bigcode/the-stack
train
8205e0f3d43aaae2cc388845
train
function
def fourcumplot(x1,x2,x3,x4,xmin,xmax,x1leg='$x_1$',x2leg='$x_2$',x3leg='$x_3$',x4leg='$x_3$',xlabel='',ylabel='$N(x>x\')$',fig=1,sharey=False,fontsize=12,bins1=50,bins2=50,bins3=50,bins4=50): """ Script that plots the cumulative histograms of four variables x1, x2, x3 and x4 sharing the same X-axis. For each bin, Y i...
def fourcumplot(x1,x2,x3,x4,xmin,xmax,x1leg='$x_1$',x2leg='$x_2$',x3leg='$x_3$',x4leg='$x_3$',xlabel='',ylabel='$N(x>x\')$',fig=1,sharey=False,fontsize=12,bins1=50,bins2=50,bins3=50,bins4=50):
""" Script that plots the cumulative histograms of four variables x1, x2, x3 and x4 sharing the same X-axis. For each bin, Y is the fraction of the sample with values above X. Arguments: - x1,x2,x3,x4: arrays with data to be plotted - xmin,xmax: lower and upper range of plotted values, will be used to set a consist...
') d.legend(loc=loc,frameon=False) if line4!=None: vline(d,line4) if line4b!=None: vline(d,line4b,'k--') pylab.setp(a.get_xticklabels(), visible=False) pylab.setp(b.get_xticklabels(), visible=False) pylab.setp(c.get_xticklabels(), visible=False) d.set_xlabel(xlabel) c.set_ylabel('Number') pylab.minorticks_o...
212
213
713
90
122
rsnemmen/nemmen
nmmn/plots.py
Python
fourcumplot
fourcumplot
233
290
233
233
07e419887209ff72f6de69e46659cea4b019cb36
bigcode/the-stack
train
94731e14d7a47da529aa108e
train
function
def fitpred(xdata,ydata,errx,erry,covxy,nboot=1000,bces='ort',linestyle='',conf=0.68,predcolor='Khaki',xplot=None,front=False,**args): """ This is a wrapper that given the input data performs the BCES fit, get the orthogonal parameters and plot (i) the best-fit line and (ii) prediction band. I decided to put to...
def fitpred(xdata,ydata,errx,erry,covxy,nboot=1000,bces='ort',linestyle='',conf=0.68,predcolor='Khaki',xplot=None,front=False,**args):
""" This is a wrapper that given the input data performs the BCES fit, get the orthogonal parameters and plot (i) the best-fit line and (ii) prediction band. I decided to put together these commands in a method because I have been using them very frequently. Assumes you initialized the plot window before c...
predcolor,edgecolor='', zorder=zorder) # Plots confidence band lcb,ucb,xcb=confbandnl(xdata,ydata,func,fitm,covm,2,conf,x) pylab.fill_between(xcb, lcb, ucb, facecolor=confcolor,edgecolor='', zorder=zorder) return a,b,erra,errb,cov def fitpred(xdata,ydata,errx,erry,covxy,nboot=1000,bces='ort',linestyle='',conf=0...
139
139
466
50
88
rsnemmen/nemmen
nmmn/plots.py
Python
fitpred
fitpred
600
641
600
600
54fe9bd95833b43b265a37dcb40ea0992360a0d5
bigcode/the-stack
train
a4d8e82110e5caf0faa64427
train
function
def ipyplots(): """ Makes sure we have exactly the same matplotlib settings as in the IPython terminal version. Call this from IPython notebook. `Source <http://stackoverflow.com/questions/16905028/why-is-matplotlib-plot-produced-from-ipython-notebook-slightly-different-from-te)>`_. """ pylab.rcParams['figure.figs...
def ipyplots():
""" Makes sure we have exactly the same matplotlib settings as in the IPython terminal version. Call this from IPython notebook. `Source <http://stackoverflow.com/questions/16905028/why-is-matplotlib-plot-produced-from-ipython-notebook-slightly-different-from-te)>`_. """ pylab.rcParams['figure.figsize']=(8.0,6.0) ...
Usage: >>> text(x,y,s, fontsize=10) will plot the strings in array 's' at coordinates given by arrays 'x' and 'y'. """ for j in range(x.size): pylab.text(x[j],y[j],s[j], **args) def ipyplots():
64
64
147
5
59
rsnemmen/nemmen
nmmn/plots.py
Python
ipyplots
ipyplots
685
695
685
685
c7715941d3e2c59e22b52960fb0d3a3351033cf5
bigcode/the-stack
train
3c3e1e6891d660ac54afbf5a
train
function
def plot(spec): """ Returns the plot of a grmonty spectrum as a pyplot object or plot it on the screen :param param: grmonty spectrum file """ s = sed.SED() s.grmonty(spec) pylab.plot(s.lognu, s.ll) pylab.show()
def plot(spec):
""" Returns the plot of a grmonty spectrum as a pyplot object or plot it on the screen :param param: grmonty spectrum file """ s = sed.SED() s.grmonty(spec) pylab.plot(s.lognu, s.ll) pylab.show()
""" Fancy plots ============== """ import numpy from matplotlib import pylab from nmmn import sed def plot(spec):
26
64
66
4
21
rsnemmen/nemmen
nmmn/plots.py
Python
plot
plot
10
21
10
10
725879563efbd786836a26b88e543e9198b69271
bigcode/the-stack
train
0e5e50f139fa0ec7a8742961
train
function
def plotlinfit(xdata,ydata,a,b,erra,errb,cov,linestyle='',conf=0.683,confcolor='gray',xplot=None,front=False,**args): """ This is a wrapper that given the output data from a linear regression method (for example, bayeslin.pro, the Bayesian linear regression method of Kelly (2007)), it plots the fits and the confid...
def plotlinfit(xdata,ydata,a,b,erra,errb,cov,linestyle='',conf=0.683,confcolor='gray',xplot=None,front=False,**args):
""" This is a wrapper that given the output data from a linear regression method (for example, bayeslin.pro, the Bayesian linear regression method of Kelly (2007)), it plots the fits and the confidence bands. The input is: X, Y, slope (A), errA, intercept (B), errB and cov(A,B) Assumes you initialized the plo...
lcb,ucb,y=confbandmc(x,fitm,covm,10000,conf) if front==True: zorder=10 else: zorder=None pylab.fill_between(x, lcb, ucb, alpha=0.3, facecolor=confcolor, zorder=zorder) return a,b,erra,errb,cov def plotlinfit(xdata,ydata,a,b,erra,errb,cov,linestyle='',conf=0.683,confcolor='gray',xplot=None,front=False,**args)...
127
128
427
43
83
rsnemmen/nemmen
nmmn/plots.py
Python
plotlinfit
plotlinfit
454
491
454
454
d06905eb104c67ada909a8683affc1af7d23410e
bigcode/the-stack
train
62475f4abce1409ec782f13f
train
function
def threehistsx(x1,x2,x3,x1leg='$x_1$',x2leg='$x_2$',x3leg='$x_3$',fig=1,fontsize=12,bins1=10,bins2=10,bins3=10): """ Script that pretty-plots three histograms of quantities x1, x2 and x3. Arguments: :param x1,x2,x3: arrays with data to be plotted :param x1leg, x2leg, x3leg: legends for each histogram :param fig: wh...
def threehistsx(x1,x2,x3,x1leg='$x_1$',x2leg='$x_2$',x3leg='$x_3$',fig=1,fontsize=12,bins1=10,bins2=10,bins3=10):
""" Script that pretty-plots three histograms of quantities x1, x2 and x3. Arguments: :param x1,x2,x3: arrays with data to be plotted :param x1leg, x2leg, x3leg: legends for each histogram :param fig: which plot window should I use? Example: x1=Lbol(AD), x2=Lbol(JD), x3=Lbol(EHF10) >>> threehists(x1,x2,x3,38,44,'A...
(), visible=False) pylab.setp(c.get_xticklabels(), visible=False) d.set_xlabel(xlabel) c.set_ylabel(ylabel) pylab.minorticks_on() pylab.subplots_adjust(hspace=0.15) pylab.draw() pylab.show() def threehistsx(x1,x2,x3,x1leg='$x_1$',x2leg='$x_2$',x3leg='$x_3$',fig=1,fontsize=12,bins1=10,bins2=10,bins3=10):
117
118
396
58
59
rsnemmen/nemmen
nmmn/plots.py
Python
threehistsx
threehistsx
298
333
298
298
ff8fdf2f96b77c1d507e33a7cc00febf3b73a245
bigcode/the-stack
train
285208be98cf4354206b1069
train
function
def turbocmap(): """ Returns the Turbo colormap: an improved version of the awful jet colormap. The look-up table contains 256 entries. Each entry is a floating point sRGB triplet. Usage: >>> turbo=nmmn.plots.turbocmap() >>> imshow(rho, cmap=turbo) Copyright 2019 Google LLC. SPDX-License-Identifier: Apache-...
def turbocmap():
""" Returns the Turbo colormap: an improved version of the awful jet colormap. The look-up table contains 256 entries. Each entry is a floating point sRGB triplet. Usage: >>> turbo=nmmn.plots.turbocmap() >>> imshow(rho, cmap=turbo) Copyright 2019 Google LLC. SPDX-License-Identifier: Apache-2.0 Author: Anto...
.240347619], [0.9990428571, 0.7653142857, 0.2164142857], [0.9955333333, 0.7860571429, 0.196652381], [0.988, 0.8066, 0.1793666667], [0.9788571429, 0.8271428571, 0.1633142857], [0.9697, 0.8481380952, 0.147452381], [0.9625857143, 0.8705142857, 0.1309], [0.9588714286, 0.8949, 0.1132428571], [0.9598238095, 0.92...
256
256
4,046
5
251
rsnemmen/nemmen
nmmn/plots.py
Python
turbocmap
turbocmap
838
862
838
838
4845134b302e18d1d3637bb0a3f24c7c3167d801
bigcode/the-stack
train
7e0bfaa252243f4fcd89e63f
train
function
def wolframcmap(): """ Returns colormap that matches closely the one used by default for images in Wolfram Mathematica 11 (dark blue to orange). I spent one hour playing around to reproduce it. Usage: >>> mycmap=nmmn.plots.wolframcmap() >>> imshow(rho, cmap=mycmap) .. figure:: ../figures/wolframcmap.png :scale: 1...
def wolframcmap():
""" Returns colormap that matches closely the one used by default for images in Wolfram Mathematica 11 (dark blue to orange). I spent one hour playing around to reproduce it. Usage: >>> mycmap=nmmn.plots.wolframcmap() >>> imshow(rho, cmap=mycmap) .. figure:: ../figures/wolframcmap.png :scale: 100 % :alt: Image p...
[-1]], cmap=my_cmap) pylab.axes().set_aspect('equal') colorbar() circle2=Circle((0,0),1,color='k') gca().add_artist(circle2) savefig('tmp.png',transparent=True,dpi=150) def wolframcmap():
64
64
198
6
58
rsnemmen/nemmen
nmmn/plots.py
Python
wolframcmap
wolframcmap
752
774
752
752
15268f89360d8b8ba75c1be41494ac504160da06
bigcode/the-stack
train
2f260f53b804d7f5388fec6b
train
function
def fitconfmc(xdata,ydata,errx,erry,covxy,nboot=1000,bcesMethod='ort',linestyle='',conf=1.,confcolor='gray',xplot=None,front=False,**args): """ This is a wrapper that given the input data performs the BCES fit, get the orthogonal parameters and plot the best-fit line and confidence band (generated using MC). I deci...
def fitconfmc(xdata,ydata,errx,erry,covxy,nboot=1000,bcesMethod='ort',linestyle='',conf=1.,confcolor='gray',xplot=None,front=False,**args):
""" This is a wrapper that given the input data performs the BCES fit, get the orthogonal parameters and plot the best-fit line and confidence band (generated using MC). I decided to put together these commands in a method because I have been using them very frequently. Assumes you initialized the plot window ...
def func(x): return x[1]*x[0]+x[2] # Plots confidence band lcb,ucb,xcb=stats.confbandnl(xdata,ydata,func,fitm,covm,2,conf,x) if front==True: zorder=10 else: zorder=None pylab.fill_between(xcb, lcb, ucb, alpha=0.3, facecolor=confcolor, zorder=zorder) return a,b,erra,errb,cov def fitconfmc(xdata,ydata,errx...
166
166
556
49
116
rsnemmen/nemmen
nmmn/plots.py
Python
fitconfmc
fitconfmc
394
443
394
394
fed3c36f31ef9b0036a6ed6e0f6c0912097656bf
bigcode/the-stack
train
1129162859eebbf8bcb29590
train
function
def fourhists(x1,x2,x3,x4,xmin,xmax,x1leg='$x_1$',x2leg='$x_2$',x3leg='$x_3$',x4leg='$x_3$',xlabel='',fig=1,sharey=False,fontsize=12,bins1=10,bins2=10,bins3=10,bins4=10,line1=None,line2=None,line3=None,line4=None,line1b=None,line2b=None,line3b=None,line4b=None,loc='best'): """ Script that plots four histograms of quan...
def fourhists(x1,x2,x3,x4,xmin,xmax,x1leg='$x_1$',x2leg='$x_2$',x3leg='$x_3$',x4leg='$x_3$',xlabel='',fig=1,sharey=False,fontsize=12,bins1=10,bins2=10,bins3=10,bins4=10,line1=None,line2=None,line3=None,line4=None,line1b=None,line2b=None,line3b=None,line4b=None,loc='best'):
""" Script that plots four histograms of quantities x1, x2, x3 and x4 sharing the same X-axis. Arguments: - x1,x2,x3,x4: arrays with data to be plotted - xmin,xmax: lower and upper range of plotted values, will be used to set a consistent x-range or both histograms. - x1leg, x2leg, x3leg, x4leg: legends for each his...
',frameon=False) a.set_xlim(xmin,xmax) b.hist(x2,label=x2leg,color='r',histtype='stepfilled') b.legend(loc='best',frameon=False) c.hist(x3,label=x3leg,color='y',histtype='stepfilled') c.legend(loc='best',frameon=False) pylab.setp(a.get_xticklabels(), visible=False) pylab.setp(b.get_xticklabels(), visible=Fa...
253
256
907
114
139
rsnemmen/nemmen
nmmn/plots.py
Python
fourhists
fourhists
151
226
151
151
18018076b60554a89ca82774aa18061326751542
bigcode/the-stack
train
5ff9863628a6fcc9825d8baf
train
function
def twohists(x1,x2,xmin,xmax,range=None,x1leg='$x_1$',x2leg='$x_2$',xlabel='',fig=1,sharey=False,fontsize=12,bins1=10,bins2=10): """ Script that plots two histograms of quantities x1 and x2 sharing the same X-axis. :param x1,x2: arrays with data to be plotted :param xmin,xmax: lower and upper range of plotted values,...
def twohists(x1,x2,xmin,xmax,range=None,x1leg='$x_1$',x2leg='$x_2$',xlabel='',fig=1,sharey=False,fontsize=12,bins1=10,bins2=10):
""" Script that plots two histograms of quantities x1 and x2 sharing the same X-axis. :param x1,x2: arrays with data to be plotted :param xmin,xmax: lower and upper range of plotted values, will be used to set a consistent x-range for both histograms. :param x1leg, x2leg: legends for each histogram :param xlabel: s...
of x with the corresponding xlabel. """ pylab.clf() pylab.rcParams.update({'font.size': fontsize}) pylab.hist(x,histtype='stepfilled') pylab.legend() #### Change the X-axis appropriately #### pylab.xlabel(xlabel) pylab.ylabel('Number') pylab.draw() pylab.show() def twohists(x1,x2,xmin,xmax,range=None,x1leg...
133
134
449
55
78
rsnemmen/nemmen
nmmn/plots.py
Python
twohists
twohists
45
87
45
45
275769c81039f7e7715363690a3e6e05529383f5
bigcode/the-stack
train
82b3ea095f36987e12d12d57
train
function
def uerrorbar(ux,uy,**args): """ Adaptation of pylab.errorbar to work with arrays defined using the uncertainties package, which include the errorbars built-in. Usage: >>> uerrorbar(x,y,fmt='o') will plot the points and error bars associated with the 'unumpy' arrays x and y """ x=unumpy.nominal_values(ux) y=unu...
def uerrorbar(ux,uy,**args):
""" Adaptation of pylab.errorbar to work with arrays defined using the uncertainties package, which include the errorbars built-in. Usage: >>> uerrorbar(x,y,fmt='o') will plot the points and error bars associated with the 'unumpy' arrays x and y """ x=unumpy.nominal_values(ux) y=unumpy.nominal_values(uy) errx=...
fitm,covm,2,conf,x) pylab.fill_between(xpb, lpb, upb, facecolor=predcolor,edgecolor='', zorder=zorder) return a,b,erra,errb,cov def uerrorbar(ux,uy,**args):
64
64
140
12
51
rsnemmen/nemmen
nmmn/plots.py
Python
uerrorbar
uerrorbar
648
665
648
648
9584efc09a7fc22d7fce702c6120b7fa67cea7cc
bigcode/the-stack
train
9d2036e51e9347405b27441b
train
function
def parulacmap(): """ Creates the beautiful Parula colormap which is Matlab's default. Usage: >>> mycmap=nmmn.plots.parulacmap() >>> imshow(rho, cmap=mycmap) Code taken from `here <https://github.com/BIDS/colormap/blob/master/parula.py>`_ """ from matplotlib.colors import LinearSegmentedColormap cm_data = ...
def parulacmap():
""" Creates the beautiful Parula colormap which is Matlab's default. Usage: >>> mycmap=nmmn.plots.parulacmap() >>> imshow(rho, cmap=mycmap) Code taken from `here <https://github.com/BIDS/colormap/blob/master/parula.py>`_ """ from matplotlib.colors import LinearSegmentedColormap cm_data = [[0.2081, 0.1663, ...
) pylab.axes().set_aspect('equal') colorbar() circle2=Circle((0,0),1,color='k') gca().add_artist(circle2) savefig('tmp.png',transparent=True,dpi=150) def wolframcmap(): """ Returns colormap that matches closely the one used by default for images in Wolfram Mathematica 11 (dark blue to orange). I spent one ho...
255
256
1,652
6
249
rsnemmen/nemmen
nmmn/plots.py
Python
parulacmap
parulacmap
780
835
780
780
b65be7e9eada1768e3326e205b6b552b3c1f2ccf
bigcode/the-stack
train
6a017d3cf270652d7c2de12c
train
function
def jointplot(X,Y,xlabel=None,ylabel=None,binsim=40,binsh=20,contour=True): """ Plots the joint distribution of posteriors for X1 and X2, including the 1D histograms showing the median and standard deviations. The work that went in creating this nice method is shown, step by step, in the ipython notebook "error cont...
def jointplot(X,Y,xlabel=None,ylabel=None,binsim=40,binsh=20,contour=True):
""" Plots the joint distribution of posteriors for X1 and X2, including the 1D histograms showing the median and standard deviations. The work that went in creating this nice method is shown, step by step, in the ipython notebook "error contours.ipynb". Sources of inspiration: - http://python4mpia.github.io/intro/q...
.07902,0.00408],[0.64223,0.07380,0.00401],[0.63082,0.06868,0.00401],[0.61923,0.06367,0.00410],[0.60746,0.05878,0.00427],[0.59550,0.05399,0.00453],[0.58336,0.04931,0.00486],[0.57103,0.04474,0.00529],[0.55852,0.04028,0.00579],[0.54583,0.03593,0.00638],[0.53295,0.03169,0.00705],[0.51989,0.02756,0.00780],[0.50664,0.02354,0...
255
256
1,113
26
229
rsnemmen/nemmen
nmmn/plots.py
Python
jointplot
jointplot
874
948
874
874
32ed0caf132dd79047ab997d44b19814a65da958
bigcode/the-stack
train
cae127b297a75dbc42782d52
train
function
def image(Z,xnew,ynew,my_cmap=None,aspect='equal'): """ Creates pretty image. You need to specify: """ imshow(log10(Z),extent=[xnew[0],xnew[-1],ynew[0],ynew[-1]], cmap=my_cmap) pylab.axes().set_aspect('equal') colorbar() circle2=Circle((0,0),1,color='k') gca().add_artist(circle2) savefig('tmp.png',transparent=T...
def image(Z,xnew,ynew,my_cmap=None,aspect='equal'):
""" Creates pretty image. You need to specify: """ imshow(log10(Z),extent=[xnew[0],xnew[-1],ynew[0],ynew[-1]], cmap=my_cmap) pylab.axes().set_aspect('equal') colorbar() circle2=Circle((0,0),1,color='k') gca().add_artist(circle2) savefig('tmp.png',transparent=True,dpi=150)
1], color[1])) cdict['blue'].append((pos, color[2], color[2])) cmap = mpl.colors.LinearSegmentedColormap('my_colormap',cdict,256) return cmap def image(Z,xnew,ynew,my_cmap=None,aspect='equal'):
64
64
112
16
47
rsnemmen/nemmen
nmmn/plots.py
Python
image
image
738
747
738
738
0158723cd0060e58972da62d2ca41c36d36659fe
bigcode/the-stack
train
fdc7c8f74ae0d77d57588b9f
train
function
def fitconf(xdata,ydata,errx,erry,covxy,nboot=1000,bcesMethod='ort',linestyle='',conf=0.683,confcolor='gray',xplot=None,front=False,**args): """ This is a wrapper that given the input data performs the BCES fit, get the orthogonal parameters and plot the best-fit line and confidence band (generated using analytical...
def fitconf(xdata,ydata,errx,erry,covxy,nboot=1000,bcesMethod='ort',linestyle='',conf=0.683,confcolor='gray',xplot=None,front=False,**args):
""" This is a wrapper that given the input data performs the BCES fit, get the orthogonal parameters and plot the best-fit line and confidence band (generated using analytical methods). I decided to put together these commands in a method because I have been using them very frequently. Assumes you initialized ...
ylab.subplot(3,1,2) pylab.hist(x2,label=x2leg,color='r',bins=bins2) pylab.legend(loc='best',frameon=False) pylab.subplot(3,1,3) pylab.hist(x3,label=x3leg,color='y',bins=bins3) pylab.legend(loc='best',frameon=False) pylab.minorticks_on() pylab.subplots_adjust(hspace=0.15) pylab.draw() pylab.show() def fitconf...
163
165
551
50
113
rsnemmen/nemmen
nmmn/plots.py
Python
fitconf
fitconf
339
388
339
339
ebba5b3c1f858361a8d1b53a4ff355105a159d19
bigcode/the-stack
train
a5c2ebd6c1ea2711a9c3e788
train
function
def make_cmap(colors, position=None, bit=False): ''' make_cmap takes a list of tuples which contain RGB values. The RGB values may either be in 8-bit [0 to 255] (in which bit must be set to True when called) or arithmetic [0 to 1] (default). make_cmap returns a cmap with equally spaced colors. A...
def make_cmap(colors, position=None, bit=False):
''' make_cmap takes a list of tuples which contain RGB values. The RGB values may either be in 8-bit [0 to 255] (in which bit must be set to True when called) or arithmetic [0 to 1] (default). make_cmap returns a cmap with equally spaced colors. Arrange your tuples so that the first color is the...
http://stackoverflow.com/questions/16905028/why-is-matplotlib-plot-produced-from-ipython-notebook-slightly-different-from-te)>`_. """ pylab.rcParams['figure.figsize']=(8.0,6.0) #(6.0,4.0) pylab.rcParams['font.size']=12 #10 pylab.rcParams['savefig.dpi']=100 #72 pylab.rcParams['figure...
124
124
415
12
111
rsnemmen/nemmen
nmmn/plots.py
Python
make_cmap
make_cmap
700
735
700
700
922e5ad81cf45107a63c9f57020e43f13c50b37d
bigcode/the-stack
train
0efe8779acd9a52f7fc45b4b
train
function
def jh(xdata,ydata,errx,erry,covxy,nboot=1000,bces='ort',linestyle='',conf=0.683,confcolor='gray',xplot=None,front=False,**args): """ This is a wrapper that given the input data performs the BCES fit, get the orthogonal parameters, best-fit line and confidence band. Then returns the points corresponding to the line...
def jh(xdata,ydata,errx,erry,covxy,nboot=1000,bces='ort',linestyle='',conf=0.683,confcolor='gray',xplot=None,front=False,**args):
""" This is a wrapper that given the input data performs the BCES fit, get the orthogonal parameters, best-fit line and confidence band. Then returns the points corresponding to the line and confidence band. I wrote this for the John Hunter plotting contest, in order to simplify my AGN-GRB plot. Inherited from...
0]+x[2] # Plots confidence band lcb,ucb,xcb=confbandnl(xdata,ydata,func,fitm,covm,2,conf,x) if front==True: zorder=10 else: zorder=None pylab.fill_between(xcb, lcb, ucb, alpha=0.3, facecolor=confcolor, zorder=zorder) def jh(xdata,ydata,errx,erry,covxy,nboot=1000,bces='ort',linestyle='',conf=0.683,confcolor='g...
140
142
476
49
91
rsnemmen/nemmen
nmmn/plots.py
Python
jh
jh
497
539
497
497
8e523a40a39bc3e19facdc416f3ff22b4ccda685
bigcode/the-stack
train
21044d702c3087e633021222
train
function
def threehists(x1,x2,x3,xmin,xmax,x1leg='$x_1$',x2leg='$x_2$',x3leg='$x_3$',xlabel='',fig=1,sharey=False,fontsize=12): """ Script that plots three histograms of quantities x1, x2 and x3 sharing the same X-axis. Arguments: - x1,x2,x3: arrays with data to be plotted - xmin,xmax: lower and upper range of plotted values...
def threehists(x1,x2,x3,xmin,xmax,x1leg='$x_1$',x2leg='$x_2$',x3leg='$x_3$',xlabel='',fig=1,sharey=False,fontsize=12):
""" Script that plots three histograms of quantities x1, x2 and x3 sharing the same X-axis. Arguments: - x1,x2,x3: arrays with data to be plotted - xmin,xmax: lower and upper range of plotted values, will be used to set a consistent x-range for both histograms. - x1leg, x2leg, x3leg: legends for each histogram - xl...
.legend(loc='best',frameon=False) a.set_xlim(xmin,xmax) b.hist(x2,bins2,label=x2leg,color='r',histtype='stepfilled',range=range) b.legend(loc='best',frameon=False) pylab.setp(a.get_xticklabels(), visible=False) b.set_xlabel(xlabel) b.set_ylabel('Number',verticalalignment='bottom') pylab.minorticks_on() pyl...
166
167
557
52
114
rsnemmen/nemmen
nmmn/plots.py
Python
threehists
threehists
93
143
93
93
fe767085ec21de3baf122fc0da02d8b94bb47ec0
bigcode/the-stack
train
b51044aa81745a1c231aa331
train
function
def fitconfpred(xdata,ydata,errx,erry,covxy,nboot=1000,bces='ort',linestyle='',conf=0.68,confcolor='LightGrey',predcolor='Khaki',xplot=None,front=False,**args): """ This is a wrapper that given the input data performs the BCES fit, get the orthogonal parameters and plot (i) the best-fit line, (ii) confidence band a...
def fitconfpred(xdata,ydata,errx,erry,covxy,nboot=1000,bces='ort',linestyle='',conf=0.68,confcolor='LightGrey',predcolor='Khaki',xplot=None,front=False,**args):
""" This is a wrapper that given the input data performs the BCES fit, get the orthogonal parameters and plot (i) the best-fit line, (ii) confidence band and (iii) prediction band. I decided to put together these commands in a method because I have been using them very frequently. Assumes you initialized t...
# array with best-fit parameters covm=numpy.array([ (erra[i]**2,cov[i]), (cov[i],errb[i]**2) ]) # covariance matrix def func(x): return x[1]*x[0]+x[2] # Plots confidence band lcb,ucb,xcb=confbandnl(xdata,ydata,func,fitm,covm,2,conf,x) return x,y,lcb,ucb def fitconfpred(xdata,ydata,errx,erry,covxy,nboot=1000,bce...
162
163
544
57
104
rsnemmen/nemmen
nmmn/plots.py
Python
fitconfpred
fitconfpred
550
595
550
550
c43f88e7ea5a5c1c2917568f5869c63b8f1db3d5
bigcode/the-stack
train
8260c5913221e88ff0dcaa03
train
function
def text(x,y,s,**args): """ Version of pylab.text that can be applied to arrays. Usage: >>> text(x,y,s, fontsize=10) will plot the strings in array 's' at coordinates given by arrays 'x' and 'y'. """ for j in range(x.size): pylab.text(x[j],y[j],s[j], **args)
def text(x,y,s,**args):
""" Version of pylab.text that can be applied to arrays. Usage: >>> text(x,y,s, fontsize=10) will plot the strings in array 's' at coordinates given by arrays 'x' and 'y'. """ for j in range(x.size): pylab.text(x[j],y[j],s[j], **args)
ux) y=unumpy.nominal_values(uy) errx=unumpy.std_devs(ux) erry=unumpy.std_devs(uy) pylab.errorbar(x,y,xerr=errx,yerr=erry,**args) def text(x,y,s,**args):
64
64
82
9
55
rsnemmen/nemmen
nmmn/plots.py
Python
text
text
669
681
669
669
bde6045ddd78742468a55d2a75cea00b87064b5d
bigcode/the-stack
train
819ef48e8368641399274677
train
class
class LookbackEventSequenceEncoderDecoderTest(tf.test.TestCase): def setUp(self): self.enc = encoder_decoder.LookbackEventSequenceEncoderDecoder( testing_lib.TrivialOneHotEncoding(3, num_steps=range(3)), [1, 2], 2) def testInputSize(self): self.assertEqual(13, self.enc.input_size) def testNumCl...
class LookbackEventSequenceEncoderDecoderTest(tf.test.TestCase):
def setUp(self): self.enc = encoder_decoder.LookbackEventSequenceEncoderDecoder( testing_lib.TrivialOneHotEncoding(3, num_steps=range(3)), [1, 2], 2) def testInputSize(self): self.assertEqual(13, self.enc.input_size) def testNumClasses(self): self.assertEqual(5, self.enc.num_classes) def ...
1, 0, 2, 0] sequence_example = self.enc.encode(events) expected_inputs = [[0], [1], [0], [2]] expected_labels = [1, 0, 2, 0] expected_sequence_example = sequence_example_lib.make_sequence_example( expected_inputs, expected_labels) self.assertEqual(sequence_example, expected_sequence_example)...
256
256
1,891
13
243
Rancerle/Clarkson_Magenta
magenta/music/encoder_decoder_test.py
Python
LookbackEventSequenceEncoderDecoderTest
LookbackEventSequenceEncoderDecoderTest
164
276
164
165
617a9dcaa70d8f9485f2e2f26195fe741a790166
bigcode/the-stack
train
a50e25a067620f8d7c987b5e
train
class
class OptionalEventSequenceEncoderTest(tf.test.TestCase): def setUp(self): self.enc = encoder_decoder.OptionalEventSequenceEncoder( encoder_decoder.OneHotEventSequenceEncoderDecoder( testing_lib.TrivialOneHotEncoding(3))) def testInputSize(self): self.assertEquals(4, self.enc.input_siz...
class OptionalEventSequenceEncoderTest(tf.test.TestCase):
def setUp(self): self.enc = encoder_decoder.OptionalEventSequenceEncoder( encoder_decoder.OneHotEventSequenceEncoderDecoder( testing_lib.TrivialOneHotEncoding(3))) def testInputSize(self): self.assertEquals(4, self.enc.input_size) def testEventsToInput(self): events = [(False, 0)...
, 0.4], [0.0, 0.4, 0.6]]] p = self.enc.evaluate_log_likelihood(target_event_sequences, softmax) self.assertListEqual([np.log(0.5) + np.log(0.3), np.log(0.4) + np.log(0.6)], p) class OptionalEventSequenceEncoderTest(tf.test.TestCase):
88
88
294
11
77
Rancerle/Clarkson_Magenta
magenta/music/encoder_decoder_test.py
Python
OptionalEventSequenceEncoderTest
OptionalEventSequenceEncoderTest
381
407
381
382
85b4f1d18ab90016a9d98571558d968cb9e80504
bigcode/the-stack
train
2890d1c4882561a3ebfb05a6
train
class
class MultipleEventSequenceEncoderTest(tf.test.TestCase): def setUp(self): self.enc = encoder_decoder.MultipleEventSequenceEncoder([ encoder_decoder.OneHotEventSequenceEncoderDecoder( testing_lib.TrivialOneHotEncoding(2)), encoder_decoder.OneHotEventSequenceEncoderDecoder( ...
class MultipleEventSequenceEncoderTest(tf.test.TestCase):
def setUp(self): self.enc = encoder_decoder.MultipleEventSequenceEncoder([ encoder_decoder.OneHotEventSequenceEncoderDecoder( testing_lib.TrivialOneHotEncoding(2)), encoder_decoder.OneHotEventSequenceEncoderDecoder( testing_lib.TrivialOneHotEncoding(3))]) def testInputSi...
, 0.0], self.enc.events_to_input(events, 2)) self.assertEqual( [1.0, 0.0, 0.0, 0.0], self.enc.events_to_input(events, 3)) self.assertEqual( [1.0, 0.0, 0.0, 0.0], self.enc.events_to_input(events, 4)) class MultipleEventSequenceEncoderTest(tf.test.TestCase):
102
102
342
11
91
Rancerle/Clarkson_Magenta
magenta/music/encoder_decoder_test.py
Python
MultipleEventSequenceEncoderTest
MultipleEventSequenceEncoderTest
410
438
410
411
6aad5ac4dd8860f9b44979aaa6e52745da183c7a
bigcode/the-stack
train
aa28b789838d0cb5c1582d91
train
class
class OneHotIndexEventSequenceEncoderDecoderTest(tf.test.TestCase): def setUp(self): self.enc = encoder_decoder.OneHotIndexEventSequenceEncoderDecoder( testing_lib.TrivialOneHotEncoding(3, num_steps=range(3))) def testInputSize(self): self.assertEquals(1, self.enc.input_size) def testInputDepth...
class OneHotIndexEventSequenceEncoderDecoderTest(tf.test.TestCase):
def setUp(self): self.enc = encoder_decoder.OneHotIndexEventSequenceEncoderDecoder( testing_lib.TrivialOneHotEncoding(3, num_steps=range(3))) def testInputSize(self): self.assertEquals(1, self.enc.input_size) def testInputDepth(self): self.assertEquals(3, self.enc.input_depth) def testEve...
events2] softmax = [[[0.0, 0.5, 0.5], [0.3, 0.4, 0.3]], [[0.0, 0.6, 0.4], [0.0, 0.4, 0.6]]] p = self.enc.evaluate_log_likelihood(event_sequences, softmax) self.assertListEqual([np.log(0.5) + np.log(0.3), np.log(0.4) + np.log(0.6)], p) class OneHotIndexEventSequenceE...
137
137
457
14
123
Rancerle/Clarkson_Magenta
magenta/music/encoder_decoder_test.py
Python
OneHotIndexEventSequenceEncoderDecoderTest
OneHotIndexEventSequenceEncoderDecoderTest
120
161
120
121
dd5147dbc0c3c3557f67458d79a1dbe5d1c4cd38
bigcode/the-stack
train
09583769301641b6edf7d64b
train
class
class OneHotEventSequenceEncoderDecoderTest(tf.test.TestCase): def setUp(self): self.enc = encoder_decoder.OneHotEventSequenceEncoderDecoder( testing_lib.TrivialOneHotEncoding(3, num_steps=range(3))) def testInputSize(self): self.assertEquals(3, self.enc.input_size) def testNumClasses(self): ...
class OneHotEventSequenceEncoderDecoderTest(tf.test.TestCase):
def setUp(self): self.enc = encoder_decoder.OneHotEventSequenceEncoderDecoder( testing_lib.TrivialOneHotEncoding(3, num_steps=range(3))) def testInputSize(self): self.assertEquals(3, self.enc.input_size) def testNumClasses(self): self.assertEqual(3, self.enc.num_classes) def testEventsToI...
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
209
256
1,217
13
195
Rancerle/Clarkson_Magenta
magenta/music/encoder_decoder_test.py
Python
OneHotEventSequenceEncoderDecoderTest
OneHotEventSequenceEncoderDecoderTest
28
117
28
29
eb840cfeae16404ce6dbccf319c8a45f2aa0cbf6
bigcode/the-stack
train
3188160127d3e6ec5df5768d
train
class
class ConditionalEventSequenceEncoderDecoderTest(tf.test.TestCase): def setUp(self): self.enc = encoder_decoder.ConditionalEventSequenceEncoderDecoder( encoder_decoder.OneHotEventSequenceEncoderDecoder( testing_lib.TrivialOneHotEncoding(2)), encoder_decoder.OneHotEventSequenceEncoderD...
class ConditionalEventSequenceEncoderDecoderTest(tf.test.TestCase):
def setUp(self): self.enc = encoder_decoder.ConditionalEventSequenceEncoderDecoder( encoder_decoder.OneHotEventSequenceEncoderDecoder( testing_lib.TrivialOneHotEncoding(2)), encoder_decoder.OneHotEventSequenceEncoderDecoder( testing_lib.TrivialOneHotEncoding(3))) def tes...
[:1])) self.assertEqual(0, self.enc.class_index_to_event(0, events[:2])) self.assertEqual(1, self.enc.class_index_to_event(1, events[:2])) self.assertEqual(2, self.enc.class_index_to_event(2, events[:2])) self.assertEqual(0, self.enc.class_index_to_event(0, events[:3])) self.assertEqual(1, self.enc....
255
256
1,437
12
243
Rancerle/Clarkson_Magenta
magenta/music/encoder_decoder_test.py
Python
ConditionalEventSequenceEncoderDecoderTest
ConditionalEventSequenceEncoderDecoderTest
279
378
279
280
ff369f2a85ea16e5fb9a2b0cbb21bb23e8d7dc29
bigcode/the-stack
train
d6056dd8917c1d2d4d77f1f0
train
class
class XGraph(): def __init__(self): # directed = False if non-directed graph, and otherwise self.verticesCount = 0 self.edgesCount = 0 self.verticeList = XHashTable() self.edgesList = XHashTable() def __len__(self): return self.verticesCount def empty(self):...
class XGraph():
def __init__(self): # directed = False if non-directed graph, and otherwise self.verticesCount = 0 self.edgesCount = 0 self.verticeList = XHashTable() self.edgesList = XHashTable() def __len__(self): return self.verticesCount def empty(self): return ...
__author__ = 'HaoBin' from XHashTable import XHashTable class XGraph():
22
256
1,081
4
17
mrbinx/mrbinx_python
Python/P12 - Graphs and Numerical/XGraph2.py
Python
XGraph
XGraph
6
165
6
6
d20b8686d9c5a0d2ab4092287eeb19a3903845a6
bigcode/the-stack
train
cfee38bdef5a513eb5d671b3
train
class
class XEdge(): def __init__(self, v1, v2, weight, directed=False): self.v1 = v1 self.v2 = v2 self.directed = directed self.cost = weight def isDirected(self): return self.directed def getCost(self): return self.cost def getV2(self): return self....
class XEdge():
def __init__(self, v1, v2, weight, directed=False): self.v1 = v1 self.v2 = v2 self.directed = directed self.cost = weight def isDirected(self): return self.directed def getCost(self): return self.cost def getV2(self): return self.v2 def get...
): # Complexity: O(|E|) or O(|V|^2) for v in self.getVertices(): for c in self.getConnections(v[0]): print(v[1].getID(), ">", c[1].getV2().getID()) class XEdge():
63
64
124
4
59
mrbinx/mrbinx_python
Python/P12 - Graphs and Numerical/XGraph2.py
Python
XEdge
XEdge
171
191
171
171
cae1cbdb98565a9670a203f85bbbc475ab840507
bigcode/the-stack
train
bf7b6c1253849c634c002a0f
train
class
class XVertice(): def __init__(self, key): self.id = key def getID(self): return self.id
class XVertice():
def __init__(self, key): self.id = key def getID(self): return self.id
getCost(self): return self.cost def getV2(self): return self.v2 def getV1(self): return self.v1 def strConnection(self): return self.v1.getID() + " " + self.v2.getID() class XVertice():
64
64
31
5
59
mrbinx/mrbinx_python
Python/P12 - Graphs and Numerical/XGraph2.py
Python
XVertice
XVertice
194
199
194
194
0726a435577ba46689c62b6ed96450fb3aeb1b2d
bigcode/the-stack
train
78a639671478fc6a801ce58f
train
function
def main(argv): """Trains QR-DQN agent on Atari.""" del argv logging.info('QR-DQN on Atari on %s.', jax.lib.xla_bridge.get_backend().platform) random_state = np.random.RandomState(FLAGS.seed) rng_key = jax.random.PRNGKey( random_state.randint(-sys.maxsize - 1, sys.maxsize + 1, dtype=np.in...
def main(argv):
"""Trains QR-DQN agent on Atari.""" del argv logging.info('QR-DQN on Atari on %s.', jax.lib.xla_bridge.get_backend().platform) random_state = np.random.RandomState(FLAGS.seed) rng_key = jax.random.PRNGKey( random_state.randint(-sys.maxsize - 1, sys.maxsize + 1, dtype=np.int64)) if FLAG...
exploration_epsilon_decay_frame_fraction', 0.02, '') flags.DEFINE_float('eval_exploration_epsilon', 0.001, '') flags.DEFINE_integer('target_network_update_period', int(4e4), '') flags.DEFINE_float('huber_param', 1., '') flags.DEFINE_float('learning_rate', 0.00005, '') flags.DEFINE_float('optimizer_epsilon', 0.01 / 32, ...
255
256
1,662
4
251
WorksWellWithOthers/dqn_zoo
dqn_zoo/qrdqn/run_atari.py
Python
main
main
81
258
81
81
b9e72aa07a82f36b9d15dba73499ddb24187813b
bigcode/the-stack
train
e161be7f0c360f6bab665aee
train
function
def search_in_rotated_array(arr, key): if len(arr) == 0: return -1 start, end = 0, len(arr) - 1 while start <= end: mid = start + (end - start) // 2 if arr[mid] == key: return mid if arr[start] <= arr[mid]: if key >= arr[start] and key < ...
def search_in_rotated_array(arr, key):
if len(arr) == 0: return -1 start, end = 0, len(arr) - 1 while start <= end: mid = start + (end - start) // 2 if arr[mid] == key: return mid if arr[start] <= arr[mid]: if key >= arr[start] and key < arr[mid]: end = mid - 1...
: [10, 15, 1, 3, 8], key = 15 # Output: 1 # Explanation: '15' is present in the array at index '1'. # O(logN) space:O(1) def search_in_rotated_array(arr, key):
64
64
153
10
54
JoanWu5/Grokking-the-coding-interview
modified binary search/search in rotated array.py
Python
search_in_rotated_array
search_in_rotated_array
13
34
13
13
86c2115dcd847ec76975cf3c3acafd649878612f
bigcode/the-stack
train
37f18b19beccec1772622301
train
function
def search_in_rotated_duplicate_array(arr, key): if len(arr) == 0: return -1 start, end = 0, len(arr) - 1 while start <= end: mid = start + (end - start) // 2 if arr[mid] == key: return mid if arr[start] == arr[mid] and arr[end] == arr[mid]: ...
def search_in_rotated_duplicate_array(arr, key):
if len(arr) == 0: return -1 start, end = 0, len(arr) - 1 while start <= end: mid = start + (end - start) // 2 if arr[mid] == key: return mid if arr[start] == arr[mid] and arr[end] == arr[mid]: start += 1 end -= 1 if a...
in a sorted and rotated array that also has duplicates? print(search_in_rotated_array([3, 7, 3, 3, 3], 7)) # best: O(logN) worst:O(N) space:O(1) def search_in_rotated_duplicate_array(arr, key):
64
64
183
11
53
JoanWu5/Grokking-the-coding-interview
modified binary search/search in rotated array.py
Python
search_in_rotated_duplicate_array
search_in_rotated_duplicate_array
44
69
44
44
3be16494f75e6659ba3aa5faa982de7fb999cb17
bigcode/the-stack
train
2d4fcd8674dbfe9296bf962a
train
function
def get_time_from_file_name(fileName): splitted = fileName.split('-') dateStr = splitted[1] timeStr = splitted[2] year = dateStr[0:4] month = dateStr[4:6] day = dateStr[6:8] hour = timeStr[0:2] return [year, month, day, hour]
def get_time_from_file_name(fileName):
splitted = fileName.split('-') dateStr = splitted[1] timeStr = splitted[2] year = dateStr[0:4] month = dateStr[4:6] day = dateStr[6:8] hour = timeStr[0:2] return [year, month, day, hour]
] hour = timeStr[0:2] d = date(int(year), int(month), int(day)) t = time(int(hour), 00) d = datetime.datetime.combine(d, t) return calendar.timegm(d.timetuple()) def get_time_from_file_name(fileName):
63
64
84
9
54
sgomezsaez/SCARF-Evaluation
wikipedia_workload/de/uni-stuttgart/iaas/experiments_results/utils.py
Python
get_time_from_file_name
get_time_from_file_name
51
59
51
51
4044012783a445ed8f2f89232a70f0aafff8f602
bigcode/the-stack
train
eacf595d2649107865ca569e
train
function
def get_N_HexCol(N=5): HSV_tuples = [(x*1.0/N, 0.5, 0.5) for x in xrange(N)] hex_out = [] for rgb in HSV_tuples: rgb = map(lambda x: int(x*255),colorsys.hsv_to_rgb(*rgb)) hex_out.append("".join(map(lambda x: chr(x).encode('hex'),rgb))) return hex_out
def get_N_HexCol(N=5):
HSV_tuples = [(x*1.0/N, 0.5, 0.5) for x in xrange(N)] hex_out = [] for rgb in HSV_tuples: rgb = map(lambda x: int(x*255),colorsys.hsv_to_rgb(*rgb)) hex_out.append("".join(map(lambda x: chr(x).encode('hex'),rgb))) return hex_out
)[2:].zfill(6) for I in range(0, max_value, interval)] return [(int(i[:2], 16), int(i[2:4], 16), int(i[4:], 16)) for i in colors] def get_N_HexCol(N=5):
64
64
98
10
54
sgomezsaez/SCARF-Evaluation
wikipedia_workload/de/uni-stuttgart/iaas/experiments_results/utils.py
Python
get_N_HexCol
get_N_HexCol
69
76
69
70
09022105632ecb42478f31ac5c61e700065b0573
bigcode/the-stack
train
4dc8cbb84c62363e963b9773
train
function
def get_timestamp_from_file_name(fileName): splitted = fileName.split('-') dateStr = splitted[0] timeStr = splitted[1] year = dateStr[0:4] month = dateStr[4:6] day = dateStr[6:8] hour = timeStr[0:2] d = date(int(year), int(month), int(day)) t = time(int(hour), 00) d = datetime.da...
def get_timestamp_from_file_name(fileName):
splitted = fileName.split('-') dateStr = splitted[0] timeStr = splitted[1] year = dateStr[0:4] month = dateStr[4:6] day = dateStr[6:8] hour = timeStr[0:2] d = date(int(year), int(month), int(day)) t = time(int(hour), 00) d = datetime.datetime.combine(d, t) return calendar.tim...
if suffix != '': fileName = fileName + suffix fileList.append(fileName) return fileList def build_file_name(year, month, day, time, count): return year + month + day + "-" + time + "0000" def get_timestamp_from_file_name(fileName):
64
64
116
9
55
sgomezsaez/SCARF-Evaluation
wikipedia_workload/de/uni-stuttgart/iaas/experiments_results/utils.py
Python
get_timestamp_from_file_name
get_timestamp_from_file_name
36
47
36
36
10f486cb53aac8c4ba7687b075feb70344c5ff8a
bigcode/the-stack
train
bf6705cccd22237b4f574d5f
train
function
def retrieve_files_time_interval(beginYear, beginMonth, beginday, endYear, endMonth, endday, hours, count, suffix=''): a = date(beginYear, beginMonth, beginday) b = date(endYear, endMonth, endday) dd = [a + timedelta(days=x) for x in range((b-a).days + 1)] fileList = [] if dd.__len__() == 0: ...
def retrieve_files_time_interval(beginYear, beginMonth, beginday, endYear, endMonth, endday, hours, count, suffix=''):
a = date(beginYear, beginMonth, beginday) b = date(endYear, endMonth, endday) dd = [a + timedelta(days=x) for x in range((b-a).days + 1)] fileList = [] if dd.__len__() == 0: for h in hours: fileName = build_file_name(str(beginYear).zfill(2), str(beginMonth).zfill(2), str(beginda...
import colorsys import itertools timeStampToDateTime = lambda x: datetime.fromtimestamp( int(x) ).strftime('%Y-%m-%d %H:%M:%S') def retrieve_files_time_interval(beginYear, beginMonth, beginday, endYear, endMonth, endday, hours, count, suffix=''):
72
72
243
31
41
sgomezsaez/SCARF-Evaluation
wikipedia_workload/de/uni-stuttgart/iaas/experiments_results/utils.py
Python
retrieve_files_time_interval
retrieve_files_time_interval
11
31
11
11
6ba246630cbe078a2aaa1dadd6aeca87b398f6de
bigcode/the-stack
train
7a49876569f66c1148c25c08
train
function
def build_file_name(year, month, day, time, count): return year + month + day + "-" + time + "0000"
def build_file_name(year, month, day, time, count):
return year + month + day + "-" + time + "0000"
0], d.isoformat().split('-')[1], d.isoformat().split('-')[2], h, count) if suffix != '': fileName = fileName + suffix fileList.append(fileName) return fileList def build_file_name(year, month, day, time, count):
64
64
30
14
49
sgomezsaez/SCARF-Evaluation
wikipedia_workload/de/uni-stuttgart/iaas/experiments_results/utils.py
Python
build_file_name
build_file_name
33
34
33
33
4d5bbb3203f4ab8a1b8331ee3011ac6030041323
bigcode/the-stack
train
fefc6493b932c071038ff04c
train
function
def get_spaced_colors(n): max_value = 16581375 #255**3 interval = int(max_value / n) colors = [hex(I)[2:].zfill(6) for I in range(0, max_value, interval)] return [(int(i[:2], 16), int(i[2:4], 16), int(i[4:], 16)) for i in colors]
def get_spaced_colors(n):
max_value = 16581375 #255**3 interval = int(max_value / n) colors = [hex(I)[2:].zfill(6) for I in range(0, max_value, interval)] return [(int(i[:2], 16), int(i[2:4], 16), int(i[4:], 16)) for i in colors]
Str = splitted[2] year = dateStr[0:4] month = dateStr[4:6] day = dateStr[6:8] hour = timeStr[0:2] return [year, month, day, hour] def get_spaced_colors(n):
64
64
89
7
57
sgomezsaez/SCARF-Evaluation
wikipedia_workload/de/uni-stuttgart/iaas/experiments_results/utils.py
Python
get_spaced_colors
get_spaced_colors
62
67
62
62
97e41ba2746c8e4ae94955c2d8e637240652d606
bigcode/the-stack
train
491dbad97b43e3a0840c27bf
train
function
def flip(items, ncol): return itertools.chain(*[items[i::ncol] for i in range(ncol)])
def flip(items, ncol):
return itertools.chain(*[items[i::ncol] for i in range(ncol)])
_out = [] for rgb in HSV_tuples: rgb = map(lambda x: int(x*255),colorsys.hsv_to_rgb(*rgb)) hex_out.append("".join(map(lambda x: chr(x).encode('hex'),rgb))) return hex_out def flip(items, ncol):
64
64
26
7
56
sgomezsaez/SCARF-Evaluation
wikipedia_workload/de/uni-stuttgart/iaas/experiments_results/utils.py
Python
flip
flip
78
79
78
78
2e0fc83474e83479029f3a616e2c7811ec605aa6
bigcode/the-stack
train
894b4e8917a782f083ea10ec
train
function
def print_filesystem_listing(filesystems, plan): for fs in filesystems.values(): fs['actions'] = fs.get('actions', []) for action in plan: if isinstance(action, SnapshotManager.CreateSnapshot) or \ isinstance(action, SnapshotManager.DeleteSnapshot) or \ isinstance(action,...
def print_filesystem_listing(filesystems, plan):
for fs in filesystems.values(): fs['actions'] = fs.get('actions', []) for action in plan: if isinstance(action, SnapshotManager.CreateSnapshot) or \ isinstance(action, SnapshotManager.DeleteSnapshot) or \ isinstance(action, SnapshotManager.RenameSnapshot): if a...
we need to add a new snapshot if len(planed_times) and planed_times[0] not in satisfied_jobs: target_name = self._snapshot_name(datetime.datetime.now()) yield self.CreateSnapshot(self, filesystem, target_name) if maintain_symlinks: yield s...
96
97
325
10
86
efenka/ZAS
zas.py
Python
print_filesystem_listing
print_filesystem_listing
527
563
527
528
d17f9dd8934ddd781f6cf06e1d9843d36276a10d
bigcode/the-stack
train
ce5aac746354d3177a2ead32
train
class
class TimeParser(object): """ Each definition can consist of combinations of: a number (1,2,3,...) a letter (M,H,d,W,m or y) M = Minutes H = Hours d = Days W = Weeks m = Month y = Years an / combined with a number (n...
class TimeParser(object):
""" Each definition can consist of combinations of: a number (1,2,3,...) a letter (M,H,d,W,m or y) M = Minutes H = Hours d = Days W = Weeks m = Month y = Years an / combined with a number (n) to set any time ...
ystems by name. --prefix=<string> Snapshot name prefix. [default: snapshot-from-]. --no-prefix-check Don't ignore snapshots without matching prefix. --symlinks Create symlink required by samba vfs objects shadow_copy. Other options: --zfs-binary=<path> Alternative location ...
256
256
1,446
5
250
efenka/ZAS
zas.py
Python
TimeParser
TimeParser
55
262
55
55
f383dd06a40182bac307dc6a70b6106d26366b94
bigcode/the-stack
train
aefcd3eebdbda39fdb371a61
train
class
class SnapshotManager(object): def __init__(self, binary=False, prefix="snapshot-from-", prefix_check=True): self.zfs_binary = binary or "/sbin/zfs" self.snapshot_prefix = prefix self.prefix_check = prefix_check class Filesystems(dict): pass def filesystems(self, includes=...
class SnapshotManager(object):
def __init__(self, binary=False, prefix="snapshot-from-", prefix_check=True): self.zfs_binary = binary or "/sbin/zfs" self.snapshot_prefix = prefix self.prefix_check = prefix_check class Filesystems(dict): pass def filesystems(self, includes=None, excludes=None): d...
day', 'days'), ('week', 'weeks'), ('month', 'months'), ('year', 'years')] possible_results = [] unit = list(map(lambda element: element[1], names)).index(unit) amount *= intervals[unit] while len(intervals): this_result = [...
255
256
2,195
5
250
efenka/ZAS
zas.py
Python
SnapshotManager
SnapshotManager
265
524
265
266
8353fa1ad9e2ba9d741d3c06dff925240297dda7
bigcode/the-stack
train
61e5eab1d9832746c0c050e3
train
function
def main(): arguments = docopt.docopt(__doc__.format(cmd=os.path.basename(__file__), time_help=indent(TimeParser.__doc__, ' ' * 24))) logging.basicConfig( filename=arguments['--logfile'], format="%(asctime)s %(levelname)s: %(message)s", datef...
def main():
arguments = docopt.docopt(__doc__.format(cmd=os.path.basename(__file__), time_help=indent(TimeParser.__doc__, ' ' * 24))) logging.basicConfig( filename=arguments['--logfile'], format="%(asctime)s %(levelname)s: %(message)s", datefmt="%Y-%m-%d...
=' '))) for action in fs['actions']: if isinstance(action, SnapshotManager.CreateSnapshot): print(' [CREATE] %s' % action) print() def lock(path=__file__): import fcntl import os fp = os.open(path, os.O_CREAT | os.O_WRONLY) try: fcntl.lockf(fp, fcntl...
115
115
386
3
111
efenka/ZAS
zas.py
Python
main
main
579
624
579
579
70b097ebeb35ab9fe07f7703a18c49cd5d084c92
bigcode/the-stack
train
5defedddc1dab1d662f17b42
train
function
def lock(path=__file__): import fcntl import os fp = os.open(path, os.O_CREAT | os.O_WRONLY) try: fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: return False else: return True
def lock(path=__file__):
import fcntl import os fp = os.open(path, os.O_CREAT | os.O_WRONLY) try: fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: return False else: return True
_name, snapshot['creation'], TimeParser.humanize_time(snapshot['age'], join=' '))) for action in fs['actions']: if isinstance(action, SnapshotManager.CreateSnapshot): print(' [CREATE] %s' % action) print() def lock(path=__file__):
64
64
75
8
56
efenka/ZAS
zas.py
Python
lock
lock
566
576
566
566
09881d8db96cd8d5b764b7996f1bbc67378f91be
bigcode/the-stack
train
81084c6f93a61e64fda79147
train
class
class Pypdfy: def __init__(self): self.image = 0 self.is_path = True self.not_image = 0 self.options = { 'statistics' : False } def is_image(self, file): if self.is_path: file_contents = open(file, 'rb').read() else: ...
class Pypdfy:
def __init__(self): self.image = 0 self.is_path = True self.not_image = 0 self.options = { 'statistics' : False } def is_image(self, file): if self.is_path: file_contents = open(file, 'rb').read() else: file_contents ...
import re class Pypdfy:
10
118
395
6
3
TheHunter896/pypdfy
pypdfy/pypdfy.py
Python
Pypdfy
Pypdfy
4
61
4
4
955d54a3abe487aaa2d1c6cff438965fb87c42a1
bigcode/the-stack
train
235a4b6c4e9d1f75ec68d843
train
class
@dataclass class UniformInvoiceInfo: """ The UniformInvoiceInfo object keeps track of an item in inventory, including invoice year, claiming date and winning_numbers (i.e. rewards).` """ invoice_year: str claiming_date: str winning_numbers: list
@dataclass class UniformInvoiceInfo:
""" The UniformInvoiceInfo object keeps track of an item in inventory, including invoice year, claiming date and winning_numbers (i.e. rewards).` """ invoice_year: str claiming_date: str winning_numbers: list
import re from typing import Union from bs4 import BeautifulSoup from dataclasses import dataclass @dataclass class UniformInvoiceInfo:
30
64
60
8
21
Retr0327/uniform-invoice-tkinter-app
invoiceapp/uniforminvoice/uniform_invoice_data.py
Python
UniformInvoiceInfo
UniformInvoiceInfo
7
15
7
8
94ca37f39445f16399b19ed5da58141026ede4b0
bigcode/the-stack
train
3ae5705f6ad1ca28a7c8fb9a
train
class
@dataclass class UniformInvoiceData: """ The UniformInvoiceData object finds the crucial data of the uniform-invoice webpage, namely title and winning numbers. """ soup: BeautifulSoup def __post_init__(self) -> None: self.table_tag = self.soup.find("table", class_=re.compile(r"mytable(gree...
@dataclass class UniformInvoiceData:
""" The UniformInvoiceData object finds the crucial data of the uniform-invoice webpage, namely title and winning numbers. """ soup: BeautifulSoup def __post_init__(self) -> None: self.table_tag = self.soup.find("table", class_=re.compile(r"mytable(green|pink)")) def extract_claiming_...
import re from typing import Union from bs4 import BeautifulSoup from dataclasses import dataclass @dataclass class UniformInvoiceInfo: """ The UniformInvoiceInfo object keeps track of an item in inventory, including invoice year, claiming date and winning_numbers (i.e. rewards).` """ invoice_year: s...
90
113
379
8
81
Retr0327/uniform-invoice-tkinter-app
invoiceapp/uniforminvoice/uniform_invoice_data.py
Python
UniformInvoiceData
UniformInvoiceData
18
65
18
19
cd378f7fc3cde2bc8f2f42b7ba1dd9629b1cf776
bigcode/the-stack
train
600f3b341af0e310f68f9f74
train
function
def _prodmode_compile_action(ctx, inputs, outputs, tsconfig_file, node_opts): outs = _expected_outs(ctx) return _compile_action(ctx, inputs, outputs + outs.closure_js, outs.i18n_messages, tsconfig_file, node_opts)
def _prodmode_compile_action(ctx, inputs, outputs, tsconfig_file, node_opts):
outs = _expected_outs(ctx) return _compile_action(ctx, inputs, outputs + outs.closure_js, outs.i18n_messages, tsconfig_file, node_opts)
.attr.deps if hasattr(dep, "collect_summaries_aspect_result")]) return ngc_compile_action(ctx, ctx.label, action_inputs, outputs, messages_out, tsconfig_file, node_opts) def _prodmode_compile_action(ctx, inputs, outputs, tsconfig_file, node_opts):
64
64
57
19
45
echarny/material2
node_modules/@angular/bazel/src/ng_module.bzl
Python
_prodmode_compile_action
_prodmode_compile_action
301
303
301
301
88bb7a067095e656e453cde3030a67f5104a6d48
bigcode/the-stack
train
c2ac66091c63adb21d8dfdc0
train
function
def _ng_module_impl(ctx): return ts_providers_dict_to_struct(ng_module_impl(ctx, compile_ts))
def _ng_module_impl(ctx):
return ts_providers_dict_to_struct(ng_module_impl(ctx, compile_ts))
["angular"]["flat_module_metadata"] = struct( module_name = ctx.attr.module_name, metadata_file = outs.metadata[0], typings_file = outs.bundle_index_typings, flat_module_out_file = _flat_module_out_file(ctx), ) return providers def _ng_module_impl(ctx):
64
64
24
7
56
echarny/material2
node_modules/@angular/bazel/src/ng_module.bzl
Python
_ng_module_impl
_ng_module_impl
360
361
360
360
14e9a22564cabb9a97d978041e272c4af906b808
bigcode/the-stack
train
90a3929f01caebbe26722b73
train
function
def _expected_outs(ctx): devmode_js_files = [] closure_js_files = [] declaration_files = [] summary_files = [] metadata_files = [] factory_basename_set = depset([_basename_of(ctx, src) for src in ctx.files.factories]) for src in ctx.files.srcs + ctx.files.assets: package_prefix = ctx.label.package +...
def _expected_outs(ctx):
devmode_js_files = [] closure_js_files = [] declaration_files = [] summary_files = [] metadata_files = [] factory_basename_set = depset([_basename_of(ctx, src) for src in ctx.files.factories]) for src in ctx.files.srcs + ctx.files.assets: package_prefix = ctx.label.package + "/" if ctx.label.package...
other attributes (name) Args: ctx: skylark rule execution context Returns: a basename used for the flat module out (no extension) """ if hasattr(ctx.attr, "flat_module_out_file") and ctx.attr.flat_module_out_file: return ctx.attr.flat_module_out_file return "%s_public_index" % ctx.label.name d...
225
225
752
7
218
echarny/material2
node_modules/@angular/bazel/src/ng_module.bzl
Python
_expected_outs
_expected_outs
63
136
63
63
9c77bfda1708541f2524bb0a29a2a3a2dce1a4ab
bigcode/the-stack
train
23df7fc1ed75c8294660f159
train
function
def ngc_compile_action(ctx, label, inputs, outputs, messages_out, tsconfig_file, node_opts, locale=None, i18n_args=[]): """Helper function to create the ngc action. This is exposed for google3 to wire up i18n replay rules, and is not intended as part of the public API. Args: ctx: sk...
def ngc_compile_action(ctx, label, inputs, outputs, messages_out, tsconfig_file, node_opts, locale=None, i18n_args=[]):
"""Helper function to create the ngc action. This is exposed for google3 to wire up i18n replay rules, and is not intended as part of the public API. Args: ctx: skylark context label: the label of the ng_module being compiled inputs: passed to the ngc action's inputs outputs: passed to the ngc...
s = ctx.rule.attr.srcs if hasattr(ctx.rule.attr, "srcs") else [] # "re-export" rules should expose all the files of their deps if not srcs: for dep in ctx.rule.attr.deps: if (hasattr(dep, "angular")): results = depset(dep.angular.summaries, transitive = [results]) return struct(collect_summari...
198
198
662
33
165
echarny/material2
node_modules/@angular/bazel/src/ng_module.bzl
Python
ngc_compile_action
ngc_compile_action
197
277
197
198
1efb2ab7f7e54c9fecf494eb5045695d5737e935
bigcode/the-stack
train
5bd3151d5a74e179934bd293
train
function
def _basename_of(ctx, file): ext_len = len(".ts") if file.short_path.endswith(".ng.html"): ext_len = len(".ng.html") elif file.short_path.endswith(".html"): ext_len = len(".html") return file.short_path[len(ctx.label.package) + 1:-ext_len]
def _basename_of(ctx, file):
ext_len = len(".ts") if file.short_path.endswith(".ng.html"): ext_len = len(".ng.html") elif file.short_path.endswith(".html"): ext_len = len(".html") return file.short_path[len(ctx.label.package) + 1:-ext_len]
ng_module rule. """ load(":rules_typescript.bzl", "tsc_wrapped_tsconfig", "COMMON_ATTRIBUTES", "COMMON_OUTPUTS", "compile_ts", "DEPS_ASPECTS", "ts_providers_dict_to_struct", ) def _basename_of(ctx, file):
64
64
69
8
56
echarny/material2
node_modules/@angular/bazel/src/ng_module.bzl
Python
_basename_of
_basename_of
17
23
17
17
405d77fc7c92ca62c54e8d71f4d74e9920963163
bigcode/the-stack
train
0379fb309dd8a33474c6de1b
train
function
def _ivy_tsconfig(ctx, files, srcs, **kwargs): return _ngc_tsconfig_helper(ctx, files, srcs, True, **kwargs)
def _ivy_tsconfig(ctx, files, srcs, **kwargs):
return _ngc_tsconfig_helper(ctx, files, srcs, True, **kwargs)
= devmode_js_files, declarations = declaration_files, summaries = summary_files, metadata = metadata_files, bundle_index_typings = bundle_index_typings, i18n_messages = i18n_messages_files, ) def _ivy_tsconfig(ctx, files, srcs, **kwargs):
64
64
35
15
49
echarny/material2
node_modules/@angular/bazel/src/ng_module.bzl
Python
_ivy_tsconfig
_ivy_tsconfig
138
139
138
138
1ea7bc532ce563226363069ff7c2dacb9bc4b64b
bigcode/the-stack
train
08b546f58077c8f6808e94ec
train
function
def _compile_action(ctx, inputs, outputs, messages_out, tsconfig_file, node_opts): # Give the Angular compiler all the user-listed assets file_inputs = list(ctx.files.assets) # The compiler only needs to see TypeScript sources from the npm dependencies, # but may need to look at package.json and ngsummary.json...
def _compile_action(ctx, inputs, outputs, messages_out, tsconfig_file, node_opts): # Give the Angular compiler all the user-listed assets
file_inputs = list(ctx.files.assets) # The compiler only needs to see TypeScript sources from the npm dependencies, # but may need to look at package.json and ngsummary.json files as well. if hasattr(ctx.attr, "node_modules"): file_inputs += [f for f in ctx.files.node_modules if f.path....
: return struct( label = label, tsconfig = tsconfig_file, inputs = inputs, outputs = outputs, compiler = ctx.executable.compiler, ) return None def _compile_action(ctx, inputs, outputs, messages_out, tsconfig_file, node_opts): # Give the Angular compiler all the user...
74
74
247
32
41
echarny/material2
node_modules/@angular/bazel/src/ng_module.bzl
Python
_compile_action
_compile_action
279
298
279
280
6badbb50f43d824dba3214d5f84d29e4b50eebc4
bigcode/the-stack
train
434b97cff9d52c84988075a2
train
function
def _ivy_module_impl(ctx): return ts_providers_dict_to_struct(ng_module_impl(ctx, compile_ts, True))
def _ivy_module_impl(ctx):
return ts_providers_dict_to_struct(ng_module_impl(ctx, compile_ts, True))
.metadata[0], typings_file = outs.bundle_index_typings, flat_module_out_file = _flat_module_out_file(ctx), ) return providers def _ng_module_impl(ctx): return ts_providers_dict_to_struct(ng_module_impl(ctx, compile_ts)) def _ivy_module_impl(ctx):
64
64
26
7
57
echarny/material2
node_modules/@angular/bazel/src/ng_module.bzl
Python
_ivy_module_impl
_ivy_module_impl
363
364
363
363
966f458262c02401d270f60daf8d984145c9557b
bigcode/the-stack
train
82e0528f148acfd7b2a17b92
train
function
def _is_bazel(): return not hasattr(native, "genmpm")
def _is_bazel():
return not hasattr(native, "genmpm")
elif file.short_path.endswith(".html"): ext_len = len(".html") return file.short_path[len(ctx.label.package) + 1:-ext_len] # Return true if run with bazel (the open-sourced version of blaze), false if # run with blaze. def _is_bazel():
64
64
17
6
58
echarny/material2
node_modules/@angular/bazel/src/ng_module.bzl
Python
_is_bazel
_is_bazel
27
28
27
27
edb065b00d270f2cbfae1d731046bc3fe94f1d28
bigcode/the-stack
train
b284f265a18210c6d17a9076
train
function
def _collect_summaries_aspect_impl(target, ctx): results = depset(target.angular.summaries if hasattr(target, "angular") else []) # If we are visiting empty-srcs ts_library, this is a re-export srcs = ctx.rule.attr.srcs if hasattr(ctx.rule.attr, "srcs") else [] # "re-export" rules should expose all the files ...
def _collect_summaries_aspect_impl(target, ctx):
results = depset(target.angular.summaries if hasattr(target, "angular") else []) # If we are visiting empty-srcs ts_library, this is a re-export srcs = ctx.rule.attr.srcs if hasattr(ctx.rule.attr, "srcs") else [] # "re-export" rules should expose all the files of their deps if not srcs: for dep in ctx.r...
.workspace_name] + ctx.label.package.split("/") + [ctx.label.name, ""]) return dict(tsc_wrapped_tsconfig(ctx, files, srcs, **kwargs), **{ "angularCompilerOptions": angular_compiler_options }) def _collect_summaries_aspect_impl(target, ctx):
64
64
145
13
51
echarny/material2
node_modules/@angular/bazel/src/ng_module.bzl
Python
_collect_summaries_aspect_impl
_collect_summaries_aspect_impl
172
184
172
172
84bb958bd5e2e9c2c93fa7e3c8aa768bd2b4f25a
bigcode/the-stack
train
82f675936897b813968d2ef5
train
function
def ng_module_impl(ctx, ts_compile_actions, ivy = False): """Implementation function for the ng_module rule. This is exposed so that google3 can have its own entry point that re-uses this and is not meant as a public API. Args: ctx: the skylark rule context ts_compile_actions: generates all the action...
def ng_module_impl(ctx, ts_compile_actions, ivy = False):
"""Implementation function for the ng_module rule. This is exposed so that google3 can have its own entry point that re-uses this and is not meant as a public API. Args: ctx: the skylark rule context ts_compile_actions: generates all the actions to run an ngc compilation ivy: if True, run the comp...
outputs + outs.devmode_js + outs.declarations + outs.summaries + outs.metadata _compile_action(ctx, inputs, compile_action_outputs, None, tsconfig_file, node_opts) def _ts_expected_outs(ctx, label): # rules_typescript expects a function with two arguments, but our # implementation doesn't use the label _ignor...
103
103
346
14
89
echarny/material2
node_modules/@angular/bazel/src/ng_module.bzl
Python
ng_module_impl
ng_module_impl
316
358
316
316
4abf16d28211b759519d5314c3adcfc7e3300eaf
bigcode/the-stack
train
22e3755bc83bf6fe4194ef97
train
function
def _ts_expected_outs(ctx, label): # rules_typescript expects a function with two arguments, but our # implementation doesn't use the label _ignored = [label] return _expected_outs(ctx)
def _ts_expected_outs(ctx, label): # rules_typescript expects a function with two arguments, but our # implementation doesn't use the label
_ignored = [label] return _expected_outs(ctx)
clarations + outs.summaries + outs.metadata _compile_action(ctx, inputs, compile_action_outputs, None, tsconfig_file, node_opts) def _ts_expected_outs(ctx, label): # rules_typescript expects a function with two arguments, but our # implementation doesn't use the label
64
64
48
33
31
echarny/material2
node_modules/@angular/bazel/src/ng_module.bzl
Python
_ts_expected_outs
_ts_expected_outs
310
314
310
312
38de7920db408fa5c330a4c7b7359b7427f4d7cf
bigcode/the-stack
train
59e091a42d6e9247eb8be64b
train
function
def _ngc_tsconfig_helper(ctx, files, srcs, enable_ivy, **kwargs): outs = _expected_outs(ctx) if "devmode_manifest" in kwargs: expected_outs = outs.devmode_js + outs.declarations + outs.summaries + outs.metadata else: expected_outs = outs.closure_js angular_compiler_options = { "enableResourceInli...
def _ngc_tsconfig_helper(ctx, files, srcs, enable_ivy, **kwargs):
outs = _expected_outs(ctx) if "devmode_manifest" in kwargs: expected_outs = outs.devmode_js + outs.declarations + outs.summaries + outs.metadata else: expected_outs = outs.closure_js angular_compiler_options = { "enableResourceInlining": ctx.attr.inline_resources, "generateCodeForLibraries"...
_tsconfig(ctx, files, srcs, **kwargs): return _ngc_tsconfig_helper(ctx, files, srcs, True, **kwargs) def _ngc_tsconfig(ctx, files, srcs, **kwargs): return _ngc_tsconfig_helper(ctx, files, srcs, False, **kwargs) def _ngc_tsconfig_helper(ctx, files, srcs, enable_ivy, **kwargs):
89
89
297
21
68
echarny/material2
node_modules/@angular/bazel/src/ng_module.bzl
Python
_ngc_tsconfig_helper
_ngc_tsconfig_helper
144
170
144
144
36584c2c6859d9bd768ca397218188427fae68ec
bigcode/the-stack
train
f079247a5eccb87cce667ca5
train
function
def _ngc_tsconfig(ctx, files, srcs, **kwargs): return _ngc_tsconfig_helper(ctx, files, srcs, False, **kwargs)
def _ngc_tsconfig(ctx, files, srcs, **kwargs):
return _ngc_tsconfig_helper(ctx, files, srcs, False, **kwargs)
i18n_messages = i18n_messages_files, ) def _ivy_tsconfig(ctx, files, srcs, **kwargs): return _ngc_tsconfig_helper(ctx, files, srcs, True, **kwargs) def _ngc_tsconfig(ctx, files, srcs, **kwargs):
64
64
36
16
48
echarny/material2
node_modules/@angular/bazel/src/ng_module.bzl
Python
_ngc_tsconfig
_ngc_tsconfig
141
142
141
141
992eb5307580cbec1d678c1a627391e2097b2ee8
bigcode/the-stack
train
1aeb9f5e91689519a69b4f6d
train
function
def _devmode_compile_action(ctx, inputs, outputs, tsconfig_file, node_opts): outs = _expected_outs(ctx) compile_action_outputs = outputs + outs.devmode_js + outs.declarations + outs.summaries + outs.metadata _compile_action(ctx, inputs, compile_action_outputs, None, tsconfig_file, node_opts)
def _devmode_compile_action(ctx, inputs, outputs, tsconfig_file, node_opts):
outs = _expected_outs(ctx) compile_action_outputs = outputs + outs.devmode_js + outs.declarations + outs.summaries + outs.metadata _compile_action(ctx, inputs, compile_action_outputs, None, tsconfig_file, node_opts)
tsconfig_file, node_opts): outs = _expected_outs(ctx) return _compile_action(ctx, inputs, outputs + outs.closure_js, outs.i18n_messages, tsconfig_file, node_opts) def _devmode_compile_action(ctx, inputs, outputs, tsconfig_file, node_opts):
64
64
74
19
45
echarny/material2
node_modules/@angular/bazel/src/ng_module.bzl
Python
_devmode_compile_action
_devmode_compile_action
305
308
305
305
6305148d4e8ba707bda185f6fe65e19b115d5b21
bigcode/the-stack
train
926dbbb57843e8a22d274635
train
function
def _should_produce_flat_module_outs(ctx): """Should we produce flat module outputs. We only produce flat module outs when we expect the ng_module is meant to be published, based on the presence of the module_name attribute. Args: ctx: skylark rule execution context Returns: true iff we should run ...
def _should_produce_flat_module_outs(ctx):
"""Should we produce flat module outputs. We only produce flat module outs when we expect the ng_module is meant to be published, based on the presence of the module_name attribute. Args: ctx: skylark rule execution context Returns: true iff we should run the bundle_index_host to produce flat modul...
used for the flat module out (no extension) """ if hasattr(ctx.attr, "flat_module_out_file") and ctx.attr.flat_module_out_file: return ctx.attr.flat_module_out_file return "%s_public_index" % ctx.label.name def _should_produce_flat_module_outs(ctx):
64
64
99
11
52
echarny/material2
node_modules/@angular/bazel/src/ng_module.bzl
Python
_should_produce_flat_module_outs
_should_produce_flat_module_outs
46
58
46
46
afdff9876cceb36f246ccd7650eb31c8a687bb47
bigcode/the-stack
train
ae765664c530340908849e57
train
function
def _flat_module_out_file(ctx): """Provide a default for the flat_module_out_file attribute. We cannot use the default="" parameter of ctx.attr because the value is calculated from other attributes (name) Args: ctx: skylark rule execution context Returns: a basename used for the flat module out (no...
def _flat_module_out_file(ctx):
"""Provide a default for the flat_module_out_file attribute. We cannot use the default="" parameter of ctx.attr because the value is calculated from other attributes (name) Args: ctx: skylark rule execution context Returns: a basename used for the flat module out (no extension) """ if hasattr(c...
.short_path[len(ctx.label.package) + 1:-ext_len] # Return true if run with bazel (the open-sourced version of blaze), false if # run with blaze. def _is_bazel(): return not hasattr(native, "genmpm") def _flat_module_out_file(ctx):
64
64
116
8
56
echarny/material2
node_modules/@angular/bazel/src/ng_module.bzl
Python
_flat_module_out_file
_flat_module_out_file
30
44
30
30
0a74308ccd221f979db897d3c59c621723bbde62
bigcode/the-stack
train
59345c2c2e09be4b6c16a84a
train
class
class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: if k < 2: return head first_call = True node = head for i in range(0, self.length(head) // k): if first_call: first_call = False first, second = self....
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode: if k < 2: return head first_call = True node = head for i in range(0, self.length(head) // k): if first_call: first_call = False first, second = self.reverse_k(node, ...
-> int: l = 0 start = node while start: start = start.next l += 1 return l @classmethod def from_list(cls, my_list: List[int]) -> "ListNode": assert my_list start = cls(my_list[0]) cur = start for i in my_list[1:]: ...
104
104
347
3
100
BurnySc2/leetcode-solutions
python_src/025.py
Python
Solution
Solution
61
109
61
61
1b29aaf7029283d77ae6a594b89a99cd2b17b84f
bigcode/the-stack
train
c6bba4a0af7ea269ad896602
train
class
class ListNode: def __init__(self, val: int = 0, next: "ListNode" = None): self.val = val self.next = next def __eq__(self, other: "ListNode") -> bool: if not isinstance(other, ListNode): return False if self.length(self) != self.length(other): return Fa...
class ListNode:
def __init__(self, val: int = 0, next: "ListNode" = None): self.val = val self.next = next def __eq__(self, other: "ListNode") -> bool: if not isinstance(other, ListNode): return False if self.length(self) != self.length(other): return False fir...
""" Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. https://leetcode.com/problems/pascals-triangle/ """ from typing import List, Tuple class ListNode:
42
99
332
4
37
BurnySc2/leetcode-solutions
python_src/025.py
Python
ListNode
ListNode
9
58
9
9
6f3b5c09f5d94760e7d9d4af7bac8292e3cfe417
bigcode/the-stack
train
5d9fb047cf263f82f66fe23f
train
class
class GlobalWindow(BoundedWindow): """The default window into which all data is placed (via GlobalWindows).""" _instance = None # type: GlobalWindow def __new__(cls): if cls._instance is None: cls._instance = super(GlobalWindow, cls).__new__(cls) return cls._instance def __init__(self): # t...
class GlobalWindow(BoundedWindow):
"""The default window into which all data is placed (via GlobalWindows).""" _instance = None # type: GlobalWindow def __new__(cls): if cls._instance is None: cls._instance = super(GlobalWindow, cls).__new__(cls) return cls._instance def __init__(self): # type: () -> None super(GlobalWin...
): return hash((self.value, self.timestamp)) def __lt__(self, other): if type(self) != type(other): return type(self).__name__ < type(other).__name__ if self.value != other.value: return self.value < other.value return self.timestamp < other.timestamp class GlobalWindow(BoundedWindow):
73
73
245
7
65
NarimanAB/beam
sdks/python/apache_beam/transforms/window.py
Python
GlobalWindow
GlobalWindow
310
343
310
310
6421502ea446845944e392f6d0f518458346d226
bigcode/the-stack
train
c2e785858a378d703a36863d
train
class
class TimestampCombiner(object): """Determines how output timestamps of grouping operations are assigned.""" OUTPUT_AT_EOW = beam_runner_api_pb2.OutputTime.END_OF_WINDOW OUTPUT_AT_EARLIEST = beam_runner_api_pb2.OutputTime.EARLIEST_IN_PANE OUTPUT_AT_LATEST = beam_runner_api_pb2.OutputTime.LATEST_IN_PANE # TOD...
class TimestampCombiner(object):
"""Determines how output timestamps of grouping operations are assigned.""" OUTPUT_AT_EOW = beam_runner_api_pb2.OutputTime.END_OF_WINDOW OUTPUT_AT_EARLIEST = beam_runner_api_pb2.OutputTime.EARLIEST_IN_PANE OUTPUT_AT_LATEST = beam_runner_api_pb2.OutputTime.LATEST_IN_PANE # TODO(robertwb): Add this to the runn...
__ = [ 'TimestampCombiner', 'WindowFn', 'BoundedWindow', 'IntervalWindow', 'TimestampedValue', 'GlobalWindow', 'NonMergingWindowFn', 'GlobalWindows', 'FixedWindows', 'SlidingWindows', 'Sessions', ] # TODO(ccy): revisit naming and semantics once Java Apache Beam finalizes th...
90
90
301
6
84
NarimanAB/beam
sdks/python/apache_beam/transforms/window.py
Python
TimestampCombiner
TimestampCombiner
95
116
95
95
8fe120fa1ab7672c104f1956cf8f0b79813a579c
bigcode/the-stack
train
b3b9ac94038e5d437db31d96
train
class
class BoundedWindow(object): """A window for timestamps in range (-infinity, end). Attributes: end: End of window. """ def __init__(self, end): # type: (TimestampTypes) -> None self._end = Timestamp.of(end) @property def start(self): # type: () -> Timestamp raise NotImplementedError ...
class BoundedWindow(object):
"""A window for timestamps in range (-infinity, end). Attributes: end: End of window. """ def __init__(self, end): # type: (TimestampTypes) -> None self._end = Timestamp.of(end) @property def start(self): # type: () -> Timestamp raise NotImplementedError @property def end(self): ...
earliest of the timestamps returned by get_transformed_output_time() for elements of the window. Arguments: window: Output window of element. input_timestamp: Input timestamp of element as a timeutil.Timestamp object. Returns: Transformed timestamp. """ # By default,...
104
104
348
6
98
NarimanAB/beam
sdks/python/apache_beam/transforms/window.py
Python
BoundedWindow
BoundedWindow
200
255
200
200
5de935218700fd7a7662998aea165a1f027fa685
bigcode/the-stack
train
f44bb719e6fc44968f04dac6
train
class
class FixedWindows(NonMergingWindowFn): """A windowing function that assigns each element to one time interval. The attributes size and offset determine in what time interval a timestamp will be slotted. The time intervals have the following formula: [N * size + offset, (N + 1) * size + offset) Attributes: ...
class FixedWindows(NonMergingWindowFn):
"""A windowing function that assigns each element to one time interval. The attributes size and offset determine in what time interval a timestamp will be slotted. The time intervals have the following formula: [N * size + offset, (N + 1) * size + offset) Attributes: size: Size of the window as seconds....
type: (WindowFn.AssignContext) -> List[GlobalWindow] return [GlobalWindow()] def get_window_coder(self): # type: () -> coders.GlobalWindowCoder return coders.GlobalWindowCoder() def __hash__(self): return hash(type(self)) def __eq__(self, other): # Global windowfn is always and only equal ...
185
185
618
10
175
NarimanAB/beam
sdks/python/apache_beam/transforms/window.py
Python
FixedWindows
FixedWindows
393
460
393
393
93a2d578fff50a82690bf0fc6571b846bc4d47fe
bigcode/the-stack
train
4169ff3094cbf25978e8ab87
train
class
@total_ordering class IntervalWindow(windowed_value._IntervalWindowBase, BoundedWindow): """A window for timestamps in range [start, end). Attributes: start: Start of window as seconds since Unix epoch. end: End of window as seconds since Unix epoch. """ def __lt__(self, other): if self.end != othe...
@total_ordering class IntervalWindow(windowed_value._IntervalWindowBase, BoundedWindow):
"""A window for timestamps in range [start, end). Attributes: start: Start of window as seconds since Unix epoch. end: End of window as seconds since Unix epoch. """ def __lt__(self, other): if self.end != other.end: return self.end < other.end return hash(self) < hash(other) def inter...
other.end return hash(self) >= hash(other) def __hash__(self): raise NotImplementedError def __repr__(self): return '[?, %s)' % float(self.end) @total_ordering class IntervalWindow(windowed_value._IntervalWindowBase, BoundedWindow):
64
64
167
20
44
NarimanAB/beam
sdks/python/apache_beam/transforms/window.py
Python
IntervalWindow
IntervalWindow
258
278
258
259
f11c7e3e9aaadca0cef0957435bc7aeb974930c5
bigcode/the-stack
train
19a7fe34bff3991c1521219f
train
class
class SlidingWindows(NonMergingWindowFn): """A windowing function that assigns each element to a set of sliding windows. The attributes size and offset determine in what time interval a timestamp will be slotted. The time intervals have the following formula: [N * period + offset, N * period + offset + size) ...
class SlidingWindows(NonMergingWindowFn):
"""A windowing function that assigns each element to a set of sliding windows. The attributes size and offset determine in what time interval a timestamp will be slotted. The time intervals have the following formula: [N * period + offset, N * period + offset + size) Attributes: size: Size of the window...
self): return hash((self.size, self.offset)) def to_runner_api_parameter(self, context): return ( common_urns.fixed_windows.urn, standard_window_fns_pb2.FixedWindowsPayload( size=proto_utils.from_micros( duration_pb2.Duration, self.size.micros), offset=...
193
194
649
10
183
NarimanAB/beam
sdks/python/apache_beam/transforms/window.py
Python
SlidingWindows
SlidingWindows
463
534
463
463
49170755c28b3ef7f394283ebb2eb68477f17545
bigcode/the-stack
train
d3532675dc5f8020479a8450
train
class
class WindowFn(urns.RunnerApiFn, metaclass=abc.ABCMeta): """An abstract windowing function defining a basic assign and merge.""" class AssignContext(object): """Context passed to WindowFn.assign().""" def __init__( self, timestamp, # type: TimestampTypes element=None, # type: Optio...
class WindowFn(urns.RunnerApiFn, metaclass=abc.ABCMeta):
"""An abstract windowing function defining a basic assign and merge.""" class AssignContext(object): """Context passed to WindowFn.assign().""" def __init__( self, timestamp, # type: TimestampTypes element=None, # type: Optional[Any] window=None # type: Optional[BoundedWin...
.Enum, WindowFn) -> timeutil.TimestampCombinerImpl if timestamp_combiner == TimestampCombiner.OUTPUT_AT_EOW: return timeutil.OutputAtEndOfWindowImpl() elif timestamp_combiner == TimestampCombiner.OUTPUT_AT_EARLIEST: return timeutil.OutputAtEarliestInputTimestampImpl() elif timestamp_combiner == ...
172
172
575
19
153
NarimanAB/beam
sdks/python/apache_beam/transforms/window.py
Python
WindowFn
WindowFn
119
197
119
119
052949abfc655fccfa515642d55db2bdbf752d19
bigcode/the-stack
train
d5b5004addd6910ce045730c
train
class
@total_ordering class TimestampedValue(object): """A timestamped value having a value and a timestamp. Attributes: value: The underlying value. timestamp: Timestamp associated with the value as seconds since Unix epoch. """ def __init__(self, value, timestamp): # type: (Any, TimestampTypes) -> None...
@total_ordering class TimestampedValue(object):
"""A timestamped value having a value and a timestamp. Attributes: value: The underlying value. timestamp: Timestamp associated with the value as seconds since Unix epoch. """ def __init__(self, value, timestamp): # type: (Any, TimestampTypes) -> None self.value = value self.timestamp = Tim...
return other.start < self.end or self.start < other.end def union(self, other): # type: (IntervalWindow) -> IntervalWindow return IntervalWindow( min(self.start, other.start), max(self.end, other.end)) @total_ordering class TimestampedValue(object):
64
64
195
11
53
NarimanAB/beam
sdks/python/apache_beam/transforms/window.py
Python
TimestampedValue
TimestampedValue
281
307
281
282
ecdb5f06f24e1e98e75fc1a258bb8a3923da10be
bigcode/the-stack
train
b6ed091a145d5a4a9d5e2fd2
train
class
class GlobalWindows(NonMergingWindowFn): """A windowing function that assigns everything to one global window.""" @classmethod def windowed_value( cls, value, # type: Any timestamp=MIN_TIMESTAMP, # type: Timestamp pane_info=windowed_value.PANE_INFO_UNKNOWN # type: windowed_value.PaneInf...
class GlobalWindows(NonMergingWindowFn):
"""A windowing function that assigns everything to one global window.""" @classmethod def windowed_value( cls, value, # type: Any timestamp=MIN_TIMESTAMP, # type: Timestamp pane_info=windowed_value.PANE_INFO_UNKNOWN # type: windowed_value.PaneInfo ): # type: (...) -> WindowedValue...
_MAX_TIMESTAMP_MILLIS.constant) return Timestamp(micros=ts_millis * 1000) class NonMergingWindowFn(WindowFn): def is_merging(self): # type: () -> bool return False def merge(self, merge_context): # type: (WindowFn.MergeContext) -> None pass # No merging. class GlobalWindows(NonMergingWindowF...
88
88
294
10
78
NarimanAB/beam
sdks/python/apache_beam/transforms/window.py
Python
GlobalWindows
GlobalWindows
356
390
356
356
583b1975763cc2892959359b21817324e98d016f
bigcode/the-stack
train
d499c48108fef345eb6d2275
train
class
class Sessions(WindowFn): """A windowing function that groups elements into sessions. A session is defined as a series of consecutive events separated by a specified gap size. Attributes: gap_size: Size of the gap between windows as floating-point seconds. """ def __init__(self, gap_size): # type:...
class Sessions(WindowFn):
"""A windowing function that groups elements into sessions. A session is defined as a series of consecutive events separated by a specified gap size. Attributes: gap_size: Size of the gap between windows as floating-point seconds. """ def __init__(self, gap_size): # type: (DurationTypes) -> None ...
icros), offset=proto_utils.from_micros( timestamp_pb2.Timestamp, self.offset.micros), period=proto_utils.from_micros( duration_pb2.Duration, self.period.micros))) @staticmethod @urns.RunnerApiFn.register_urn( common_urns.sliding_windows.urn, stand...
163
164
548
5
158
NarimanAB/beam
sdks/python/apache_beam/transforms/window.py
Python
Sessions
Sessions
537
604
537
537
27e3557db6e55d2acb504ce18481cdbd8244bffa
bigcode/the-stack
train
bc799b094da1a7d1a22637e4
train
class
class NonMergingWindowFn(WindowFn): def is_merging(self): # type: () -> bool return False def merge(self, merge_context): # type: (WindowFn.MergeContext) -> None pass # No merging.
class NonMergingWindowFn(WindowFn):
def is_merging(self): # type: () -> bool return False def merge(self, merge_context): # type: (WindowFn.MergeContext) -> None pass # No merging.
def _getTimestampFromProto(): # type: () -> Timestamp ts_millis = int( common_urns.constants.GLOBAL_WINDOW_MAX_TIMESTAMP_MILLIS.constant) return Timestamp(micros=ts_millis * 1000) class NonMergingWindowFn(WindowFn):
64
64
56
9
55
NarimanAB/beam
sdks/python/apache_beam/transforms/window.py
Python
NonMergingWindowFn
NonMergingWindowFn
346
353
346
346
ce46098ef9d3bf42754cb02877760decf838ce2d
bigcode/the-stack
train
818c5fba7bfddce0101e1328
train
function
@app.route('/games') def get_games(): with open('game_info.json', 'r') as f: data = json.load(f) return render_template('games_view.html', pages = data['game_pages'])
@app.route('/games') def get_games():
with open('game_info.json', 'r') as f: data = json.load(f) return render_template('games_view.html', pages = data['game_pages'])
import Flask, render_template, jsonify, request import json, os from get_data import get_game_details app = Flask(__name__, template_folder='./templates/', static_folder='./static/') @app.route('/') def hello_world(): return render_template("index.html") @app.route('/games') def get_games():
64
64
46
9
55
ShubheshDixit/atnogames
app.py
Python
get_games
get_games
10
14
10
11
af10756a171c168715b20649a280d2dc7a183b77
bigcode/the-stack
train
3e4383a3472eed0192b90776
train
function
@app.route('/') def hello_world(): return render_template("index.html")
@app.route('/') def hello_world():
return render_template("index.html")
from flask import Flask, render_template, jsonify, request import json, os from get_data import get_game_details app = Flask(__name__, template_folder='./templates/', static_folder='./static/') @app.route('/') def hello_world():
48
64
15
7
41
ShubheshDixit/atnogames
app.py
Python
hello_world
hello_world
6
8
6
7
50f708249ca32e5c64e66848af786ecdbc998239
bigcode/the-stack
train
5d3d00a886eb3e28be134621
train
function
@app.route('/details') def get_data(): link = request.args.get('url') with open('game_info.json', 'r') as f: data = json.load(f) pages = data['game_pages'] for page in pages: g_list = page['games_list'] for game in g_list: g_link = game['link'] meta = game...
@app.route('/details') def get_data():
link = request.args.get('url') with open('game_info.json', 'r') as f: data = json.load(f) pages = data['game_pages'] for page in pages: g_list = page['games_list'] for game in g_list: g_link = game['link'] meta = game['meta_details'] if g_link ...
(): return render_template("index.html") @app.route('/games') def get_games(): with open('game_info.json', 'r') as f: data = json.load(f) return render_template('games_view.html', pages = data['game_pages']) @app.route('/details') def get_data():
64
64
97
9
55
ShubheshDixit/atnogames
app.py
Python
get_data
get_data
16
28
16
17
731bef2b87eb5c5da15785999038bc498d2c5f99
bigcode/the-stack
train
d84d062abc58246d6ebb688c
train
function
def run_trainer(config): random.seed(0) np.random.seed(0) torch.manual_seed(0) run_name_format = ( "d_model={d_model}-" "layers_count={layers_count}-" "heads_count={heads_count}-" "pe={positional_encoding}-" "optimizer={optimizer}-" "{timestamp}" ) ...
def run_trainer(config):
random.seed(0) np.random.seed(0) torch.manual_seed(0) run_name_format = ( "d_model={d_model}-" "layers_count={layers_count}-" "heads_count={heads_count}-" "pe={positional_encoding}-" "optimizer={optimizer}-" "{timestamp}" ) run_name = run_name_fo...
=1) parser.add_argument('--save_every', type=int, default=1) parser.add_argument('--vocabulary_size', type=int, default=None) parser.add_argument('--positional_encoding', action='store_true') parser.add_argument('--d_model', type=int, default=128) parser.add_argument('--layers_count', type=int, default=1) parser.add_...
216
216
720
6
210
Zenodia/nativePytorch_NMT
train.py
Python
run_trainer
run_trainer
53
143
53
53
2184f8614f00fbb62207d80f03dfc68adca0f647
bigcode/the-stack
train
5274e341903bb3d43bde31d4
train
class
class DetectionBbox(AnnotationBbox): """ Inherits from AnnotationBbox """ def __init__( self, left: int, top: int, right: int, bottom: int, label_idx: int, score: float, im_path: str = None, label_name: str = None, ): """ Initi...
class DetectionBbox(AnnotationBbox):
""" Inherits from AnnotationBbox """ def __init__( self, left: int, top: int, right: int, bottom: int, label_idx: int, score: float, im_path: str = None, label_name: str = None, ): """ Initialize DetectionBbox """ super...
def __repr__(self): name = ( "None" if self.label_name == str(self.label_idx) else self.label_name ) return f"{{{str(self)} | <{name}> | label:{self.label_idx} | path:{self.im_path}}}" class DetectionBbox(AnnotationBbox):
73
74
247
9
64
muminkoykiran/computervision-recipes
utils_cv/detection/bbox.py
Python
DetectionBbox
DetectionBbox
157
196
157
157
dd720d5f0e0c2d28d4870357bf42130385f2972e
bigcode/the-stack
train
aebd2b721c6ccef58fa20ce6
train
class
class AnnotationBbox(_Bbox): """ Inherits from Bbox """ def __init__( self, left: int, top: int, right: int, bottom: int, label_idx: int, im_path: str = None, label_name: str = None, ): """ Initialize AnnotationBbox """ super()...
class AnnotationBbox(_Bbox):
""" Inherits from Bbox """ def __init__( self, left: int, top: int, right: int, bottom: int, label_idx: int, im_path: str = None, label_name: str = None, ): """ Initialize AnnotationBbox """ super().__init__(left, top, right, b...
self.top + max_height self.standardize() return self def is_valid(self) -> bool: if self.left > self.right or self.top > self.bottom: return False if ( min(self.rect()) < -self.MAX_VALID_DIM or max(self.rect()) > self.MAX_VALID_DIM ): ...
87
87
291
8
78
muminkoykiran/computervision-recipes
utils_cv/detection/bbox.py
Python
AnnotationBbox
AnnotationBbox
116
154
116
116
e0f7b4c37f679bc5786c0577205ce8f779f776b4
bigcode/the-stack
train
c6241f6ed06f7f9aceebbdb0
train
class
class _Bbox: """ Util to represent bounding boxes Generally speaking, you should use either the AnnotationBbox or the DetectionBbox that inherit from this class. Source: https://github.com/Azure/ObjectDetectionUsingCntk/blob/master/helpers.py """ MAX_VALID_DIM = 100000 left = top = ri...
class _Bbox:
""" Util to represent bounding boxes Generally speaking, you should use either the AnnotationBbox or the DetectionBbox that inherit from this class. Source: https://github.com/Azure/ObjectDetectionUsingCntk/blob/master/helpers.py """ MAX_VALID_DIM = 100000 left = top = right = bottom ...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from typing import List, Union class _Bbox:
31
256
873
5
25
muminkoykiran/computervision-recipes
utils_cv/detection/bbox.py
Python
_Bbox
_Bbox
7
113
7
7
d895c6a4a6550444921e73105afe996d28412b29
bigcode/the-stack
train
4631fa13d95ab2c8766d67f5
train
function
def bboxes_iou(bbox1: DetectionBbox, bbox2: DetectionBbox): """Compute intersection-over-union between two bounding boxes Args: bbox1: First bounding box bbox2: Second bounding box Returns: Returns intersection-over-union of the two bounding boxes """ overlap_box = bbox1.ge...
def bboxes_iou(bbox1: DetectionBbox, bbox2: DetectionBbox):
"""Compute intersection-over-union between two bounding boxes Args: bbox1: First bounding box bbox2: Second bounding box Returns: Returns intersection-over-union of the two bounding boxes """ overlap_box = bbox1.get_overlap_bbox(bbox2) if overlap_box is not None: ...
bbox.__class__ = DetectionBbox bbox.score = score return bbox def __repr__(self): return f"{super().__repr__()} | score: {self.score}" def bboxes_iou(bbox1: DetectionBbox, bbox2: DetectionBbox):
63
64
167
20
43
muminkoykiran/computervision-recipes
utils_cv/detection/bbox.py
Python
bboxes_iou
bboxes_iou
199
220
199
199
4c1ef74f4be3764194f95ff79f53e35178869643
bigcode/the-stack
train
3ce572843e08334e4d284887
train
function
def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execpr...
def bctest(testDir, testObj, buildenv):
"""Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], ...
/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "bitcoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" inp...
256
256
918
13
243
minblock/torchcoin
test/util/bitcoin-util-test.py
Python
bctest
bctest
68
161
68
68
68bb25e33b4b2f5ff9ee7786b6aea6b0d337c06e
bigcode/the-stack
train
2751ff12fefeda5b953155c6
train
function
def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for...
def bctester(testDir, input_basename, buildenv):
""" Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: ...
/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "bitcoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv):
64
64
193
14
50
minblock/torchcoin
test/util/bitcoin-util-test.py
Python
bctester
bctester
44
66
44
44
17d443541212468c3dc5cddb2cee10da80b88cc2
bigcode/the-stack
train
9c276b464c76c31ea837fab2
train
function
def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v'...
def main():
config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose...
/licenses/mit-license.php. """Test framework for torchcoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main():
64
64
183
3
60
minblock/torchcoin
test/util/bitcoin-util-test.py
Python
main
main
23
42
23
23
7f418df174d47162f72fcce0d9c5fd96b2259354
bigcode/the-stack
train
98f0ef98b9ee56c13d2bd093
train
function
def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) ...
def parse_output(a, fmt):
"""Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise Not...
that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt):
64
64
97
7
56
minblock/torchcoin
test/util/bitcoin-util-test.py
Python
parse_output
parse_output
163
172
163
163
208f5044c273c1e633d62128695eb73de4e1a7cc
bigcode/the-stack
train
c3e28d1dd42469bbd021a247
train
class
class NegativeDistanceScore(object): def __init__(self): # pre-compute some values self.scores = {} self.scores[0.5] = self.compute_score_full(50, 0.5) self.scores[1.0] = self.compute_score_full(50, 1.0) self.scores[2.0] = self.compute_score_full(50, 2.0) def...
class NegativeDistanceScore(object):
def __init__(self): # pre-compute some values self.scores = {} self.scores[0.5] = self.compute_score_full(50, 0.5) self.scores[1.0] = self.compute_score_full(50, 1.0) self.scores[2.0] = self.compute_score_full(50, 2.0) def __call__(self, i, L, tau): i...
torch import torch.nn.functional as F from fairseq.models import register_model, register_model_architecture from fairseq.models.nat import ( LevenshteinTransformerDecoder, LevenshteinTransformerModel, FairseqNATModel, ensemble_decoder ) from fairseq.models.transformer import Linear from fa...
96
96
323
6
89
aiboxlab/TSPNet
fairseq/models/nat/insertion_transformer.py
Python
NegativeDistanceScore
NegativeDistanceScore
22
50
22
22
464039f6268dfa56b0122ebd7e3fc83d8e2e75f0
bigcode/the-stack
train
d32025638ea37c8c84b592b5
train
class
@register_model("insertion_transformer") class InsertionTransformerModel(LevenshteinTransformerModel): def __init__(self, args, encoder, decoder): super().__init__(args, encoder, decoder) @staticmethod def add_args(parser): FairseqNATModel.add_args(parser) parser.add_argumen...
@register_model("insertion_transformer") class InsertionTransformerModel(LevenshteinTransformerModel):
def __init__(self, args, encoder, decoder): super().__init__(args, encoder, decoder) @staticmethod def add_args(parser): FairseqNATModel.add_args(parser) parser.add_argument("--label-tau", default=None, type=float) @classmethod def build_decoder(cls, args, tgt_dict...
_ins_scores.masked_fill_(padding_masks, 0.0) word_ins_pred.masked_fill_(padding_masks, padding_idx) in_coords = new_arange(in_tokens).type_as(in_scores) # shift all padding predictions to infinite out_coords = (in_coords[:, 1:] - 0.5).masked_fill( word_ins_pred.eq(padding_idx), float("i...
189
189
632
22
166
aiboxlab/TSPNet
fairseq/models/nat/insertion_transformer.py
Python
InsertionTransformerModel
InsertionTransformerModel
120
206
120
121
3a1bc3f7c6b76d64874a72adf784baab13196efb
bigcode/the-stack
train
1005b75d721182bac0899a39
train
function
def _apply_ins_words(in_tokens, in_scores, word_ins_pred, word_ins_scores, padding_idx): padding_masks = in_tokens[:, 1:].eq(padding_idx) word_ins_scores.masked_fill_(padding_masks, 0.0) word_ins_pred.masked_fill_(padding_masks, padding_idx) in_coords = new_arange(in_tokens).type_as(in_scores) ...
def _apply_ins_words(in_tokens, in_scores, word_ins_pred, word_ins_scores, padding_idx):
padding_masks = in_tokens[:, 1:].eq(padding_idx) word_ins_scores.masked_fill_(padding_masks, 0.0) word_ins_pred.masked_fill_(padding_masks, padding_idx) in_coords = new_arange(in_tokens).type_as(in_scores) # shift all padding predictions to infinite out_coords = (in_coords[:, 1:] - 0.5)...
insert_label_tensors.scatter_(0, insert_index.long(), insert_labels) insert_label_tensors = insert_label_tensors.view(B, T - 1, V) return insert_label_tensors def _apply_ins_words(in_tokens, in_scores, word_ins_pred, word_ins_scores, padding_idx):
64
64
206
22
41
aiboxlab/TSPNet
fairseq/models/nat/insertion_transformer.py
Python
_apply_ins_words
_apply_ins_words
102
117
102
103
e167b2623d97c834638c0e9363d87415d749a8ac
bigcode/the-stack
train
1616f466f119a22e7af07e8c
train
class
class InsertionTransformerDecoder(LevenshteinTransformerDecoder): def __init__(self, args, dictionary, embed_tokens, no_encoder_attn=False): # use the TransformerDecoder's __init__ super(LevenshteinTransformerDecoder, self).__init__( args, dictionary, embed_tokens, no_encoder_attn=no...
class InsertionTransformerDecoder(LevenshteinTransformerDecoder):
def __init__(self, args, dictionary, embed_tokens, no_encoder_attn=False): # use the TransformerDecoder's __init__ super(LevenshteinTransformerDecoder, self).__init__( args, dictionary, embed_tokens, no_encoder_attn=no_encoder_attn ) self.dictionary = dictionary ...
output_tokens = output_tokens[:, :cut_off] output_scores = output_scores[:, :cut_off] if history is not None: history.append(output_tokens.clone()) return decoder_out._replace( output_tokens=output_tokens, output_scores=output_scores, a...
82
83
278
13
69
aiboxlab/TSPNet
fairseq/models/nat/insertion_transformer.py
Python
InsertionTransformerDecoder
InsertionTransformerDecoder
209
237
209
209
9a5c96d716fc1ff3f496b82df343ec93de884eeb
bigcode/the-stack
train
6644debac34c3cc939296601
train
function
@register_model_architecture("insertion_transformer", "insertion_transformer") def insertion_base_architecture(args): args.encoder_embed_path = getattr(args, "encoder_embed_path", None) args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512) args.encoder_ffn_embed_dim = getattr(args, "encoder_f...
@register_model_architecture("insertion_transformer", "insertion_transformer") def insertion_base_architecture(args):
args.encoder_embed_path = getattr(args, "encoder_embed_path", None) args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512) args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 2048) args.encoder_layers = getattr(args, "encoder_layers", 6) args.encoder_attention_heads = g...
"label_tau", None) @ensemble_decoder def forward_word_ins(self, normalize, encoder_out, prev_output_tokens): features = self.extract_features(prev_output_tokens, encoder_out=encoder_out)[0] features = self.pool_out( torch.cat([features[:, :-1, :], features[:, 1:, :]], 2) ...
165
165
550
24
140
aiboxlab/TSPNet
fairseq/models/nat/insertion_transformer.py
Python
insertion_base_architecture
insertion_base_architecture
240
280
240
241
6bc65169ae1feb16cdb540b6c20a8229b3e95da4
bigcode/the-stack
train
1ffad268412cac66845edcd7
train
function
def _get_ins_targets(in_tokens, out_tokens, padding_idx, unk_idx, vocab_size, tau=None): try: from fairseq import libnat except ImportError as e: import sys sys.stderr.write('ERROR: missing libnat. run `pip install --editable .`\n') raise e B = in_tokens.size(0) ...
def _get_ins_targets(in_tokens, out_tokens, padding_idx, unk_idx, vocab_size, tau=None):
try: from fairseq import libnat except ImportError as e: import sys sys.stderr.write('ERROR: missing libnat. run `pip install --editable .`\n') raise e B = in_tokens.size(0) T = in_tokens.size(1) V = vocab_size with torch.cuda.device_of(in_tokens): ...
tau): s = -abs(np.arange(0, L - 1)[:, None] / 2 - np.arange(L)[None, :]) / tau s = np.tril(s, 0) + np.triu(s - float("inf"), 1) s = np.exp(s - s.max(1, keepdims=True)) return s / s.sum(1, keepdims=True) neg_scorer = NegativeDistanceScore() def _get_ins_targets(in_tokens, out_to...
120
120
401
23
97
aiboxlab/TSPNet
fairseq/models/nat/insertion_transformer.py
Python
_get_ins_targets
_get_ins_targets
56
99
56
56
f3b4ad22a010e3b7887a840a2a0702d815b58141
bigcode/the-stack
train
da775c8145355ffd9fe84144
train
class
class Migration(migrations.Migration): dependencies = [ ('auctions', '0001_initial'), ] operations = [ migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),...
class Migration(migrations.Migration):
dependencies = [ ('auctions', '0001_initial'), ] operations = [ migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), migra...
# Generated by Django 3.0.3 on 2020-02-26 07:39 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
51
78
261
7
43
dariangarcia-404/breezy-palm-tree
full-stack-work/mock-ecommerce/commerce/auctions/migrations/0002_bid_comment_listing.py
Python
Migration
Migration
8
40
8
9
ae035625110b551603f6ea91289dc5bc673a59c5
bigcode/the-stack
train
a7250dcf1a4fa29c3e78d9b7
train
function
def sendDeployToOtherSystemManagers(node_name, node_names, sysmgr_address, type, file_name, data): """ Handles a message from the rest server to the active system manager to distribute an egg to other system managers. :param node_name: The name of this node :type node_name: str :param node_name...
def sendDeployToOtherSystemManagers(node_name, node_names, sysmgr_address, type, file_name, data):
""" Handles a message from the rest server to the active system manager to distribute an egg to other system managers. :param node_name: The name of this node :type node_name: str :param node_names: The list of nodes in the system, so that the active system manager can send a deploy egg message...
""" Copyright (c) IBM 2015-2017. All Rights Reserved. Project name: c4-system-manager This project is licensed under the MIT License, see LICENSE """ import logging import base64 import os import subprocess from c4.messaging import RouterClient from c4.system.messages import DeployDeviceManager, UndeployDeviceManager ...
99
108
362
24
74
Brewgarten/c4-system-manager
c4/system/egg.py
Python
sendDeployToOtherSystemManagers
sendDeployToOtherSystemManagers
14
43
14
14
e1e98d9ec7698ed845a9a24658d62065a9605e33
bigcode/the-stack
train