repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
spacetelescope/drizzlepac
drizzlepac/tweakutils.py
gauss
def gauss(x, sigma): """ Compute 1-D value of gaussian at position x relative to center.""" return (np.exp(-np.power(x, 2) / (2 * np.power(sigma, 2))) / (sigma * np.sqrt(2 * np.pi)))
python
def gauss(x, sigma): """ Compute 1-D value of gaussian at position x relative to center.""" return (np.exp(-np.power(x, 2) / (2 * np.power(sigma, 2))) / (sigma * np.sqrt(2 * np.pi)))
[ "def", "gauss", "(", "x", ",", "sigma", ")", ":", "return", "(", "np", ".", "exp", "(", "-", "np", ".", "power", "(", "x", ",", "2", ")", "/", "(", "2", "*", "np", ".", "power", "(", "sigma", ",", "2", ")", ")", ")", "/", "(", "sigma", ...
Compute 1-D value of gaussian at position x relative to center.
[ "Compute", "1", "-", "D", "value", "of", "gaussian", "at", "position", "x", "relative", "to", "center", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/tweakutils.py#L721-L724
train
35,700
spacetelescope/drizzlepac
drizzlepac/tweakutils.py
find_xy_peak
def find_xy_peak(img, center=None, sigma=3.0): """ Find the center of the peak of offsets """ # find level of noise in histogram istats = imagestats.ImageStats(img.astype(np.float32), nclip=1, fields='stddev,mode,mean,max,min') if istats.stddev == 0.0: istats = imagestats.ImageStats(img.astype(np.float32), fields='stddev,mode,mean,max,min') imgsum = img.sum() # clip out all values below mean+3*sigma from histogram imgc = img[:, :].copy() imgc[imgc < istats.mode + istats.stddev * sigma] = 0.0 # identify position of peak yp0, xp0 = np.where(imgc == imgc.max()) # Perform bounds checking on slice from img ymin = max(0, int(yp0[0]) - 3) ymax = min(img.shape[0], int(yp0[0]) + 4) xmin = max(0, int(xp0[0]) - 3) xmax = min(img.shape[1], int(xp0[0]) + 4) # take sum of at most a 7x7 pixel box around peak xp_slice = (slice(ymin, ymax), slice(xmin, xmax)) yp, xp = ndimage.measurements.center_of_mass(img[xp_slice]) if np.isnan(xp) or np.isnan(yp): xp = 0.0 yp = 0.0 flux = 0.0 zpqual = None else: xp += xp_slice[1].start yp += xp_slice[0].start # compute S/N criteria for this peak: flux/sqrt(mean of rest of array) flux = imgc[xp_slice].sum() delta_size = float(img.size - imgc[xp_slice].size) if delta_size == 0: delta_size = 1 delta_flux = float(imgsum - flux) if flux > imgc[xp_slice].max(): delta_flux = flux - imgc[xp_slice].max() else: delta_flux = flux zpqual = flux / np.sqrt(delta_flux / delta_size) if np.isnan(zpqual) or np.isinf(zpqual): zpqual = None if center is not None: xp -= center[0] yp -= center[1] flux = imgc[xp_slice].max() del imgc return xp, yp, flux, zpqual
python
def find_xy_peak(img, center=None, sigma=3.0): """ Find the center of the peak of offsets """ # find level of noise in histogram istats = imagestats.ImageStats(img.astype(np.float32), nclip=1, fields='stddev,mode,mean,max,min') if istats.stddev == 0.0: istats = imagestats.ImageStats(img.astype(np.float32), fields='stddev,mode,mean,max,min') imgsum = img.sum() # clip out all values below mean+3*sigma from histogram imgc = img[:, :].copy() imgc[imgc < istats.mode + istats.stddev * sigma] = 0.0 # identify position of peak yp0, xp0 = np.where(imgc == imgc.max()) # Perform bounds checking on slice from img ymin = max(0, int(yp0[0]) - 3) ymax = min(img.shape[0], int(yp0[0]) + 4) xmin = max(0, int(xp0[0]) - 3) xmax = min(img.shape[1], int(xp0[0]) + 4) # take sum of at most a 7x7 pixel box around peak xp_slice = (slice(ymin, ymax), slice(xmin, xmax)) yp, xp = ndimage.measurements.center_of_mass(img[xp_slice]) if np.isnan(xp) or np.isnan(yp): xp = 0.0 yp = 0.0 flux = 0.0 zpqual = None else: xp += xp_slice[1].start yp += xp_slice[0].start # compute S/N criteria for this peak: flux/sqrt(mean of rest of array) flux = imgc[xp_slice].sum() delta_size = float(img.size - imgc[xp_slice].size) if delta_size == 0: delta_size = 1 delta_flux = float(imgsum - flux) if flux > imgc[xp_slice].max(): delta_flux = flux - imgc[xp_slice].max() else: delta_flux = flux zpqual = flux / np.sqrt(delta_flux / delta_size) if np.isnan(zpqual) or np.isinf(zpqual): zpqual = None if center is not None: xp -= center[0] yp -= center[1] flux = imgc[xp_slice].max() del imgc return xp, yp, flux, zpqual
[ "def", "find_xy_peak", "(", "img", ",", "center", "=", "None", ",", "sigma", "=", "3.0", ")", ":", "# find level of noise in histogram", "istats", "=", "imagestats", ".", "ImageStats", "(", "img", ".", "astype", "(", "np", ".", "float32", ")", ",", "nclip"...
Find the center of the peak of offsets
[ "Find", "the", "center", "of", "the", "peak", "of", "offsets" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/tweakutils.py#L1000-L1054
train
35,701
spacetelescope/drizzlepac
drizzlepac/tweakutils.py
plot_zeropoint
def plot_zeropoint(pars): """ Plot 2d histogram. Pars will be a dictionary containing: data, figure_id, vmax, title_str, xp,yp, searchrad """ from matplotlib import pyplot as plt xp = pars['xp'] yp = pars['yp'] searchrad = int(pars['searchrad'] + 0.5) plt.figure(num=pars['figure_id']) plt.clf() if pars['interactive']: plt.ion() else: plt.ioff() plt.imshow(pars['data'], vmin=0, vmax=pars['vmax'], interpolation='nearest') plt.viridis() plt.colorbar() plt.title(pars['title_str']) plt.plot(xp + searchrad, yp + searchrad, color='red', marker='+', markersize=24) plt.plot(searchrad, searchrad, color='yellow', marker='+', markersize=120) plt.text(searchrad, searchrad, "Offset=0,0", verticalalignment='bottom', color='yellow') plt.xlabel("Offset in X (pixels)") plt.ylabel("Offset in Y (pixels)") if pars['interactive']: plt.show() if pars['plotname']: suffix = pars['plotname'][-4:] output = pars['plotname'] if '.' not in suffix: output += '.png' format = 'png' else: if suffix[1:] in ['png', 'pdf', 'ps', 'eps', 'svg']: format = suffix[1:] plt.savefig(output, format=format)
python
def plot_zeropoint(pars): """ Plot 2d histogram. Pars will be a dictionary containing: data, figure_id, vmax, title_str, xp,yp, searchrad """ from matplotlib import pyplot as plt xp = pars['xp'] yp = pars['yp'] searchrad = int(pars['searchrad'] + 0.5) plt.figure(num=pars['figure_id']) plt.clf() if pars['interactive']: plt.ion() else: plt.ioff() plt.imshow(pars['data'], vmin=0, vmax=pars['vmax'], interpolation='nearest') plt.viridis() plt.colorbar() plt.title(pars['title_str']) plt.plot(xp + searchrad, yp + searchrad, color='red', marker='+', markersize=24) plt.plot(searchrad, searchrad, color='yellow', marker='+', markersize=120) plt.text(searchrad, searchrad, "Offset=0,0", verticalalignment='bottom', color='yellow') plt.xlabel("Offset in X (pixels)") plt.ylabel("Offset in Y (pixels)") if pars['interactive']: plt.show() if pars['plotname']: suffix = pars['plotname'][-4:] output = pars['plotname'] if '.' not in suffix: output += '.png' format = 'png' else: if suffix[1:] in ['png', 'pdf', 'ps', 'eps', 'svg']: format = suffix[1:] plt.savefig(output, format=format)
[ "def", "plot_zeropoint", "(", "pars", ")", ":", "from", "matplotlib", "import", "pyplot", "as", "plt", "xp", "=", "pars", "[", "'xp'", "]", "yp", "=", "pars", "[", "'yp'", "]", "searchrad", "=", "int", "(", "pars", "[", "'searchrad'", "]", "+", "0.5"...
Plot 2d histogram. Pars will be a dictionary containing: data, figure_id, vmax, title_str, xp,yp, searchrad
[ "Plot", "2d", "histogram", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/tweakutils.py#L1057-L1101
train
35,702
spacetelescope/drizzlepac
drizzlepac/tweakutils.py
build_xy_zeropoint
def build_xy_zeropoint(imgxy, refxy, searchrad=3.0, histplot=False, figure_id=1, plotname=None, interactive=True): """ Create a matrix which contains the delta between each XY position and each UV position. """ print('Computing initial guess for X and Y shifts...') # run C function to create ZP matrix zpmat = cdriz.arrxyzero(imgxy.astype(np.float32), refxy.astype(np.float32), searchrad) xp, yp, flux, zpqual = find_xy_peak(zpmat, center=(searchrad, searchrad)) if zpqual is not None: print('Found initial X and Y shifts of ', xp, yp) print(' with significance of ', zpqual, 'and ', flux, ' matches') else: # try with a lower sigma to detect a peak in a sparse set of sources xp, yp, flux, zpqual = find_xy_peak( zpmat, center=(searchrad, searchrad), sigma=1.0 ) if zpqual: print('Found initial X and Y shifts of ', xp, yp) print(' with significance of ', zpqual, 'and ', flux, ' matches') else: print('!' * 80) print('!') print('! WARNING: No valid shift found within a search radius of ', searchrad, ' pixels.') print('!') print('!' * 80) if histplot: zpstd = flux // 5 if zpstd < 10: zpstd = 10 if zpqual is None: zpstd = 10 title_str = ("Histogram of offsets: Peak has %d matches at " "(%0.4g, %0.4g)" % (flux, xp, yp)) plot_pars = {'data': zpmat, 'figure_id': figure_id, 'vmax': zpstd, 'xp': xp, 'yp': yp, 'searchrad': searchrad, 'title_str': title_str, 'plotname': plotname, 'interactive': interactive} plot_zeropoint(plot_pars) return xp, yp, flux, zpqual
python
def build_xy_zeropoint(imgxy, refxy, searchrad=3.0, histplot=False, figure_id=1, plotname=None, interactive=True): """ Create a matrix which contains the delta between each XY position and each UV position. """ print('Computing initial guess for X and Y shifts...') # run C function to create ZP matrix zpmat = cdriz.arrxyzero(imgxy.astype(np.float32), refxy.astype(np.float32), searchrad) xp, yp, flux, zpqual = find_xy_peak(zpmat, center=(searchrad, searchrad)) if zpqual is not None: print('Found initial X and Y shifts of ', xp, yp) print(' with significance of ', zpqual, 'and ', flux, ' matches') else: # try with a lower sigma to detect a peak in a sparse set of sources xp, yp, flux, zpqual = find_xy_peak( zpmat, center=(searchrad, searchrad), sigma=1.0 ) if zpqual: print('Found initial X and Y shifts of ', xp, yp) print(' with significance of ', zpqual, 'and ', flux, ' matches') else: print('!' * 80) print('!') print('! WARNING: No valid shift found within a search radius of ', searchrad, ' pixels.') print('!') print('!' * 80) if histplot: zpstd = flux // 5 if zpstd < 10: zpstd = 10 if zpqual is None: zpstd = 10 title_str = ("Histogram of offsets: Peak has %d matches at " "(%0.4g, %0.4g)" % (flux, xp, yp)) plot_pars = {'data': zpmat, 'figure_id': figure_id, 'vmax': zpstd, 'xp': xp, 'yp': yp, 'searchrad': searchrad, 'title_str': title_str, 'plotname': plotname, 'interactive': interactive} plot_zeropoint(plot_pars) return xp, yp, flux, zpqual
[ "def", "build_xy_zeropoint", "(", "imgxy", ",", "refxy", ",", "searchrad", "=", "3.0", ",", "histplot", "=", "False", ",", "figure_id", "=", "1", ",", "plotname", "=", "None", ",", "interactive", "=", "True", ")", ":", "print", "(", "'Computing initial gue...
Create a matrix which contains the delta between each XY position and each UV position.
[ "Create", "a", "matrix", "which", "contains", "the", "delta", "between", "each", "XY", "position", "and", "each", "UV", "position", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/tweakutils.py#L1105-L1154
train
35,703
spacetelescope/drizzlepac
drizzlepac/tweakutils.py
build_pos_grid
def build_pos_grid(start, end, nstep, mesh=False): """ Return a grid of positions starting at X,Y given by 'start', and ending at X,Y given by 'end'. The grid will be completely filled in X and Y by every 'step' interval. """ # Build X and Y arrays dx = end[0] - start[0] if dx < 0: nstart = end end = start start = nstart dx = -dx stepx = dx / nstep # Perform linear fit to find exact line that connects start and end xarr = np.arange(start[0], end[0] + stepx / 2.0, stepx) yarr = np.interp(xarr, [start[0], end[0]], [start[1], end[1]]) # create grid of positions if mesh: xa, ya = np.meshgrid(xarr, yarr) xarr = xa.ravel() yarr = ya.ravel() return xarr, yarr
python
def build_pos_grid(start, end, nstep, mesh=False): """ Return a grid of positions starting at X,Y given by 'start', and ending at X,Y given by 'end'. The grid will be completely filled in X and Y by every 'step' interval. """ # Build X and Y arrays dx = end[0] - start[0] if dx < 0: nstart = end end = start start = nstart dx = -dx stepx = dx / nstep # Perform linear fit to find exact line that connects start and end xarr = np.arange(start[0], end[0] + stepx / 2.0, stepx) yarr = np.interp(xarr, [start[0], end[0]], [start[1], end[1]]) # create grid of positions if mesh: xa, ya = np.meshgrid(xarr, yarr) xarr = xa.ravel() yarr = ya.ravel() return xarr, yarr
[ "def", "build_pos_grid", "(", "start", ",", "end", ",", "nstep", ",", "mesh", "=", "False", ")", ":", "# Build X and Y arrays", "dx", "=", "end", "[", "0", "]", "-", "start", "[", "0", "]", "if", "dx", "<", "0", ":", "nstart", "=", "end", "end", ...
Return a grid of positions starting at X,Y given by 'start', and ending at X,Y given by 'end'. The grid will be completely filled in X and Y by every 'step' interval.
[ "Return", "a", "grid", "of", "positions", "starting", "at", "X", "Y", "given", "by", "start", "and", "ending", "at", "X", "Y", "given", "by", "end", ".", "The", "grid", "will", "be", "completely", "filled", "in", "X", "and", "Y", "by", "every", "step...
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/tweakutils.py#L1158-L1182
train
35,704
spacetelescope/drizzlepac
drizzlepac/wfpc2Data.py
WFPC2InputImage.doUnitConversions
def doUnitConversions(self): """ Apply unit conversions to all the chips, ignoring the group parameter. This insures that all the chips get the same conversions when this gets done, even if only 1 chip was specified to be processed. """ # Image information _handle = fileutil.openImage(self._filename, mode='readonly', memmap=False) # Now convert the SCI array(s) units for det in range(1,self._numchips+1): chip=self._image[self.scienceExt,det] conversionFactor = 1.0 # add D2IMFILE to outputNames for removal by 'clean()' method later if 'D2IMFILE' in _handle[0].header and _handle[0].header['D2IMFILE'] not in ["","N/A"]: chip.outputNames['d2imfile'] = _handle[0].header['D2IMFILE'] if chip._gain is not None: """ # Multiply the values of the sci extension pixels by the gain. print "Converting %s[%d] from COUNTS to ELECTRONS"%(self._filename,det) # If the exptime is 0 the science image will be zeroed out. np.multiply(_handle[self.scienceExt,det].data,chip._gain,_handle[self.scienceExt,det].data) chip.data=_handle[self.scienceExt,det].data # Set the BUNIT keyword to 'electrons' chip._bunit = 'ELECTRONS' chip.header.update('BUNIT','ELECTRONS') _handle[self.scienceExt,det].header.update('BUNIT','ELECTRONS') # Update the PHOTFLAM value photflam = _handle[self.scienceExt,det].header['PHOTFLAM'] _handle[self.scienceExt,det].header.update('PHOTFLAM',(photflam/chip._gain)) """ conversionFactor = chip._gain chip._effGain = chip._gain #1. chip._conversionFactor = conversionFactor #1. else: msg = "Invalid gain value for data, no conversion done" print(msg) raise ValueError(msg) # Close the files and clean-up _handle.close() self._effGain = conversionFactor
python
def doUnitConversions(self): """ Apply unit conversions to all the chips, ignoring the group parameter. This insures that all the chips get the same conversions when this gets done, even if only 1 chip was specified to be processed. """ # Image information _handle = fileutil.openImage(self._filename, mode='readonly', memmap=False) # Now convert the SCI array(s) units for det in range(1,self._numchips+1): chip=self._image[self.scienceExt,det] conversionFactor = 1.0 # add D2IMFILE to outputNames for removal by 'clean()' method later if 'D2IMFILE' in _handle[0].header and _handle[0].header['D2IMFILE'] not in ["","N/A"]: chip.outputNames['d2imfile'] = _handle[0].header['D2IMFILE'] if chip._gain is not None: """ # Multiply the values of the sci extension pixels by the gain. print "Converting %s[%d] from COUNTS to ELECTRONS"%(self._filename,det) # If the exptime is 0 the science image will be zeroed out. np.multiply(_handle[self.scienceExt,det].data,chip._gain,_handle[self.scienceExt,det].data) chip.data=_handle[self.scienceExt,det].data # Set the BUNIT keyword to 'electrons' chip._bunit = 'ELECTRONS' chip.header.update('BUNIT','ELECTRONS') _handle[self.scienceExt,det].header.update('BUNIT','ELECTRONS') # Update the PHOTFLAM value photflam = _handle[self.scienceExt,det].header['PHOTFLAM'] _handle[self.scienceExt,det].header.update('PHOTFLAM',(photflam/chip._gain)) """ conversionFactor = chip._gain chip._effGain = chip._gain #1. chip._conversionFactor = conversionFactor #1. else: msg = "Invalid gain value for data, no conversion done" print(msg) raise ValueError(msg) # Close the files and clean-up _handle.close() self._effGain = conversionFactor
[ "def", "doUnitConversions", "(", "self", ")", ":", "# Image information", "_handle", "=", "fileutil", ".", "openImage", "(", "self", ".", "_filename", ",", "mode", "=", "'readonly'", ",", "memmap", "=", "False", ")", "# Now convert the SCI array(s) units", "for", ...
Apply unit conversions to all the chips, ignoring the group parameter. This insures that all the chips get the same conversions when this gets done, even if only 1 chip was specified to be processed.
[ "Apply", "unit", "conversions", "to", "all", "the", "chips", "ignoring", "the", "group", "parameter", ".", "This", "insures", "that", "all", "the", "chips", "get", "the", "same", "conversions", "when", "this", "gets", "done", "even", "if", "only", "1", "ch...
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/wfpc2Data.py#L182-L227
train
35,705
spacetelescope/drizzlepac
drizzlepac/wfpc2Data.py
WFPC2InputImage.getdarkcurrent
def getdarkcurrent(self,exten): """ Return the dark current for the WFPC2 detector. This value will be contained within an instrument specific keyword. The value in the image header will be converted to units of electrons. Returns ------- darkcurrent : float Dark current for the WFPC3 detector in **units of counts/electrons**. """ darkrate = 0.005 # electrons / s if self.proc_unit == 'native': darkrate = darkrate / self.getGain(exten) #count/s try: chip = self._image[0] darkcurrent = chip.header['DARKTIME'] * darkrate except: msg = "#############################################\n" msg += "# #\n" msg += "# Error: #\n" msg += "# Cannot find the value for 'DARKTIME' #\n" msg += "# in the image header. WFPC2 input #\n" msg += "# images are expected to have this header #\n" msg += "# keyword. #\n" msg += "# #\n" msg += "# Error occured in the WFPC2InputImage class#\n" msg += "# #\n" msg += "#############################################\n" raise ValueError(msg) return darkcurrent
python
def getdarkcurrent(self,exten): """ Return the dark current for the WFPC2 detector. This value will be contained within an instrument specific keyword. The value in the image header will be converted to units of electrons. Returns ------- darkcurrent : float Dark current for the WFPC3 detector in **units of counts/electrons**. """ darkrate = 0.005 # electrons / s if self.proc_unit == 'native': darkrate = darkrate / self.getGain(exten) #count/s try: chip = self._image[0] darkcurrent = chip.header['DARKTIME'] * darkrate except: msg = "#############################################\n" msg += "# #\n" msg += "# Error: #\n" msg += "# Cannot find the value for 'DARKTIME' #\n" msg += "# in the image header. WFPC2 input #\n" msg += "# images are expected to have this header #\n" msg += "# keyword. #\n" msg += "# #\n" msg += "# Error occured in the WFPC2InputImage class#\n" msg += "# #\n" msg += "#############################################\n" raise ValueError(msg) return darkcurrent
[ "def", "getdarkcurrent", "(", "self", ",", "exten", ")", ":", "darkrate", "=", "0.005", "# electrons / s", "if", "self", ".", "proc_unit", "==", "'native'", ":", "darkrate", "=", "darkrate", "/", "self", ".", "getGain", "(", "exten", ")", "#count/s", "try"...
Return the dark current for the WFPC2 detector. This value will be contained within an instrument specific keyword. The value in the image header will be converted to units of electrons. Returns ------- darkcurrent : float Dark current for the WFPC3 detector in **units of counts/electrons**.
[ "Return", "the", "dark", "current", "for", "the", "WFPC2", "detector", ".", "This", "value", "will", "be", "contained", "within", "an", "instrument", "specific", "keyword", ".", "The", "value", "in", "the", "image", "header", "will", "be", "converted", "to",...
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/wfpc2Data.py#L229-L264
train
35,706
spacetelescope/drizzlepac
drizzlepac/catalogs.py
generateCatalog
def generateCatalog(wcs, mode='automatic', catalog=None, src_find_filters=None, **kwargs): """ Function which determines what type of catalog object needs to be instantiated based on what type of source selection algorithm the user specified. Parameters ---------- wcs : obj WCS object generated by STWCS or PyWCS catalog : str or ndarray Filename of existing catalog or ndarray of image for generation of source catalog. kwargs : dict Parameters needed to interpret source catalog from input catalog with `findmode` being required. Returns ------- catalog : obj A Catalog-based class instance for keeping track of WCS and associated source catalog """ if not isinstance(catalog,Catalog): if mode == 'automatic': # if an array is provided as the source # Create a new catalog directly from the image catalog = ImageCatalog(wcs,catalog,src_find_filters,**kwargs) else: # a catalog file was provided as the catalog source catalog = UserCatalog(wcs,catalog,**kwargs) return catalog
python
def generateCatalog(wcs, mode='automatic', catalog=None, src_find_filters=None, **kwargs): """ Function which determines what type of catalog object needs to be instantiated based on what type of source selection algorithm the user specified. Parameters ---------- wcs : obj WCS object generated by STWCS or PyWCS catalog : str or ndarray Filename of existing catalog or ndarray of image for generation of source catalog. kwargs : dict Parameters needed to interpret source catalog from input catalog with `findmode` being required. Returns ------- catalog : obj A Catalog-based class instance for keeping track of WCS and associated source catalog """ if not isinstance(catalog,Catalog): if mode == 'automatic': # if an array is provided as the source # Create a new catalog directly from the image catalog = ImageCatalog(wcs,catalog,src_find_filters,**kwargs) else: # a catalog file was provided as the catalog source catalog = UserCatalog(wcs,catalog,**kwargs) return catalog
[ "def", "generateCatalog", "(", "wcs", ",", "mode", "=", "'automatic'", ",", "catalog", "=", "None", ",", "src_find_filters", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "catalog", ",", "Catalog", ")", ":", "if", "mod...
Function which determines what type of catalog object needs to be instantiated based on what type of source selection algorithm the user specified. Parameters ---------- wcs : obj WCS object generated by STWCS or PyWCS catalog : str or ndarray Filename of existing catalog or ndarray of image for generation of source catalog. kwargs : dict Parameters needed to interpret source catalog from input catalog with `findmode` being required. Returns ------- catalog : obj A Catalog-based class instance for keeping track of WCS and associated source catalog
[ "Function", "which", "determines", "what", "type", "of", "catalog", "object", "needs", "to", "be", "instantiated", "based", "on", "what", "type", "of", "source", "selection", "algorithm", "the", "user", "specified", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/catalogs.py#L43-L76
train
35,707
spacetelescope/drizzlepac
drizzlepac/catalogs.py
Catalog.generateRaDec
def generateRaDec(self): """ Convert XY positions into sky coordinates using STWCS methods. """ self.prefix = self.PAR_PREFIX if not isinstance(self.wcs,pywcs.WCS): print( textutil.textbox( 'WCS not a valid PyWCS object. ' 'Conversion of RA/Dec not possible...' ), file=sys.stderr ) raise ValueError if self.xypos is None or len(self.xypos[0]) == 0: self.xypos = None warnstr = textutil.textbox( 'WARNING: \n' 'No objects found for this image...' ) for line in warnstr.split('\n'): log.warning(line) print(warnstr) return if self.radec is None: print(' Found {:d} objects.'.format(len(self.xypos[0]))) if self.wcs is not None: ra, dec = self.wcs.all_pix2world(self.xypos[0], self.xypos[1], self.origin) self.radec = [ra, dec] + copy.deepcopy(self.xypos[2:]) else: # If we have no WCS, simply pass along the XY input positions # under the assumption they were already sky positions. self.radec = copy.deepcopy(self.xypos)
python
def generateRaDec(self): """ Convert XY positions into sky coordinates using STWCS methods. """ self.prefix = self.PAR_PREFIX if not isinstance(self.wcs,pywcs.WCS): print( textutil.textbox( 'WCS not a valid PyWCS object. ' 'Conversion of RA/Dec not possible...' ), file=sys.stderr ) raise ValueError if self.xypos is None or len(self.xypos[0]) == 0: self.xypos = None warnstr = textutil.textbox( 'WARNING: \n' 'No objects found for this image...' ) for line in warnstr.split('\n'): log.warning(line) print(warnstr) return if self.radec is None: print(' Found {:d} objects.'.format(len(self.xypos[0]))) if self.wcs is not None: ra, dec = self.wcs.all_pix2world(self.xypos[0], self.xypos[1], self.origin) self.radec = [ra, dec] + copy.deepcopy(self.xypos[2:]) else: # If we have no WCS, simply pass along the XY input positions # under the assumption they were already sky positions. self.radec = copy.deepcopy(self.xypos)
[ "def", "generateRaDec", "(", "self", ")", ":", "self", ".", "prefix", "=", "self", ".", "PAR_PREFIX", "if", "not", "isinstance", "(", "self", ".", "wcs", ",", "pywcs", ".", "WCS", ")", ":", "print", "(", "textutil", ".", "textbox", "(", "'WCS not a val...
Convert XY positions into sky coordinates using STWCS methods.
[ "Convert", "XY", "positions", "into", "sky", "coordinates", "using", "STWCS", "methods", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/catalogs.py#L162-L197
train
35,708
spacetelescope/drizzlepac
drizzlepac/catalogs.py
Catalog.apply_exclusions
def apply_exclusions(self,exclusions): """ Trim sky catalog to remove any sources within regions specified by exclusions file. """ # parse exclusion file into list of positions and distances exclusion_coords = tweakutils.parse_exclusions(exclusions) if exclusion_coords is None: return excluded_list = [] radec_indx = list(range(len(self.radec[0]))) for ra,dec,indx in zip(self.radec[0],self.radec[1],radec_indx): src_pos = coords.SkyCoord(ra=ra,dec=dec,unit=(u.hourangle,u.deg)) # check to see whether this source is within an exclusion region for reg in exclusion_coords: if reg['units'] == 'sky': regpos = reg['pos'] regdist = reg['distance'] # units: arcsec else: regradec = self.wcs.all_pix2world([reg['pos']],1)[0] regpos = (regradec[0],regradec[1]) regdist = reg['distance']*self.wcs.pscale # units: arcsec epos = coords.SkyCoord(ra=regpos[0],dec=regpos[1],unit=(u.hourangle,u.deg)) if float(epos.separation(src_pos).to_string(unit=u.arcsec,decimal=True)) <= regdist: excluded_list.append(indx) break # create a list of all 'good' sources outside all exclusion regions for e in excluded_list: radec_indx.remove(e) radec_indx = np.array(radec_indx,dtype=int) num_excluded = len(excluded_list) if num_excluded > 0: radec_trimmed = [] xypos_trimmed = [] for arr in self.radec: radec_trimmed.append(arr[radec_indx]) for arr in self.xypos: xypos_trimmed.append(arr[radec_indx]) xypos_trimmed[-1] = np.arange(len(xypos_trimmed[0])) self.radec = radec_trimmed self.xypos = xypos_trimmed log.info('Excluded %d sources from catalog.'%num_excluded)
python
def apply_exclusions(self,exclusions): """ Trim sky catalog to remove any sources within regions specified by exclusions file. """ # parse exclusion file into list of positions and distances exclusion_coords = tweakutils.parse_exclusions(exclusions) if exclusion_coords is None: return excluded_list = [] radec_indx = list(range(len(self.radec[0]))) for ra,dec,indx in zip(self.radec[0],self.radec[1],radec_indx): src_pos = coords.SkyCoord(ra=ra,dec=dec,unit=(u.hourangle,u.deg)) # check to see whether this source is within an exclusion region for reg in exclusion_coords: if reg['units'] == 'sky': regpos = reg['pos'] regdist = reg['distance'] # units: arcsec else: regradec = self.wcs.all_pix2world([reg['pos']],1)[0] regpos = (regradec[0],regradec[1]) regdist = reg['distance']*self.wcs.pscale # units: arcsec epos = coords.SkyCoord(ra=regpos[0],dec=regpos[1],unit=(u.hourangle,u.deg)) if float(epos.separation(src_pos).to_string(unit=u.arcsec,decimal=True)) <= regdist: excluded_list.append(indx) break # create a list of all 'good' sources outside all exclusion regions for e in excluded_list: radec_indx.remove(e) radec_indx = np.array(radec_indx,dtype=int) num_excluded = len(excluded_list) if num_excluded > 0: radec_trimmed = [] xypos_trimmed = [] for arr in self.radec: radec_trimmed.append(arr[radec_indx]) for arr in self.xypos: xypos_trimmed.append(arr[radec_indx]) xypos_trimmed[-1] = np.arange(len(xypos_trimmed[0])) self.radec = radec_trimmed self.xypos = xypos_trimmed log.info('Excluded %d sources from catalog.'%num_excluded)
[ "def", "apply_exclusions", "(", "self", ",", "exclusions", ")", ":", "# parse exclusion file into list of positions and distances", "exclusion_coords", "=", "tweakutils", ".", "parse_exclusions", "(", "exclusions", ")", "if", "exclusion_coords", "is", "None", ":", "return...
Trim sky catalog to remove any sources within regions specified by exclusions file.
[ "Trim", "sky", "catalog", "to", "remove", "any", "sources", "within", "regions", "specified", "by", "exclusions", "file", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/catalogs.py#L199-L241
train
35,709
spacetelescope/drizzlepac
drizzlepac/catalogs.py
Catalog.buildCatalogs
def buildCatalogs(self, exclusions=None, **kwargs): """ Primary interface to build catalogs based on user inputs. """ self.generateXY(**kwargs) self.generateRaDec() if exclusions: self.apply_exclusions(exclusions) # apply selection limits as specified by the user: self.apply_flux_limits()
python
def buildCatalogs(self, exclusions=None, **kwargs): """ Primary interface to build catalogs based on user inputs. """ self.generateXY(**kwargs) self.generateRaDec() if exclusions: self.apply_exclusions(exclusions) # apply selection limits as specified by the user: self.apply_flux_limits()
[ "def", "buildCatalogs", "(", "self", ",", "exclusions", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "generateXY", "(", "*", "*", "kwargs", ")", "self", ".", "generateRaDec", "(", ")", "if", "exclusions", ":", "self", ".", "apply_exclus...
Primary interface to build catalogs based on user inputs.
[ "Primary", "interface", "to", "build", "catalogs", "based", "on", "user", "inputs", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/catalogs.py#L339-L348
train
35,710
spacetelescope/drizzlepac
drizzlepac/catalogs.py
Catalog.plotXYCatalog
def plotXYCatalog(self, **kwargs): """ Method which displays the original image and overlays the positions of the detected sources from this image's catalog. Plotting `kwargs` that can be provided are: vmin, vmax, cmap, marker Default colormap is `summer`. """ try: from matplotlib import pyplot as pl except: pl = None if pl is not None: # If the pyplot package could be loaded... pl.clf() pars = kwargs.copy() if 'marker' not in pars: pars['marker'] = 'b+' if 'cmap' in pars: pl_cmap = pars['cmap'] del pars['cmap'] else: pl_cmap = 'summer' pl_vmin = None pl_vmax = None if 'vmin' in pars: pl_vmin = pars['vmin'] del pars['vmin'] if 'vmax' in pars: pl_vmax = pars['vmax'] del pars['vmax'] pl.imshow(self.source,cmap=pl_cmap,vmin=pl_vmin,vmax=pl_vmax) pl.plot(self.xypos[0]-1,self.xypos[1]-1,pars['marker'])
python
def plotXYCatalog(self, **kwargs): """ Method which displays the original image and overlays the positions of the detected sources from this image's catalog. Plotting `kwargs` that can be provided are: vmin, vmax, cmap, marker Default colormap is `summer`. """ try: from matplotlib import pyplot as pl except: pl = None if pl is not None: # If the pyplot package could be loaded... pl.clf() pars = kwargs.copy() if 'marker' not in pars: pars['marker'] = 'b+' if 'cmap' in pars: pl_cmap = pars['cmap'] del pars['cmap'] else: pl_cmap = 'summer' pl_vmin = None pl_vmax = None if 'vmin' in pars: pl_vmin = pars['vmin'] del pars['vmin'] if 'vmax' in pars: pl_vmax = pars['vmax'] del pars['vmax'] pl.imshow(self.source,cmap=pl_cmap,vmin=pl_vmin,vmax=pl_vmax) pl.plot(self.xypos[0]-1,self.xypos[1]-1,pars['marker'])
[ "def", "plotXYCatalog", "(", "self", ",", "*", "*", "kwargs", ")", ":", "try", ":", "from", "matplotlib", "import", "pyplot", "as", "pl", "except", ":", "pl", "=", "None", "if", "pl", "is", "not", "None", ":", "# If the pyplot package could be loaded...", ...
Method which displays the original image and overlays the positions of the detected sources from this image's catalog. Plotting `kwargs` that can be provided are: vmin, vmax, cmap, marker Default colormap is `summer`.
[ "Method", "which", "displays", "the", "original", "image", "and", "overlays", "the", "positions", "of", "the", "detected", "sources", "from", "this", "image", "s", "catalog", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/catalogs.py#L350-L389
train
35,711
spacetelescope/drizzlepac
drizzlepac/catalogs.py
Catalog.writeXYCatalog
def writeXYCatalog(self,filename): """ Write out the X,Y catalog to a file """ if self.xypos is None: warnstr = textutil.textbox( 'WARNING: \n No X,Y source catalog to write to file. ') for line in warnstr.split('\n'): log.warning(line) print(warnstr) return f = open(filename,'w') f.write("# Source catalog derived for %s\n"%self.wcs.filename) f.write("# Columns: \n") if self.use_sharp_round: f.write('# X Y Flux ID Sharp Round1 Round2\n') else: f.write('# X Y Flux ID\n') f.write('# (%s) (%s)\n'%(self.in_units,self.in_units)) for row in range(len(self.xypos[0])): for i in range(len(self.xypos)): f.write("%g "%(self.xypos[i][row])) f.write("\n") f.close()
python
def writeXYCatalog(self,filename): """ Write out the X,Y catalog to a file """ if self.xypos is None: warnstr = textutil.textbox( 'WARNING: \n No X,Y source catalog to write to file. ') for line in warnstr.split('\n'): log.warning(line) print(warnstr) return f = open(filename,'w') f.write("# Source catalog derived for %s\n"%self.wcs.filename) f.write("# Columns: \n") if self.use_sharp_round: f.write('# X Y Flux ID Sharp Round1 Round2\n') else: f.write('# X Y Flux ID\n') f.write('# (%s) (%s)\n'%(self.in_units,self.in_units)) for row in range(len(self.xypos[0])): for i in range(len(self.xypos)): f.write("%g "%(self.xypos[i][row])) f.write("\n") f.close()
[ "def", "writeXYCatalog", "(", "self", ",", "filename", ")", ":", "if", "self", ".", "xypos", "is", "None", ":", "warnstr", "=", "textutil", ".", "textbox", "(", "'WARNING: \\n No X,Y source catalog to write to file. '", ")", "for", "line", "in", "warnstr", "....
Write out the X,Y catalog to a file
[ "Write", "out", "the", "X", "Y", "catalog", "to", "a", "file" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/catalogs.py#L391-L416
train
35,712
spacetelescope/drizzlepac
drizzlepac/catalogs.py
UserCatalog.generateXY
def generateXY(self, **kwargs): """ Method to interpret input catalog file as columns of positions and fluxes. """ self.num_objects = 0 xycols = self._readCatalog() if xycols is not None: # convert the catalog into attribute self.xypos = xycols[:3] # convert optional columns if they are present if self.numcols > 3: self.xypos.append(np.asarray(xycols[3], dtype=int)) # source ID if self.numcols > 4: self.sharp = xycols[4] if self.numcols > 5: self.round1 = xycols[5] if self.numcols > 6: self.round2 = xycols[6] self.num_objects = len(xycols[0]) if self.numcols < 3: # account for flux column self.xypos.append(np.zeros(self.num_objects, dtype=float)) self.flux_col = False if self.numcols < 4: # add source ID column self.xypos.append(np.arange(self.num_objects)+self.start_id) if self.use_sharp_round: for i in range(len(self.xypos), 7): self.xypos.append(np.zeros(self.num_objects, dtype=float)) self.sharp_col = False if self.pars['xyunits'] == 'degrees': self.radec = [x.copy() for x in self.xypos] if self.wcs is not None: self.xypos[:2] = list(self.wcs.all_world2pix(np.array(self.xypos[:2]).T, self.origin).T)
python
def generateXY(self, **kwargs): """ Method to interpret input catalog file as columns of positions and fluxes. """ self.num_objects = 0 xycols = self._readCatalog() if xycols is not None: # convert the catalog into attribute self.xypos = xycols[:3] # convert optional columns if they are present if self.numcols > 3: self.xypos.append(np.asarray(xycols[3], dtype=int)) # source ID if self.numcols > 4: self.sharp = xycols[4] if self.numcols > 5: self.round1 = xycols[5] if self.numcols > 6: self.round2 = xycols[6] self.num_objects = len(xycols[0]) if self.numcols < 3: # account for flux column self.xypos.append(np.zeros(self.num_objects, dtype=float)) self.flux_col = False if self.numcols < 4: # add source ID column self.xypos.append(np.arange(self.num_objects)+self.start_id) if self.use_sharp_round: for i in range(len(self.xypos), 7): self.xypos.append(np.zeros(self.num_objects, dtype=float)) self.sharp_col = False if self.pars['xyunits'] == 'degrees': self.radec = [x.copy() for x in self.xypos] if self.wcs is not None: self.xypos[:2] = list(self.wcs.all_world2pix(np.array(self.xypos[:2]).T, self.origin).T)
[ "def", "generateXY", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "num_objects", "=", "0", "xycols", "=", "self", ".", "_readCatalog", "(", ")", "if", "xycols", "is", "not", "None", ":", "# convert the catalog into attribute", "self", ".", ...
Method to interpret input catalog file as columns of positions and fluxes.
[ "Method", "to", "interpret", "input", "catalog", "file", "as", "columns", "of", "positions", "and", "fluxes", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/catalogs.py#L694-L730
train
35,713
spacetelescope/drizzlepac
drizzlepac/ablot.py
do_blot
def do_blot(source, source_wcs, blot_wcs, exptime, coeffs = True, interp='poly5', sinscl=1.0, stepsize=10, wcsmap=None): """ Core functionality of performing the 'blot' operation to create a single blotted image from a single source image. All distortion information is assumed to be included in the WCS specification of the 'output' blotted image given in 'blot_wcs'. This is the simplest interface that can be called for stand-alone use of the blotting function. Parameters ---------- source Input numpy array of undistorted source image in units of 'cps'. source_wcs HSTWCS object representing source image distortion-corrected WCS. blot_wcs (py)wcs.WCS object representing the blotted image WCS. exptime exptime to use for scaling output blot image. A value of 1 will result in output blot image in units of 'cps'. coeffs Flag to specify whether or not to use distortion coefficients associated with blot_wcs. If False, do not apply any distortion model. interp Form of interpolation to use when blotting pixels. Valid options:: "nearest","linear","poly3", "poly5"(default), "spline3", "sinc" sinscl Scale for sinc interpolation kernel (in output, blotted pixels) stepsize Number of pixels for WCS interpolation wcsmap Custom mapping class to use to provide transformation from drizzled to blotted WCS. Default will be to use `drizzlepac.wcs_functions.WCSMap`. """ _outsci = np.zeros(blot_wcs.array_shape, dtype=np.float32) # Now pass numpy objects to callable version of Blot... build=False misval = 0.0 kscale = 1.0 xmin = 1 ymin = 1 xmax, ymax = source_wcs.pixel_shape # compute the undistorted 'natural' plate scale for this chip if coeffs: wcslin = distortion.utils.make_orthogonal_cd(blot_wcs) else: wcslin = blot_wcs blot_wcs.sip = None blot_wcs.cpdis1 = None blot_wcs.cpdis2 = None blot_wcs.det2im = None if wcsmap is None and cdriz is not None: """ Use default C mapping function. """ print('Using default C-based coordinate transformation...') mapping = cdriz.DefaultWCSMapping( blot_wcs, source_wcs, blot_wcs.pixel_shape[0], blot_wcs.pixel_shape[1], stepsize ) pix_ratio = source_wcs.pscale/wcslin.pscale else: # ##Using the Python class for the WCS-based transformation # # Use user provided mapping function print('Using coordinate transformation defined by user...') if wcsmap is None: wcsmap = wcs_functions.WCSMap wmap = wcsmap(blot_wcs,source_wcs) mapping = wmap.forward pix_ratio = source_wcs.pscale/wcslin.pscale t = cdriz.tblot( source, _outsci,xmin,xmax,ymin,ymax, pix_ratio, kscale, 1.0, 1.0, 'center',interp, exptime, misval, sinscl, 1, mapping) del mapping return _outsci
python
def do_blot(source, source_wcs, blot_wcs, exptime, coeffs = True, interp='poly5', sinscl=1.0, stepsize=10, wcsmap=None): """ Core functionality of performing the 'blot' operation to create a single blotted image from a single source image. All distortion information is assumed to be included in the WCS specification of the 'output' blotted image given in 'blot_wcs'. This is the simplest interface that can be called for stand-alone use of the blotting function. Parameters ---------- source Input numpy array of undistorted source image in units of 'cps'. source_wcs HSTWCS object representing source image distortion-corrected WCS. blot_wcs (py)wcs.WCS object representing the blotted image WCS. exptime exptime to use for scaling output blot image. A value of 1 will result in output blot image in units of 'cps'. coeffs Flag to specify whether or not to use distortion coefficients associated with blot_wcs. If False, do not apply any distortion model. interp Form of interpolation to use when blotting pixels. Valid options:: "nearest","linear","poly3", "poly5"(default), "spline3", "sinc" sinscl Scale for sinc interpolation kernel (in output, blotted pixels) stepsize Number of pixels for WCS interpolation wcsmap Custom mapping class to use to provide transformation from drizzled to blotted WCS. Default will be to use `drizzlepac.wcs_functions.WCSMap`. """ _outsci = np.zeros(blot_wcs.array_shape, dtype=np.float32) # Now pass numpy objects to callable version of Blot... build=False misval = 0.0 kscale = 1.0 xmin = 1 ymin = 1 xmax, ymax = source_wcs.pixel_shape # compute the undistorted 'natural' plate scale for this chip if coeffs: wcslin = distortion.utils.make_orthogonal_cd(blot_wcs) else: wcslin = blot_wcs blot_wcs.sip = None blot_wcs.cpdis1 = None blot_wcs.cpdis2 = None blot_wcs.det2im = None if wcsmap is None and cdriz is not None: """ Use default C mapping function. """ print('Using default C-based coordinate transformation...') mapping = cdriz.DefaultWCSMapping( blot_wcs, source_wcs, blot_wcs.pixel_shape[0], blot_wcs.pixel_shape[1], stepsize ) pix_ratio = source_wcs.pscale/wcslin.pscale else: # ##Using the Python class for the WCS-based transformation # # Use user provided mapping function print('Using coordinate transformation defined by user...') if wcsmap is None: wcsmap = wcs_functions.WCSMap wmap = wcsmap(blot_wcs,source_wcs) mapping = wmap.forward pix_ratio = source_wcs.pscale/wcslin.pscale t = cdriz.tblot( source, _outsci,xmin,xmax,ymin,ymax, pix_ratio, kscale, 1.0, 1.0, 'center',interp, exptime, misval, sinscl, 1, mapping) del mapping return _outsci
[ "def", "do_blot", "(", "source", ",", "source_wcs", ",", "blot_wcs", ",", "exptime", ",", "coeffs", "=", "True", ",", "interp", "=", "'poly5'", ",", "sinscl", "=", "1.0", ",", "stepsize", "=", "10", ",", "wcsmap", "=", "None", ")", ":", "_outsci", "=...
Core functionality of performing the 'blot' operation to create a single blotted image from a single source image. All distortion information is assumed to be included in the WCS specification of the 'output' blotted image given in 'blot_wcs'. This is the simplest interface that can be called for stand-alone use of the blotting function. Parameters ---------- source Input numpy array of undistorted source image in units of 'cps'. source_wcs HSTWCS object representing source image distortion-corrected WCS. blot_wcs (py)wcs.WCS object representing the blotted image WCS. exptime exptime to use for scaling output blot image. A value of 1 will result in output blot image in units of 'cps'. coeffs Flag to specify whether or not to use distortion coefficients associated with blot_wcs. If False, do not apply any distortion model. interp Form of interpolation to use when blotting pixels. Valid options:: "nearest","linear","poly3", "poly5"(default), "spline3", "sinc" sinscl Scale for sinc interpolation kernel (in output, blotted pixels) stepsize Number of pixels for WCS interpolation wcsmap Custom mapping class to use to provide transformation from drizzled to blotted WCS. Default will be to use `drizzlepac.wcs_functions.WCSMap`.
[ "Core", "functionality", "of", "performing", "the", "blot", "operation", "to", "create", "a", "single", "blotted", "image", "from", "a", "single", "source", "image", ".", "All", "distortion", "information", "is", "assumed", "to", "be", "included", "in", "the",...
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/ablot.py#L329-L419
train
35,714
spacetelescope/drizzlepac
drizzlepac/runastrodriz.py
_lowerAsn
def _lowerAsn(asnfile): """ Create a copy of the original asn file and change the case of all members to lower-case. """ # Start by creating a new name for the ASN table _indx = asnfile.find('_asn.fits') _new_asn = asnfile[:_indx]+'_pipeline'+asnfile[_indx:] if os.path.exists(_new_asn): os.remove(_new_asn) # copy original ASN table to new table shutil.copy(asnfile,_new_asn) # Open up the new copy and convert all MEMNAME's to lower-case fasn = fits.open(_new_asn, mode='update', memmap=False) for i in range(len(fasn[1].data)): fasn[1].data[i].setfield('MEMNAME',fasn[1].data[i].field('MEMNAME').lower()) fasn.close() return _new_asn
python
def _lowerAsn(asnfile): """ Create a copy of the original asn file and change the case of all members to lower-case. """ # Start by creating a new name for the ASN table _indx = asnfile.find('_asn.fits') _new_asn = asnfile[:_indx]+'_pipeline'+asnfile[_indx:] if os.path.exists(_new_asn): os.remove(_new_asn) # copy original ASN table to new table shutil.copy(asnfile,_new_asn) # Open up the new copy and convert all MEMNAME's to lower-case fasn = fits.open(_new_asn, mode='update', memmap=False) for i in range(len(fasn[1].data)): fasn[1].data[i].setfield('MEMNAME',fasn[1].data[i].field('MEMNAME').lower()) fasn.close() return _new_asn
[ "def", "_lowerAsn", "(", "asnfile", ")", ":", "# Start by creating a new name for the ASN table", "_indx", "=", "asnfile", ".", "find", "(", "'_asn.fits'", ")", "_new_asn", "=", "asnfile", "[", ":", "_indx", "]", "+", "'_pipeline'", "+", "asnfile", "[", "_indx",...
Create a copy of the original asn file and change the case of all members to lower-case.
[ "Create", "a", "copy", "of", "the", "original", "asn", "file", "and", "change", "the", "case", "of", "all", "members", "to", "lower", "-", "case", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/runastrodriz.py#L520-L538
train
35,715
spacetelescope/drizzlepac
drizzlepac/runastrodriz.py
_appendTrlFile
def _appendTrlFile(trlfile,drizfile): """ Append drizfile to already existing trlfile from CALXXX. """ if not os.path.exists(drizfile): return # Open already existing CALWF3 trailer file for appending ftrl = open(trlfile,'a') # Open astrodrizzle trailer file fdriz = open(drizfile) # Read in drizzle comments _dlines = fdriz.readlines() # Append them to CALWF3 trailer file ftrl.writelines(_dlines) # Close all files ftrl.close() fdriz.close() # Now, clean up astrodrizzle trailer file os.remove(drizfile)
python
def _appendTrlFile(trlfile,drizfile): """ Append drizfile to already existing trlfile from CALXXX. """ if not os.path.exists(drizfile): return # Open already existing CALWF3 trailer file for appending ftrl = open(trlfile,'a') # Open astrodrizzle trailer file fdriz = open(drizfile) # Read in drizzle comments _dlines = fdriz.readlines() # Append them to CALWF3 trailer file ftrl.writelines(_dlines) # Close all files ftrl.close() fdriz.close() # Now, clean up astrodrizzle trailer file os.remove(drizfile)
[ "def", "_appendTrlFile", "(", "trlfile", ",", "drizfile", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "drizfile", ")", ":", "return", "# Open already existing CALWF3 trailer file for appending", "ftrl", "=", "open", "(", "trlfile", ",", "'a'", ...
Append drizfile to already existing trlfile from CALXXX.
[ "Append", "drizfile", "to", "already", "existing", "trlfile", "from", "CALXXX", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/runastrodriz.py#L540-L561
train
35,716
spacetelescope/drizzlepac
drizzlepac/runastrodriz.py
_timestamp
def _timestamp(_process_name): """Create formatted time string recognizable by OPUS.""" _prefix= time.strftime("%Y%j%H%M%S-I-----",time.localtime()) _lenstr = 60 - len(_process_name) return _prefix+_process_name+(_lenstr*'-')+'\n'
python
def _timestamp(_process_name): """Create formatted time string recognizable by OPUS.""" _prefix= time.strftime("%Y%j%H%M%S-I-----",time.localtime()) _lenstr = 60 - len(_process_name) return _prefix+_process_name+(_lenstr*'-')+'\n'
[ "def", "_timestamp", "(", "_process_name", ")", ":", "_prefix", "=", "time", ".", "strftime", "(", "\"%Y%j%H%M%S-I-----\"", ",", "time", ".", "localtime", "(", ")", ")", "_lenstr", "=", "60", "-", "len", "(", "_process_name", ")", "return", "_prefix", "+",...
Create formatted time string recognizable by OPUS.
[ "Create", "formatted", "time", "string", "recognizable", "by", "OPUS", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/runastrodriz.py#L564-L568
train
35,717
spacetelescope/drizzlepac
drizzlepac/runastrodriz.py
_createWorkingDir
def _createWorkingDir(rootdir,input): """ Create a working directory based on input name under the parent directory specified as rootdir """ # extract rootname from input rootname = input[:input.find('_')] newdir = os.path.join(rootdir,rootname) if not os.path.exists(newdir): os.mkdir(newdir) return newdir
python
def _createWorkingDir(rootdir,input): """ Create a working directory based on input name under the parent directory specified as rootdir """ # extract rootname from input rootname = input[:input.find('_')] newdir = os.path.join(rootdir,rootname) if not os.path.exists(newdir): os.mkdir(newdir) return newdir
[ "def", "_createWorkingDir", "(", "rootdir", ",", "input", ")", ":", "# extract rootname from input", "rootname", "=", "input", "[", ":", "input", ".", "find", "(", "'_'", ")", "]", "newdir", "=", "os", ".", "path", ".", "join", "(", "rootdir", ",", "root...
Create a working directory based on input name under the parent directory specified as rootdir
[ "Create", "a", "working", "directory", "based", "on", "input", "name", "under", "the", "parent", "directory", "specified", "as", "rootdir" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/runastrodriz.py#L578-L587
train
35,718
spacetelescope/drizzlepac
drizzlepac/runastrodriz.py
_copyToNewWorkingDir
def _copyToNewWorkingDir(newdir,input): """ Copy input file and all related files necessary for processing to the new working directory. This function works in a greedy manner, in that all files associated with all inputs(have the same rootname) will be copied to the new working directory. """ flist = [] if '_asn.fits' in input: asndict = asnutil.readASNTable(input,None) flist.append(input[:input.find('_')]) flist.extend(asndict['order']) flist.append(asndict['output']) else: flist.append(input[:input.find('_')]) # copy all files related to these rootnames into new dir for rootname in flist: for fname in glob.glob(rootname+'*'): shutil.copy(fname,os.path.join(newdir,fname))
python
def _copyToNewWorkingDir(newdir,input): """ Copy input file and all related files necessary for processing to the new working directory. This function works in a greedy manner, in that all files associated with all inputs(have the same rootname) will be copied to the new working directory. """ flist = [] if '_asn.fits' in input: asndict = asnutil.readASNTable(input,None) flist.append(input[:input.find('_')]) flist.extend(asndict['order']) flist.append(asndict['output']) else: flist.append(input[:input.find('_')]) # copy all files related to these rootnames into new dir for rootname in flist: for fname in glob.glob(rootname+'*'): shutil.copy(fname,os.path.join(newdir,fname))
[ "def", "_copyToNewWorkingDir", "(", "newdir", ",", "input", ")", ":", "flist", "=", "[", "]", "if", "'_asn.fits'", "in", "input", ":", "asndict", "=", "asnutil", ".", "readASNTable", "(", "input", ",", "None", ")", "flist", ".", "append", "(", "input", ...
Copy input file and all related files necessary for processing to the new working directory. This function works in a greedy manner, in that all files associated with all inputs(have the same rootname) will be copied to the new working directory.
[ "Copy", "input", "file", "and", "all", "related", "files", "necessary", "for", "processing", "to", "the", "new", "working", "directory", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/runastrodriz.py#L589-L607
train
35,719
spacetelescope/drizzlepac
drizzlepac/createMedian.py
median
def median(input=None, configObj=None, editpars=False, **inputDict): """ Create a median image from the seperately drizzled images. """ if input is not None: inputDict["input"] = input else: raise ValueError("Please supply an input image") configObj = util.getDefaultConfigObj(__taskname__, configObj, inputDict, loadOnly=(not editpars)) if configObj is None: return if not editpars: run(configObj)
python
def median(input=None, configObj=None, editpars=False, **inputDict): """ Create a median image from the seperately drizzled images. """ if input is not None: inputDict["input"] = input else: raise ValueError("Please supply an input image") configObj = util.getDefaultConfigObj(__taskname__, configObj, inputDict, loadOnly=(not editpars)) if configObj is None: return if not editpars: run(configObj)
[ "def", "median", "(", "input", "=", "None", ",", "configObj", "=", "None", ",", "editpars", "=", "False", ",", "*", "*", "inputDict", ")", ":", "if", "input", "is", "not", "None", ":", "inputDict", "[", "\"input\"", "]", "=", "input", "else", ":", ...
Create a median image from the seperately drizzled images.
[ "Create", "a", "median", "image", "from", "the", "seperately", "drizzled", "images", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/createMedian.py#L37-L52
train
35,720
spacetelescope/drizzlepac
drizzlepac/createMedian.py
createMedian
def createMedian(imgObjList, configObj, procSteps=None): """ Top-level interface to createMedian step called from top-level AstroDrizzle. This function parses the input parameters then calls the `_median()` function to median-combine the input images into a single image. """ if imgObjList is None: msg = "Please provide a list of imageObjects to the median step" print(msg, file=sys.stderr) raise ValueError(msg) if procSteps is not None: procSteps.addStep('Create Median') step_name = util.getSectionName(configObj, _step_num_) if not configObj[step_name]['median']: log.info('Median combination step not performed.') return paramDict = configObj[step_name] paramDict['proc_unit'] = configObj['proc_unit'] # include whether or not compression was performed driz_sep_name = util.getSectionName(configObj, _single_step_num_) driz_sep_paramDict = configObj[driz_sep_name] paramDict['compress'] = driz_sep_paramDict['driz_sep_compress'] log.info('USER INPUT PARAMETERS for Create Median Step:') util.printParams(paramDict, log=log) _median(imgObjList, paramDict) if procSteps is not None: procSteps.endStep('Create Median')
python
def createMedian(imgObjList, configObj, procSteps=None): """ Top-level interface to createMedian step called from top-level AstroDrizzle. This function parses the input parameters then calls the `_median()` function to median-combine the input images into a single image. """ if imgObjList is None: msg = "Please provide a list of imageObjects to the median step" print(msg, file=sys.stderr) raise ValueError(msg) if procSteps is not None: procSteps.addStep('Create Median') step_name = util.getSectionName(configObj, _step_num_) if not configObj[step_name]['median']: log.info('Median combination step not performed.') return paramDict = configObj[step_name] paramDict['proc_unit'] = configObj['proc_unit'] # include whether or not compression was performed driz_sep_name = util.getSectionName(configObj, _single_step_num_) driz_sep_paramDict = configObj[driz_sep_name] paramDict['compress'] = driz_sep_paramDict['driz_sep_compress'] log.info('USER INPUT PARAMETERS for Create Median Step:') util.printParams(paramDict, log=log) _median(imgObjList, paramDict) if procSteps is not None: procSteps.endStep('Create Median')
[ "def", "createMedian", "(", "imgObjList", ",", "configObj", ",", "procSteps", "=", "None", ")", ":", "if", "imgObjList", "is", "None", ":", "msg", "=", "\"Please provide a list of imageObjects to the median step\"", "print", "(", "msg", ",", "file", "=", "sys", ...
Top-level interface to createMedian step called from top-level AstroDrizzle. This function parses the input parameters then calls the `_median()` function to median-combine the input images into a single image.
[ "Top", "-", "level", "interface", "to", "createMedian", "step", "called", "from", "top", "-", "level", "AstroDrizzle", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/createMedian.py#L67-L102
train
35,721
spacetelescope/drizzlepac
drizzlepac/createMedian.py
_writeImage
def _writeImage(dataArray=None, inputHeader=None): """ Writes out the result of the combination step. The header of the first 'outsingle' file in the association parlist is used as the header of the new image. Parameters ---------- dataArray : arr Array of data to be written to a fits.PrimaryHDU object inputHeader : obj fits.header.Header object to use as basis for the PrimaryHDU header """ prihdu = fits.PrimaryHDU(data=dataArray, header=inputHeader) pf = fits.HDUList() pf.append(prihdu) return pf
python
def _writeImage(dataArray=None, inputHeader=None): """ Writes out the result of the combination step. The header of the first 'outsingle' file in the association parlist is used as the header of the new image. Parameters ---------- dataArray : arr Array of data to be written to a fits.PrimaryHDU object inputHeader : obj fits.header.Header object to use as basis for the PrimaryHDU header """ prihdu = fits.PrimaryHDU(data=dataArray, header=inputHeader) pf = fits.HDUList() pf.append(prihdu) return pf
[ "def", "_writeImage", "(", "dataArray", "=", "None", ",", "inputHeader", "=", "None", ")", ":", "prihdu", "=", "fits", ".", "PrimaryHDU", "(", "data", "=", "dataArray", ",", "header", "=", "inputHeader", ")", "pf", "=", "fits", ".", "HDUList", "(", ")"...
Writes out the result of the combination step. The header of the first 'outsingle' file in the association parlist is used as the header of the new image. Parameters ---------- dataArray : arr Array of data to be written to a fits.PrimaryHDU object inputHeader : obj fits.header.Header object to use as basis for the PrimaryHDU header
[ "Writes", "out", "the", "result", "of", "the", "combination", "step", ".", "The", "header", "of", "the", "first", "outsingle", "file", "in", "the", "association", "parlist", "is", "used", "as", "the", "header", "of", "the", "new", "image", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/createMedian.py#L454-L472
train
35,722
ethpm/py-ethpm
ethpm/backends/registry.py
RegistryURIBackend.fetch_uri_contents
def fetch_uri_contents(self, uri: str) -> URI: """ Return content-addressed URI stored at registry URI. """ address, pkg_name, pkg_version = parse_registry_uri(uri) self.w3.enable_unstable_package_management_api() self.w3.pm.set_registry(address) _, _, manifest_uri = self.w3.pm.get_release_data(pkg_name, pkg_version) return manifest_uri
python
def fetch_uri_contents(self, uri: str) -> URI: """ Return content-addressed URI stored at registry URI. """ address, pkg_name, pkg_version = parse_registry_uri(uri) self.w3.enable_unstable_package_management_api() self.w3.pm.set_registry(address) _, _, manifest_uri = self.w3.pm.get_release_data(pkg_name, pkg_version) return manifest_uri
[ "def", "fetch_uri_contents", "(", "self", ",", "uri", ":", "str", ")", "->", "URI", ":", "address", ",", "pkg_name", ",", "pkg_version", "=", "parse_registry_uri", "(", "uri", ")", "self", ".", "w3", ".", "enable_unstable_package_management_api", "(", ")", "...
Return content-addressed URI stored at registry URI.
[ "Return", "content", "-", "addressed", "URI", "stored", "at", "registry", "URI", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/backends/registry.py#L35-L43
train
35,723
ethpm/py-ethpm
ethpm/backends/ipfs.py
DummyIPFSBackend.pin_assets
def pin_assets(self, file_or_dir_path: Path) -> List[Dict[str, str]]: """ Return a dict containing the IPFS hash, file name, and size of a file. """ if file_or_dir_path.is_dir(): asset_data = [dummy_ipfs_pin(path) for path in file_or_dir_path.glob("*")] elif file_or_dir_path.is_file(): asset_data = [dummy_ipfs_pin(file_or_dir_path)] else: raise FileNotFoundError( f"{file_or_dir_path} is not a valid file or directory path." ) return asset_data
python
def pin_assets(self, file_or_dir_path: Path) -> List[Dict[str, str]]: """ Return a dict containing the IPFS hash, file name, and size of a file. """ if file_or_dir_path.is_dir(): asset_data = [dummy_ipfs_pin(path) for path in file_or_dir_path.glob("*")] elif file_or_dir_path.is_file(): asset_data = [dummy_ipfs_pin(file_or_dir_path)] else: raise FileNotFoundError( f"{file_or_dir_path} is not a valid file or directory path." ) return asset_data
[ "def", "pin_assets", "(", "self", ",", "file_or_dir_path", ":", "Path", ")", "->", "List", "[", "Dict", "[", "str", ",", "str", "]", "]", ":", "if", "file_or_dir_path", ".", "is_dir", "(", ")", ":", "asset_data", "=", "[", "dummy_ipfs_pin", "(", "path"...
Return a dict containing the IPFS hash, file name, and size of a file.
[ "Return", "a", "dict", "containing", "the", "IPFS", "hash", "file", "name", "and", "size", "of", "a", "file", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/backends/ipfs.py#L158-L170
train
35,724
BrewBlox/brewblox-service
brewblox_service/scheduler.py
TaskScheduler._cleanup
async def _cleanup(self): """ Periodically removes completed tasks from the collection, allowing fire-and-forget tasks to be garbage collected. This does not delete the task object, it merely removes the reference in the scheduler. """ while True: await asyncio.sleep(CLEANUP_INTERVAL_S) self._tasks = {t for t in self._tasks if not t.done()}
python
async def _cleanup(self): """ Periodically removes completed tasks from the collection, allowing fire-and-forget tasks to be garbage collected. This does not delete the task object, it merely removes the reference in the scheduler. """ while True: await asyncio.sleep(CLEANUP_INTERVAL_S) self._tasks = {t for t in self._tasks if not t.done()}
[ "async", "def", "_cleanup", "(", "self", ")", ":", "while", "True", ":", "await", "asyncio", ".", "sleep", "(", "CLEANUP_INTERVAL_S", ")", "self", ".", "_tasks", "=", "{", "t", "for", "t", "in", "self", ".", "_tasks", "if", "not", "t", ".", "done", ...
Periodically removes completed tasks from the collection, allowing fire-and-forget tasks to be garbage collected. This does not delete the task object, it merely removes the reference in the scheduler.
[ "Periodically", "removes", "completed", "tasks", "from", "the", "collection", "allowing", "fire", "-", "and", "-", "forget", "tasks", "to", "be", "garbage", "collected", "." ]
f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/scheduler.py#L121-L130
train
35,725
BrewBlox/brewblox-service
brewblox_service/scheduler.py
TaskScheduler.create
async def create(self, coro: Coroutine) -> asyncio.Task: """ Starts execution of a coroutine. The created asyncio.Task is returned, and added to managed tasks. The scheduler guarantees that it is cancelled during application shutdown, regardless of whether it was already cancelled manually. Args: coro (Coroutine): The coroutine to be wrapped in a task, and executed. Returns: asyncio.Task: An awaitable Task object. During Aiohttp shutdown, the scheduler will attempt to cancel and await this task. The task can be safely cancelled manually, or using `TaskScheduler.cancel(task)`. """ task = asyncio.get_event_loop().create_task(coro) self._tasks.add(task) return task
python
async def create(self, coro: Coroutine) -> asyncio.Task: """ Starts execution of a coroutine. The created asyncio.Task is returned, and added to managed tasks. The scheduler guarantees that it is cancelled during application shutdown, regardless of whether it was already cancelled manually. Args: coro (Coroutine): The coroutine to be wrapped in a task, and executed. Returns: asyncio.Task: An awaitable Task object. During Aiohttp shutdown, the scheduler will attempt to cancel and await this task. The task can be safely cancelled manually, or using `TaskScheduler.cancel(task)`. """ task = asyncio.get_event_loop().create_task(coro) self._tasks.add(task) return task
[ "async", "def", "create", "(", "self", ",", "coro", ":", "Coroutine", ")", "->", "asyncio", ".", "Task", ":", "task", "=", "asyncio", ".", "get_event_loop", "(", ")", ".", "create_task", "(", "coro", ")", "self", ".", "_tasks", ".", "add", "(", "task...
Starts execution of a coroutine. The created asyncio.Task is returned, and added to managed tasks. The scheduler guarantees that it is cancelled during application shutdown, regardless of whether it was already cancelled manually. Args: coro (Coroutine): The coroutine to be wrapped in a task, and executed. Returns: asyncio.Task: An awaitable Task object. During Aiohttp shutdown, the scheduler will attempt to cancel and await this task. The task can be safely cancelled manually, or using `TaskScheduler.cancel(task)`.
[ "Starts", "execution", "of", "a", "coroutine", "." ]
f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/scheduler.py#L132-L151
train
35,726
BrewBlox/brewblox-service
brewblox_service/scheduler.py
TaskScheduler.cancel
async def cancel(self, task: asyncio.Task, wait_for: bool = True) -> Any: """ Cancels and waits for an `asyncio.Task` to finish. Removes it from the collection of managed tasks. Args: task (asyncio.Task): The to be cancelled task. It is not required that the task was was created with `TaskScheduler.create_task()`. wait_for (bool, optional): Whether to wait for the task to finish execution. If falsey, this function returns immediately after cancelling the task. Returns: Any: The return value of `task`. None if `wait_for` is falsey. """ if task is None: return task.cancel() with suppress(KeyError): self._tasks.remove(task) with suppress(Exception): return (await task) if wait_for else None
python
async def cancel(self, task: asyncio.Task, wait_for: bool = True) -> Any: """ Cancels and waits for an `asyncio.Task` to finish. Removes it from the collection of managed tasks. Args: task (asyncio.Task): The to be cancelled task. It is not required that the task was was created with `TaskScheduler.create_task()`. wait_for (bool, optional): Whether to wait for the task to finish execution. If falsey, this function returns immediately after cancelling the task. Returns: Any: The return value of `task`. None if `wait_for` is falsey. """ if task is None: return task.cancel() with suppress(KeyError): self._tasks.remove(task) with suppress(Exception): return (await task) if wait_for else None
[ "async", "def", "cancel", "(", "self", ",", "task", ":", "asyncio", ".", "Task", ",", "wait_for", ":", "bool", "=", "True", ")", "->", "Any", ":", "if", "task", "is", "None", ":", "return", "task", ".", "cancel", "(", ")", "with", "suppress", "(", ...
Cancels and waits for an `asyncio.Task` to finish. Removes it from the collection of managed tasks. Args: task (asyncio.Task): The to be cancelled task. It is not required that the task was was created with `TaskScheduler.create_task()`. wait_for (bool, optional): Whether to wait for the task to finish execution. If falsey, this function returns immediately after cancelling the task. Returns: Any: The return value of `task`. None if `wait_for` is falsey.
[ "Cancels", "and", "waits", "for", "an", "asyncio", ".", "Task", "to", "finish", ".", "Removes", "it", "from", "the", "collection", "of", "managed", "tasks", "." ]
f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/scheduler.py#L153-L180
train
35,727
ethpm/py-ethpm
ethpm/utils/uri.py
is_supported_content_addressed_uri
def is_supported_content_addressed_uri(uri: URI) -> bool: """ Returns a bool indicating whether provided uri is currently supported. Currently Py-EthPM only supports IPFS and Github blob content-addressed uris. """ if not is_ipfs_uri(uri) and not is_valid_content_addressed_github_uri(uri): return False return True
python
def is_supported_content_addressed_uri(uri: URI) -> bool: """ Returns a bool indicating whether provided uri is currently supported. Currently Py-EthPM only supports IPFS and Github blob content-addressed uris. """ if not is_ipfs_uri(uri) and not is_valid_content_addressed_github_uri(uri): return False return True
[ "def", "is_supported_content_addressed_uri", "(", "uri", ":", "URI", ")", "->", "bool", ":", "if", "not", "is_ipfs_uri", "(", "uri", ")", "and", "not", "is_valid_content_addressed_github_uri", "(", "uri", ")", ":", "return", "False", "return", "True" ]
Returns a bool indicating whether provided uri is currently supported. Currently Py-EthPM only supports IPFS and Github blob content-addressed uris.
[ "Returns", "a", "bool", "indicating", "whether", "provided", "uri", "is", "currently", "supported", ".", "Currently", "Py", "-", "EthPM", "only", "supports", "IPFS", "and", "Github", "blob", "content", "-", "addressed", "uris", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/utils/uri.py#L112-L119
train
35,728
ethpm/py-ethpm
ethpm/package.py
Package.update_w3
def update_w3(self, w3: Web3) -> "Package": """ Returns a new instance of `Package` containing the same manifest, but connected to a different web3 instance. .. doctest:: >>> new_w3 = Web3(Web3.EthereumTesterProvider()) >>> NewPackage = OwnedPackage.update_w3(new_w3) >>> assert NewPackage.w3 == new_w3 >>> assert OwnedPackage.manifest == NewPackage.manifest """ validate_w3_instance(w3) return Package(self.manifest, w3, self.uri)
python
def update_w3(self, w3: Web3) -> "Package": """ Returns a new instance of `Package` containing the same manifest, but connected to a different web3 instance. .. doctest:: >>> new_w3 = Web3(Web3.EthereumTesterProvider()) >>> NewPackage = OwnedPackage.update_w3(new_w3) >>> assert NewPackage.w3 == new_w3 >>> assert OwnedPackage.manifest == NewPackage.manifest """ validate_w3_instance(w3) return Package(self.manifest, w3, self.uri)
[ "def", "update_w3", "(", "self", ",", "w3", ":", "Web3", ")", "->", "\"Package\"", ":", "validate_w3_instance", "(", "w3", ")", "return", "Package", "(", "self", ".", "manifest", ",", "w3", ",", "self", ".", "uri", ")" ]
Returns a new instance of `Package` containing the same manifest, but connected to a different web3 instance. .. doctest:: >>> new_w3 = Web3(Web3.EthereumTesterProvider()) >>> NewPackage = OwnedPackage.update_w3(new_w3) >>> assert NewPackage.w3 == new_w3 >>> assert OwnedPackage.manifest == NewPackage.manifest
[ "Returns", "a", "new", "instance", "of", "Package", "containing", "the", "same", "manifest", "but", "connected", "to", "a", "different", "web3", "instance", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/package.py#L70-L83
train
35,729
ethpm/py-ethpm
ethpm/package.py
Package.from_file
def from_file(cls, file_path: Path, w3: Web3) -> "Package": """ Returns a ``Package`` instantiated by a manifest located at the provided Path. ``file_path`` arg must be a ``pathlib.Path`` instance. A valid ``Web3`` instance is required to instantiate a ``Package``. """ if isinstance(file_path, Path): raw_manifest = file_path.read_text() validate_raw_manifest_format(raw_manifest) manifest = json.loads(raw_manifest) else: raise TypeError( "The Package.from_file method expects a pathlib.Path instance." f"Got {type(file_path)} instead." ) return cls(manifest, w3, file_path.as_uri())
python
def from_file(cls, file_path: Path, w3: Web3) -> "Package": """ Returns a ``Package`` instantiated by a manifest located at the provided Path. ``file_path`` arg must be a ``pathlib.Path`` instance. A valid ``Web3`` instance is required to instantiate a ``Package``. """ if isinstance(file_path, Path): raw_manifest = file_path.read_text() validate_raw_manifest_format(raw_manifest) manifest = json.loads(raw_manifest) else: raise TypeError( "The Package.from_file method expects a pathlib.Path instance." f"Got {type(file_path)} instead." ) return cls(manifest, w3, file_path.as_uri())
[ "def", "from_file", "(", "cls", ",", "file_path", ":", "Path", ",", "w3", ":", "Web3", ")", "->", "\"Package\"", ":", "if", "isinstance", "(", "file_path", ",", "Path", ")", ":", "raw_manifest", "=", "file_path", ".", "read_text", "(", ")", "validate_raw...
Returns a ``Package`` instantiated by a manifest located at the provided Path. ``file_path`` arg must be a ``pathlib.Path`` instance. A valid ``Web3`` instance is required to instantiate a ``Package``.
[ "Returns", "a", "Package", "instantiated", "by", "a", "manifest", "located", "at", "the", "provided", "Path", ".", "file_path", "arg", "must", "be", "a", "pathlib", ".", "Path", "instance", ".", "A", "valid", "Web3", "instance", "is", "required", "to", "in...
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/package.py#L142-L157
train
35,730
ethpm/py-ethpm
ethpm/package.py
Package.get_contract_factory
def get_contract_factory(self, name: ContractName) -> Contract: """ Return the contract factory for a given contract type, generated from the data vailable in ``Package.manifest``. Contract factories are accessible from the package class. .. code:: python Owned = OwnedPackage.get_contract_factory('owned') In cases where a contract uses a library, the contract factory will have unlinked bytecode. The ``ethpm`` package ships with its own subclass of ``web3.contract.Contract``, ``ethpm.contract.LinkableContract`` with a few extra methods and properties related to bytecode linking. .. code:: python >>> math = owned_package.contract_factories.math >>> math.needs_bytecode_linking True >>> linked_math = math.link_bytecode({'MathLib': '0x1234...'}) >>> linked_math.needs_bytecode_linking False """ validate_contract_name(name) if "contract_types" not in self.manifest: raise InsufficientAssetsError( "This package does not contain any contract type data." ) try: contract_data = self.manifest["contract_types"][name] except KeyError: raise InsufficientAssetsError( "This package does not contain any package data to generate " f"a contract factory for contract type: {name}. Available contract types include: " f"{ list(self.manifest['contract_types'].keys()) }." ) validate_minimal_contract_factory_data(contract_data) contract_kwargs = generate_contract_factory_kwargs(contract_data) contract_factory = self.w3.eth.contract(**contract_kwargs) return contract_factory
python
def get_contract_factory(self, name: ContractName) -> Contract: """ Return the contract factory for a given contract type, generated from the data vailable in ``Package.manifest``. Contract factories are accessible from the package class. .. code:: python Owned = OwnedPackage.get_contract_factory('owned') In cases where a contract uses a library, the contract factory will have unlinked bytecode. The ``ethpm`` package ships with its own subclass of ``web3.contract.Contract``, ``ethpm.contract.LinkableContract`` with a few extra methods and properties related to bytecode linking. .. code:: python >>> math = owned_package.contract_factories.math >>> math.needs_bytecode_linking True >>> linked_math = math.link_bytecode({'MathLib': '0x1234...'}) >>> linked_math.needs_bytecode_linking False """ validate_contract_name(name) if "contract_types" not in self.manifest: raise InsufficientAssetsError( "This package does not contain any contract type data." ) try: contract_data = self.manifest["contract_types"][name] except KeyError: raise InsufficientAssetsError( "This package does not contain any package data to generate " f"a contract factory for contract type: {name}. Available contract types include: " f"{ list(self.manifest['contract_types'].keys()) }." ) validate_minimal_contract_factory_data(contract_data) contract_kwargs = generate_contract_factory_kwargs(contract_data) contract_factory = self.w3.eth.contract(**contract_kwargs) return contract_factory
[ "def", "get_contract_factory", "(", "self", ",", "name", ":", "ContractName", ")", "->", "Contract", ":", "validate_contract_name", "(", "name", ")", "if", "\"contract_types\"", "not", "in", "self", ".", "manifest", ":", "raise", "InsufficientAssetsError", "(", ...
Return the contract factory for a given contract type, generated from the data vailable in ``Package.manifest``. Contract factories are accessible from the package class. .. code:: python Owned = OwnedPackage.get_contract_factory('owned') In cases where a contract uses a library, the contract factory will have unlinked bytecode. The ``ethpm`` package ships with its own subclass of ``web3.contract.Contract``, ``ethpm.contract.LinkableContract`` with a few extra methods and properties related to bytecode linking. .. code:: python >>> math = owned_package.contract_factories.math >>> math.needs_bytecode_linking True >>> linked_math = math.link_bytecode({'MathLib': '0x1234...'}) >>> linked_math.needs_bytecode_linking False
[ "Return", "the", "contract", "factory", "for", "a", "given", "contract", "type", "generated", "from", "the", "data", "vailable", "in", "Package", ".", "manifest", ".", "Contract", "factories", "are", "accessible", "from", "the", "package", "class", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/package.py#L182-L224
train
35,731
ethpm/py-ethpm
ethpm/package.py
Package.get_contract_instance
def get_contract_instance(self, name: ContractName, address: Address) -> Contract: """ Will return a ``Web3.contract`` instance generated from the contract type data available in ``Package.manifest`` and the provided ``address``. The provided ``address`` must be valid on the connected chain available through ``Package.w3``. """ validate_address(address) validate_contract_name(name) try: self.manifest["contract_types"][name]["abi"] except KeyError: raise InsufficientAssetsError( "Package does not have the ABI required to generate a contract instance " f"for contract: {name} at address: {address}." ) contract_kwargs = generate_contract_factory_kwargs( self.manifest["contract_types"][name] ) canonical_address = to_canonical_address(address) contract_instance = self.w3.eth.contract( address=canonical_address, **contract_kwargs ) return contract_instance
python
def get_contract_instance(self, name: ContractName, address: Address) -> Contract: """ Will return a ``Web3.contract`` instance generated from the contract type data available in ``Package.manifest`` and the provided ``address``. The provided ``address`` must be valid on the connected chain available through ``Package.w3``. """ validate_address(address) validate_contract_name(name) try: self.manifest["contract_types"][name]["abi"] except KeyError: raise InsufficientAssetsError( "Package does not have the ABI required to generate a contract instance " f"for contract: {name} at address: {address}." ) contract_kwargs = generate_contract_factory_kwargs( self.manifest["contract_types"][name] ) canonical_address = to_canonical_address(address) contract_instance = self.w3.eth.contract( address=canonical_address, **contract_kwargs ) return contract_instance
[ "def", "get_contract_instance", "(", "self", ",", "name", ":", "ContractName", ",", "address", ":", "Address", ")", "->", "Contract", ":", "validate_address", "(", "address", ")", "validate_contract_name", "(", "name", ")", "try", ":", "self", ".", "manifest",...
Will return a ``Web3.contract`` instance generated from the contract type data available in ``Package.manifest`` and the provided ``address``. The provided ``address`` must be valid on the connected chain available through ``Package.w3``.
[ "Will", "return", "a", "Web3", ".", "contract", "instance", "generated", "from", "the", "contract", "type", "data", "available", "in", "Package", ".", "manifest", "and", "the", "provided", "address", ".", "The", "provided", "address", "must", "be", "valid", ...
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/package.py#L226-L248
train
35,732
ethpm/py-ethpm
ethpm/package.py
Package.build_dependencies
def build_dependencies(self) -> "Dependencies": """ Return `Dependencies` instance containing the build dependencies available on this Package. The ``Package`` class should provide access to the full dependency tree. .. code:: python >>> owned_package.build_dependencies['zeppelin'] <ZeppelinPackage> """ validate_build_dependencies_are_present(self.manifest) dependencies = self.manifest["build_dependencies"] dependency_packages = {} for name, uri in dependencies.items(): try: validate_build_dependency(name, uri) dependency_package = Package.from_uri(uri, self.w3) except PyEthPMError as e: raise FailureToFetchIPFSAssetsError( f"Failed to retrieve build dependency: {name} from URI: {uri}.\n" f"Got error: {e}." ) else: dependency_packages[name] = dependency_package return Dependencies(dependency_packages)
python
def build_dependencies(self) -> "Dependencies": """ Return `Dependencies` instance containing the build dependencies available on this Package. The ``Package`` class should provide access to the full dependency tree. .. code:: python >>> owned_package.build_dependencies['zeppelin'] <ZeppelinPackage> """ validate_build_dependencies_are_present(self.manifest) dependencies = self.manifest["build_dependencies"] dependency_packages = {} for name, uri in dependencies.items(): try: validate_build_dependency(name, uri) dependency_package = Package.from_uri(uri, self.w3) except PyEthPMError as e: raise FailureToFetchIPFSAssetsError( f"Failed to retrieve build dependency: {name} from URI: {uri}.\n" f"Got error: {e}." ) else: dependency_packages[name] = dependency_package return Dependencies(dependency_packages)
[ "def", "build_dependencies", "(", "self", ")", "->", "\"Dependencies\"", ":", "validate_build_dependencies_are_present", "(", "self", ".", "manifest", ")", "dependencies", "=", "self", ".", "manifest", "[", "\"build_dependencies\"", "]", "dependency_packages", "=", "{...
Return `Dependencies` instance containing the build dependencies available on this Package. The ``Package`` class should provide access to the full dependency tree. .. code:: python >>> owned_package.build_dependencies['zeppelin'] <ZeppelinPackage>
[ "Return", "Dependencies", "instance", "containing", "the", "build", "dependencies", "available", "on", "this", "Package", ".", "The", "Package", "class", "should", "provide", "access", "to", "the", "full", "dependency", "tree", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/package.py#L255-L281
train
35,733
ethpm/py-ethpm
ethpm/package.py
Package.deployments
def deployments(self) -> Union["Deployments", Dict[None, None]]: """ Returns a ``Deployments`` object containing all the deployment data and contract factories of a ``Package``'s `contract_types`. Automatically filters deployments to only expose those available on the current ``Package.w3`` instance. .. code:: python package.deployments.get_instance("ContractType") """ if not check_for_deployments(self.manifest): return {} all_blockchain_uris = self.manifest["deployments"].keys() matching_uri = validate_single_matching_uri(all_blockchain_uris, self.w3) deployments = self.manifest["deployments"][matching_uri] all_contract_factories = { deployment_data["contract_type"]: self.get_contract_factory( deployment_data["contract_type"] ) for deployment_data in deployments.values() } validate_deployments_tx_receipt(deployments, self.w3, allow_missing_data=True) linked_deployments = get_linked_deployments(deployments) if linked_deployments: for deployment_data in linked_deployments.values(): on_chain_bytecode = self.w3.eth.getCode( to_canonical_address(deployment_data["address"]) ) unresolved_linked_refs = normalize_linked_references( deployment_data["runtime_bytecode"]["link_dependencies"] ) resolved_linked_refs = tuple( self._resolve_linked_references(link_ref, deployments) for link_ref in unresolved_linked_refs ) for linked_ref in resolved_linked_refs: validate_linked_references(linked_ref, on_chain_bytecode) return Deployments(deployments, all_contract_factories, self.w3)
python
def deployments(self) -> Union["Deployments", Dict[None, None]]: """ Returns a ``Deployments`` object containing all the deployment data and contract factories of a ``Package``'s `contract_types`. Automatically filters deployments to only expose those available on the current ``Package.w3`` instance. .. code:: python package.deployments.get_instance("ContractType") """ if not check_for_deployments(self.manifest): return {} all_blockchain_uris = self.manifest["deployments"].keys() matching_uri = validate_single_matching_uri(all_blockchain_uris, self.w3) deployments = self.manifest["deployments"][matching_uri] all_contract_factories = { deployment_data["contract_type"]: self.get_contract_factory( deployment_data["contract_type"] ) for deployment_data in deployments.values() } validate_deployments_tx_receipt(deployments, self.w3, allow_missing_data=True) linked_deployments = get_linked_deployments(deployments) if linked_deployments: for deployment_data in linked_deployments.values(): on_chain_bytecode = self.w3.eth.getCode( to_canonical_address(deployment_data["address"]) ) unresolved_linked_refs = normalize_linked_references( deployment_data["runtime_bytecode"]["link_dependencies"] ) resolved_linked_refs = tuple( self._resolve_linked_references(link_ref, deployments) for link_ref in unresolved_linked_refs ) for linked_ref in resolved_linked_refs: validate_linked_references(linked_ref, on_chain_bytecode) return Deployments(deployments, all_contract_factories, self.w3)
[ "def", "deployments", "(", "self", ")", "->", "Union", "[", "\"Deployments\"", ",", "Dict", "[", "None", ",", "None", "]", "]", ":", "if", "not", "check_for_deployments", "(", "self", ".", "manifest", ")", ":", "return", "{", "}", "all_blockchain_uris", ...
Returns a ``Deployments`` object containing all the deployment data and contract factories of a ``Package``'s `contract_types`. Automatically filters deployments to only expose those available on the current ``Package.w3`` instance. .. code:: python package.deployments.get_instance("ContractType")
[ "Returns", "a", "Deployments", "object", "containing", "all", "the", "deployment", "data", "and", "contract", "factories", "of", "a", "Package", "s", "contract_types", ".", "Automatically", "filters", "deployments", "to", "only", "expose", "those", "available", "o...
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/package.py#L288-L328
train
35,734
ethpm/py-ethpm
ethpm/utils/ipfs.py
dummy_ipfs_pin
def dummy_ipfs_pin(path: Path) -> Dict[str, str]: """ Return IPFS data as if file was pinned to an actual node. """ ipfs_return = { "Hash": generate_file_hash(path.read_bytes()), "Name": path.name, "Size": str(path.stat().st_size), } return ipfs_return
python
def dummy_ipfs_pin(path: Path) -> Dict[str, str]: """ Return IPFS data as if file was pinned to an actual node. """ ipfs_return = { "Hash": generate_file_hash(path.read_bytes()), "Name": path.name, "Size": str(path.stat().st_size), } return ipfs_return
[ "def", "dummy_ipfs_pin", "(", "path", ":", "Path", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "ipfs_return", "=", "{", "\"Hash\"", ":", "generate_file_hash", "(", "path", ".", "read_bytes", "(", ")", ")", ",", "\"Name\"", ":", "path", ".", ...
Return IPFS data as if file was pinned to an actual node.
[ "Return", "IPFS", "data", "as", "if", "file", "was", "pinned", "to", "an", "actual", "node", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/utils/ipfs.py#L12-L21
train
35,735
ethpm/py-ethpm
ethpm/utils/ipfs.py
extract_ipfs_path_from_uri
def extract_ipfs_path_from_uri(value: str) -> str: """ Return the path from an IPFS URI. Path = IPFS hash & following path. """ parse_result = parse.urlparse(value) if parse_result.netloc: if parse_result.path: return "".join((parse_result.netloc, parse_result.path.rstrip("/"))) else: return parse_result.netloc else: return parse_result.path.strip("/")
python
def extract_ipfs_path_from_uri(value: str) -> str: """ Return the path from an IPFS URI. Path = IPFS hash & following path. """ parse_result = parse.urlparse(value) if parse_result.netloc: if parse_result.path: return "".join((parse_result.netloc, parse_result.path.rstrip("/"))) else: return parse_result.netloc else: return parse_result.path.strip("/")
[ "def", "extract_ipfs_path_from_uri", "(", "value", ":", "str", ")", "->", "str", ":", "parse_result", "=", "parse", ".", "urlparse", "(", "value", ")", "if", "parse_result", ".", "netloc", ":", "if", "parse_result", ".", "path", ":", "return", "\"\"", ".",...
Return the path from an IPFS URI. Path = IPFS hash & following path.
[ "Return", "the", "path", "from", "an", "IPFS", "URI", ".", "Path", "=", "IPFS", "hash", "&", "following", "path", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/utils/ipfs.py#L28-L41
train
35,736
ethpm/py-ethpm
ethpm/utils/ipfs.py
is_ipfs_uri
def is_ipfs_uri(value: str) -> bool: """ Return a bool indicating whether or not the value is a valid IPFS URI. """ parse_result = parse.urlparse(value) if parse_result.scheme != "ipfs": return False if not parse_result.netloc and not parse_result.path: return False return True
python
def is_ipfs_uri(value: str) -> bool: """ Return a bool indicating whether or not the value is a valid IPFS URI. """ parse_result = parse.urlparse(value) if parse_result.scheme != "ipfs": return False if not parse_result.netloc and not parse_result.path: return False return True
[ "def", "is_ipfs_uri", "(", "value", ":", "str", ")", "->", "bool", ":", "parse_result", "=", "parse", ".", "urlparse", "(", "value", ")", "if", "parse_result", ".", "scheme", "!=", "\"ipfs\"", ":", "return", "False", "if", "not", "parse_result", ".", "ne...
Return a bool indicating whether or not the value is a valid IPFS URI.
[ "Return", "a", "bool", "indicating", "whether", "or", "not", "the", "value", "is", "a", "valid", "IPFS", "URI", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/utils/ipfs.py#L44-L54
train
35,737
ethpm/py-ethpm
ethpm/deployments.py
Deployments.get_instance
def get_instance(self, contract_name: str) -> None: """ Fetches a contract instance belonging to deployment after validating contract name. """ self._validate_name_and_references(contract_name) # Use a deployment's "contract_type" to lookup contract factory # in case the deployment uses a contract alias contract_type = self.deployment_data[contract_name]["contract_type"] factory = self.contract_factories[contract_type] address = to_canonical_address(self.deployment_data[contract_name]["address"]) contract_kwargs = { "abi": factory.abi, "bytecode": factory.bytecode, "bytecode_runtime": factory.bytecode_runtime, } return self.w3.eth.contract(address=address, **contract_kwargs)
python
def get_instance(self, contract_name: str) -> None: """ Fetches a contract instance belonging to deployment after validating contract name. """ self._validate_name_and_references(contract_name) # Use a deployment's "contract_type" to lookup contract factory # in case the deployment uses a contract alias contract_type = self.deployment_data[contract_name]["contract_type"] factory = self.contract_factories[contract_type] address = to_canonical_address(self.deployment_data[contract_name]["address"]) contract_kwargs = { "abi": factory.abi, "bytecode": factory.bytecode, "bytecode_runtime": factory.bytecode_runtime, } return self.w3.eth.contract(address=address, **contract_kwargs)
[ "def", "get_instance", "(", "self", ",", "contract_name", ":", "str", ")", "->", "None", ":", "self", ".", "_validate_name_and_references", "(", "contract_name", ")", "# Use a deployment's \"contract_type\" to lookup contract factory", "# in case the deployment uses a contract ...
Fetches a contract instance belonging to deployment after validating contract name.
[ "Fetches", "a", "contract", "instance", "belonging", "to", "deployment", "after", "validating", "contract", "name", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/deployments.py#L45-L61
train
35,738
ethpm/py-ethpm
ethpm/validation.py
validate_address
def validate_address(address: Any) -> None: """ Raise a ValidationError if an address is not canonicalized. """ if not is_address(address): raise ValidationError(f"Expected an address, got: {address}") if not is_canonical_address(address): raise ValidationError( "Py-EthPM library only accepts canonicalized addresses. " f"{address} is not in the accepted format." )
python
def validate_address(address: Any) -> None: """ Raise a ValidationError if an address is not canonicalized. """ if not is_address(address): raise ValidationError(f"Expected an address, got: {address}") if not is_canonical_address(address): raise ValidationError( "Py-EthPM library only accepts canonicalized addresses. " f"{address} is not in the accepted format." )
[ "def", "validate_address", "(", "address", ":", "Any", ")", "->", "None", ":", "if", "not", "is_address", "(", "address", ")", ":", "raise", "ValidationError", "(", "f\"Expected an address, got: {address}\"", ")", "if", "not", "is_canonical_address", "(", "address...
Raise a ValidationError if an address is not canonicalized.
[ "Raise", "a", "ValidationError", "if", "an", "address", "is", "not", "canonicalized", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/validation.py#L15-L25
train
35,739
ethpm/py-ethpm
ethpm/validation.py
validate_package_name
def validate_package_name(pkg_name: str) -> None: """ Raise an exception if the value is not a valid package name as defined in the EthPM-Spec. """ if not bool(re.match(PACKAGE_NAME_REGEX, pkg_name)): raise ValidationError(f"{pkg_name} is not a valid package name.")
python
def validate_package_name(pkg_name: str) -> None: """ Raise an exception if the value is not a valid package name as defined in the EthPM-Spec. """ if not bool(re.match(PACKAGE_NAME_REGEX, pkg_name)): raise ValidationError(f"{pkg_name} is not a valid package name.")
[ "def", "validate_package_name", "(", "pkg_name", ":", "str", ")", "->", "None", ":", "if", "not", "bool", "(", "re", ".", "match", "(", "PACKAGE_NAME_REGEX", ",", "pkg_name", ")", ")", ":", "raise", "ValidationError", "(", "f\"{pkg_name} is not a valid package n...
Raise an exception if the value is not a valid package name as defined in the EthPM-Spec.
[ "Raise", "an", "exception", "if", "the", "value", "is", "not", "a", "valid", "package", "name", "as", "defined", "in", "the", "EthPM", "-", "Spec", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/validation.py#L52-L58
train
35,740
ethpm/py-ethpm
ethpm/validation.py
validate_registry_uri
def validate_registry_uri(uri: str) -> None: """ Raise an exception if the URI does not conform to the registry URI scheme. """ parsed = parse.urlparse(uri) scheme, authority, pkg_name, query = ( parsed.scheme, parsed.netloc, parsed.path, parsed.query, ) validate_registry_uri_scheme(scheme) validate_registry_uri_authority(authority) if query: validate_registry_uri_version(query) validate_package_name(pkg_name[1:])
python
def validate_registry_uri(uri: str) -> None: """ Raise an exception if the URI does not conform to the registry URI scheme. """ parsed = parse.urlparse(uri) scheme, authority, pkg_name, query = ( parsed.scheme, parsed.netloc, parsed.path, parsed.query, ) validate_registry_uri_scheme(scheme) validate_registry_uri_authority(authority) if query: validate_registry_uri_version(query) validate_package_name(pkg_name[1:])
[ "def", "validate_registry_uri", "(", "uri", ":", "str", ")", "->", "None", ":", "parsed", "=", "parse", ".", "urlparse", "(", "uri", ")", "scheme", ",", "authority", ",", "pkg_name", ",", "query", "=", "(", "parsed", ".", "scheme", ",", "parsed", ".", ...
Raise an exception if the URI does not conform to the registry URI scheme.
[ "Raise", "an", "exception", "if", "the", "URI", "does", "not", "conform", "to", "the", "registry", "URI", "scheme", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/validation.py#L101-L116
train
35,741
ethpm/py-ethpm
ethpm/validation.py
validate_registry_uri_authority
def validate_registry_uri_authority(auth: str) -> None: """ Raise an exception if the authority is not a valid ENS domain or a valid checksummed contract address. """ if is_ens_domain(auth) is False and not is_checksum_address(auth): raise ValidationError(f"{auth} is not a valid registry URI authority.")
python
def validate_registry_uri_authority(auth: str) -> None: """ Raise an exception if the authority is not a valid ENS domain or a valid checksummed contract address. """ if is_ens_domain(auth) is False and not is_checksum_address(auth): raise ValidationError(f"{auth} is not a valid registry URI authority.")
[ "def", "validate_registry_uri_authority", "(", "auth", ":", "str", ")", "->", "None", ":", "if", "is_ens_domain", "(", "auth", ")", "is", "False", "and", "not", "is_checksum_address", "(", "auth", ")", ":", "raise", "ValidationError", "(", "f\"{auth} is not a va...
Raise an exception if the authority is not a valid ENS domain or a valid checksummed contract address.
[ "Raise", "an", "exception", "if", "the", "authority", "is", "not", "a", "valid", "ENS", "domain", "or", "a", "valid", "checksummed", "contract", "address", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/validation.py#L119-L125
train
35,742
ethpm/py-ethpm
ethpm/validation.py
validate_registry_uri_version
def validate_registry_uri_version(query: str) -> None: """ Raise an exception if the version param is malformed. """ query_dict = parse.parse_qs(query, keep_blank_values=True) if "version" not in query_dict: raise ValidationError(f"{query} is not a correctly formatted version param.")
python
def validate_registry_uri_version(query: str) -> None: """ Raise an exception if the version param is malformed. """ query_dict = parse.parse_qs(query, keep_blank_values=True) if "version" not in query_dict: raise ValidationError(f"{query} is not a correctly formatted version param.")
[ "def", "validate_registry_uri_version", "(", "query", ":", "str", ")", "->", "None", ":", "query_dict", "=", "parse", ".", "parse_qs", "(", "query", ",", "keep_blank_values", "=", "True", ")", "if", "\"version\"", "not", "in", "query_dict", ":", "raise", "Va...
Raise an exception if the version param is malformed.
[ "Raise", "an", "exception", "if", "the", "version", "param", "is", "malformed", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/validation.py#L136-L142
train
35,743
ethpm/py-ethpm
ethpm/utils/manifest_validation.py
validate_meta_object
def validate_meta_object(meta: Dict[str, Any], allow_extra_meta_fields: bool) -> None: """ Validates that every key is one of `META_FIELDS` and has a value of the expected type. """ for key, value in meta.items(): if key in META_FIELDS: if type(value) is not META_FIELDS[key]: raise ValidationError( f"Values for {key} are expected to have the type {META_FIELDS[key]}, " f"instead got {type(value)}." ) elif allow_extra_meta_fields: if key[:2] != "x-": raise ValidationError( "Undefined meta fields need to begin with 'x-', " f"{key} is not a valid undefined meta field." ) else: raise ValidationError( f"{key} is not a permitted meta field. To allow undefined fields, " "set `allow_extra_meta_fields` to True." )
python
def validate_meta_object(meta: Dict[str, Any], allow_extra_meta_fields: bool) -> None: """ Validates that every key is one of `META_FIELDS` and has a value of the expected type. """ for key, value in meta.items(): if key in META_FIELDS: if type(value) is not META_FIELDS[key]: raise ValidationError( f"Values for {key} are expected to have the type {META_FIELDS[key]}, " f"instead got {type(value)}." ) elif allow_extra_meta_fields: if key[:2] != "x-": raise ValidationError( "Undefined meta fields need to begin with 'x-', " f"{key} is not a valid undefined meta field." ) else: raise ValidationError( f"{key} is not a permitted meta field. To allow undefined fields, " "set `allow_extra_meta_fields` to True." )
[ "def", "validate_meta_object", "(", "meta", ":", "Dict", "[", "str", ",", "Any", "]", ",", "allow_extra_meta_fields", ":", "bool", ")", "->", "None", ":", "for", "key", ",", "value", "in", "meta", ".", "items", "(", ")", ":", "if", "key", "in", "META...
Validates that every key is one of `META_FIELDS` and has a value of the expected type.
[ "Validates", "that", "every", "key", "is", "one", "of", "META_FIELDS", "and", "has", "a", "value", "of", "the", "expected", "type", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/utils/manifest_validation.py#L21-L42
train
35,744
ethpm/py-ethpm
ethpm/utils/manifest_validation.py
validate_manifest_against_schema
def validate_manifest_against_schema(manifest: Dict[str, Any]) -> None: """ Load and validate manifest against schema located at MANIFEST_SCHEMA_PATH. """ schema_data = _load_schema_data() try: validate(manifest, schema_data) except jsonValidationError as e: raise ValidationError( f"Manifest invalid for schema version {schema_data['version']}. " f"Reason: {e.message}" )
python
def validate_manifest_against_schema(manifest: Dict[str, Any]) -> None: """ Load and validate manifest against schema located at MANIFEST_SCHEMA_PATH. """ schema_data = _load_schema_data() try: validate(manifest, schema_data) except jsonValidationError as e: raise ValidationError( f"Manifest invalid for schema version {schema_data['version']}. " f"Reason: {e.message}" )
[ "def", "validate_manifest_against_schema", "(", "manifest", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "None", ":", "schema_data", "=", "_load_schema_data", "(", ")", "try", ":", "validate", "(", "manifest", ",", "schema_data", ")", "except", "json...
Load and validate manifest against schema located at MANIFEST_SCHEMA_PATH.
[ "Load", "and", "validate", "manifest", "against", "schema", "located", "at", "MANIFEST_SCHEMA_PATH", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/utils/manifest_validation.py#L59-L71
train
35,745
ethpm/py-ethpm
ethpm/utils/manifest_validation.py
validate_manifest_deployments
def validate_manifest_deployments(manifest: Dict[str, Any]) -> None: """ Validate that a manifest's deployments contracts reference existing contract_types. """ if set(("contract_types", "deployments")).issubset(manifest): all_contract_types = list(manifest["contract_types"].keys()) all_deployments = list(manifest["deployments"].values()) all_deployment_names = extract_contract_types_from_deployments(all_deployments) missing_contract_types = set(all_deployment_names).difference( all_contract_types ) if missing_contract_types: raise ValidationError( f"Manifest missing references to contracts: {missing_contract_types}." )
python
def validate_manifest_deployments(manifest: Dict[str, Any]) -> None: """ Validate that a manifest's deployments contracts reference existing contract_types. """ if set(("contract_types", "deployments")).issubset(manifest): all_contract_types = list(manifest["contract_types"].keys()) all_deployments = list(manifest["deployments"].values()) all_deployment_names = extract_contract_types_from_deployments(all_deployments) missing_contract_types = set(all_deployment_names).difference( all_contract_types ) if missing_contract_types: raise ValidationError( f"Manifest missing references to contracts: {missing_contract_types}." )
[ "def", "validate_manifest_deployments", "(", "manifest", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "None", ":", "if", "set", "(", "(", "\"contract_types\"", ",", "\"deployments\"", ")", ")", ".", "issubset", "(", "manifest", ")", ":", "all_contr...
Validate that a manifest's deployments contracts reference existing contract_types.
[ "Validate", "that", "a", "manifest", "s", "deployments", "contracts", "reference", "existing", "contract_types", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/utils/manifest_validation.py#L88-L102
train
35,746
ethpm/py-ethpm
ethpm/tools/builder.py
build
def build(obj: Dict[str, Any], *fns: Callable[..., Any]) -> Dict[str, Any]: """ Wrapper function to pipe manifest through build functions. Does not validate the manifest by default. """ return pipe(obj, *fns)
python
def build(obj: Dict[str, Any], *fns: Callable[..., Any]) -> Dict[str, Any]: """ Wrapper function to pipe manifest through build functions. Does not validate the manifest by default. """ return pipe(obj, *fns)
[ "def", "build", "(", "obj", ":", "Dict", "[", "str", ",", "Any", "]", ",", "*", "fns", ":", "Callable", "[", "...", ",", "Any", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "return", "pipe", "(", "obj", ",", "*", "fns", ")" ]
Wrapper function to pipe manifest through build functions. Does not validate the manifest by default.
[ "Wrapper", "function", "to", "pipe", "manifest", "through", "build", "functions", ".", "Does", "not", "validate", "the", "manifest", "by", "default", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/tools/builder.py#L32-L37
train
35,747
ethpm/py-ethpm
ethpm/tools/builder.py
get_names_and_paths
def get_names_and_paths(compiler_output: Dict[str, Any]) -> Dict[str, str]: """ Return a mapping of contract name to relative path as defined in compiler output. """ return { contract_name: make_path_relative(path) for path in compiler_output for contract_name in compiler_output[path].keys() }
python
def get_names_and_paths(compiler_output: Dict[str, Any]) -> Dict[str, str]: """ Return a mapping of contract name to relative path as defined in compiler output. """ return { contract_name: make_path_relative(path) for path in compiler_output for contract_name in compiler_output[path].keys() }
[ "def", "get_names_and_paths", "(", "compiler_output", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "return", "{", "contract_name", ":", "make_path_relative", "(", "path", ")", "for", "path", "in", "compil...
Return a mapping of contract name to relative path as defined in compiler output.
[ "Return", "a", "mapping", "of", "contract", "name", "to", "relative", "path", "as", "defined", "in", "compiler", "output", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/tools/builder.py#L134-L142
train
35,748
ethpm/py-ethpm
ethpm/tools/builder.py
contract_type
def contract_type( name: str, compiler_output: Dict[str, Any], alias: Optional[str] = None, abi: Optional[bool] = False, compiler: Optional[bool] = False, contract_type: Optional[bool] = False, deployment_bytecode: Optional[bool] = False, natspec: Optional[bool] = False, runtime_bytecode: Optional[bool] = False, ) -> Manifest: """ Returns a copy of manifest with added contract_data field as specified by kwargs. If no kwargs are present, all available contract_data found in the compiler output will be included. To include specific contract_data fields, add kwarg set to True (i.e. `abi=True`) To alias a contract_type, include a kwarg `alias` (i.e. `alias="OwnedAlias"`) If only an alias kwarg is provided, all available contract data will be included. Kwargs must match fields as defined in the EthPM Spec (except "alias") if user wants to include them in custom contract_type. """ contract_type_fields = { "contract_type": contract_type, "deployment_bytecode": deployment_bytecode, "runtime_bytecode": runtime_bytecode, "abi": abi, "natspec": natspec, "compiler": compiler, } selected_fields = [k for k, v in contract_type_fields.items() if v] return _contract_type(name, compiler_output, alias, selected_fields)
python
def contract_type( name: str, compiler_output: Dict[str, Any], alias: Optional[str] = None, abi: Optional[bool] = False, compiler: Optional[bool] = False, contract_type: Optional[bool] = False, deployment_bytecode: Optional[bool] = False, natspec: Optional[bool] = False, runtime_bytecode: Optional[bool] = False, ) -> Manifest: """ Returns a copy of manifest with added contract_data field as specified by kwargs. If no kwargs are present, all available contract_data found in the compiler output will be included. To include specific contract_data fields, add kwarg set to True (i.e. `abi=True`) To alias a contract_type, include a kwarg `alias` (i.e. `alias="OwnedAlias"`) If only an alias kwarg is provided, all available contract data will be included. Kwargs must match fields as defined in the EthPM Spec (except "alias") if user wants to include them in custom contract_type. """ contract_type_fields = { "contract_type": contract_type, "deployment_bytecode": deployment_bytecode, "runtime_bytecode": runtime_bytecode, "abi": abi, "natspec": natspec, "compiler": compiler, } selected_fields = [k for k, v in contract_type_fields.items() if v] return _contract_type(name, compiler_output, alias, selected_fields)
[ "def", "contract_type", "(", "name", ":", "str", ",", "compiler_output", ":", "Dict", "[", "str", ",", "Any", "]", ",", "alias", ":", "Optional", "[", "str", "]", "=", "None", ",", "abi", ":", "Optional", "[", "bool", "]", "=", "False", ",", "compi...
Returns a copy of manifest with added contract_data field as specified by kwargs. If no kwargs are present, all available contract_data found in the compiler output will be included. To include specific contract_data fields, add kwarg set to True (i.e. `abi=True`) To alias a contract_type, include a kwarg `alias` (i.e. `alias="OwnedAlias"`) If only an alias kwarg is provided, all available contract data will be included. Kwargs must match fields as defined in the EthPM Spec (except "alias") if user wants to include them in custom contract_type.
[ "Returns", "a", "copy", "of", "manifest", "with", "added", "contract_data", "field", "as", "specified", "by", "kwargs", ".", "If", "no", "kwargs", "are", "present", "all", "available", "contract_data", "found", "in", "the", "compiler", "output", "will", "be", ...
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/tools/builder.py#L298-L329
train
35,749
ethpm/py-ethpm
ethpm/tools/builder.py
filter_all_data_by_selected_fields
def filter_all_data_by_selected_fields( all_type_data: Dict[str, Any], selected_fields: List[str] ) -> Iterable[Tuple[str, Any]]: """ Raises exception if selected field data is not available in the contract type data automatically gathered by normalize_compiler_output. Otherwise, returns the data. """ for field in selected_fields: if field in all_type_data: yield field, all_type_data[field] else: raise ManifestBuildingError( f"Selected field: {field} not available in data collected from solc output: " f"{list(sorted(all_type_data.keys()))}. Please make sure the relevant data " "is present in your solc output." )
python
def filter_all_data_by_selected_fields( all_type_data: Dict[str, Any], selected_fields: List[str] ) -> Iterable[Tuple[str, Any]]: """ Raises exception if selected field data is not available in the contract type data automatically gathered by normalize_compiler_output. Otherwise, returns the data. """ for field in selected_fields: if field in all_type_data: yield field, all_type_data[field] else: raise ManifestBuildingError( f"Selected field: {field} not available in data collected from solc output: " f"{list(sorted(all_type_data.keys()))}. Please make sure the relevant data " "is present in your solc output." )
[ "def", "filter_all_data_by_selected_fields", "(", "all_type_data", ":", "Dict", "[", "str", ",", "Any", "]", ",", "selected_fields", ":", "List", "[", "str", "]", ")", "->", "Iterable", "[", "Tuple", "[", "str", ",", "Any", "]", "]", ":", "for", "field",...
Raises exception if selected field data is not available in the contract type data automatically gathered by normalize_compiler_output. Otherwise, returns the data.
[ "Raises", "exception", "if", "selected", "field", "data", "is", "not", "available", "in", "the", "contract", "type", "data", "automatically", "gathered", "by", "normalize_compiler_output", ".", "Otherwise", "returns", "the", "data", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/tools/builder.py#L364-L379
train
35,750
ethpm/py-ethpm
ethpm/tools/builder.py
normalize_compiler_output
def normalize_compiler_output(compiler_output: Dict[str, Any]) -> Dict[str, Any]: """ Return compiler output with normalized fields for each contract type, as specified in `normalize_contract_type`. """ paths_and_names = [ (path, contract_name) for path in compiler_output for contract_name in compiler_output[path].keys() ] paths, names = zip(*paths_and_names) if len(names) != len(set(names)): raise ManifestBuildingError( "Duplicate contract names were found in the compiler output." ) return { name: normalize_contract_type(compiler_output[path][name]) for path, name in paths_and_names }
python
def normalize_compiler_output(compiler_output: Dict[str, Any]) -> Dict[str, Any]: """ Return compiler output with normalized fields for each contract type, as specified in `normalize_contract_type`. """ paths_and_names = [ (path, contract_name) for path in compiler_output for contract_name in compiler_output[path].keys() ] paths, names = zip(*paths_and_names) if len(names) != len(set(names)): raise ManifestBuildingError( "Duplicate contract names were found in the compiler output." ) return { name: normalize_contract_type(compiler_output[path][name]) for path, name in paths_and_names }
[ "def", "normalize_compiler_output", "(", "compiler_output", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "paths_and_names", "=", "[", "(", "path", ",", "contract_name", ")", "for", "path", "in", "compiler...
Return compiler output with normalized fields for each contract type, as specified in `normalize_contract_type`.
[ "Return", "compiler", "output", "with", "normalized", "fields", "for", "each", "contract", "type", "as", "specified", "in", "normalize_contract_type", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/tools/builder.py#L382-L400
train
35,751
ethpm/py-ethpm
ethpm/tools/builder.py
normalize_contract_type
def normalize_contract_type( contract_type_data: Dict[str, Any] ) -> Iterable[Tuple[str, Any]]: """ Serialize contract_data found in compiler output to the defined fields. """ yield "abi", contract_type_data["abi"] if "evm" in contract_type_data: if "bytecode" in contract_type_data["evm"]: yield "deployment_bytecode", normalize_bytecode_object( contract_type_data["evm"]["bytecode"] ) if "deployedBytecode" in contract_type_data["evm"]: yield "runtime_bytecode", normalize_bytecode_object( contract_type_data["evm"]["deployedBytecode"] ) if any(key in contract_type_data for key in NATSPEC_FIELDS): natspec = deep_merge_dicts( contract_type_data.get("userdoc", {}), contract_type_data.get("devdoc", {}) ) yield "natspec", natspec # make sure metadata isn't an empty string in solc output if "metadata" in contract_type_data and contract_type_data["metadata"]: yield "compiler", normalize_compiler_object( json.loads(contract_type_data["metadata"]) )
python
def normalize_contract_type( contract_type_data: Dict[str, Any] ) -> Iterable[Tuple[str, Any]]: """ Serialize contract_data found in compiler output to the defined fields. """ yield "abi", contract_type_data["abi"] if "evm" in contract_type_data: if "bytecode" in contract_type_data["evm"]: yield "deployment_bytecode", normalize_bytecode_object( contract_type_data["evm"]["bytecode"] ) if "deployedBytecode" in contract_type_data["evm"]: yield "runtime_bytecode", normalize_bytecode_object( contract_type_data["evm"]["deployedBytecode"] ) if any(key in contract_type_data for key in NATSPEC_FIELDS): natspec = deep_merge_dicts( contract_type_data.get("userdoc", {}), contract_type_data.get("devdoc", {}) ) yield "natspec", natspec # make sure metadata isn't an empty string in solc output if "metadata" in contract_type_data and contract_type_data["metadata"]: yield "compiler", normalize_compiler_object( json.loads(contract_type_data["metadata"]) )
[ "def", "normalize_contract_type", "(", "contract_type_data", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Iterable", "[", "Tuple", "[", "str", ",", "Any", "]", "]", ":", "yield", "\"abi\"", ",", "contract_type_data", "[", "\"abi\"", "]", "if", "...
Serialize contract_data found in compiler output to the defined fields.
[ "Serialize", "contract_data", "found", "in", "compiler", "output", "to", "the", "defined", "fields", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/tools/builder.py#L407-L432
train
35,752
ethpm/py-ethpm
ethpm/tools/builder.py
process_bytecode
def process_bytecode(link_refs: Dict[str, Any], bytecode: bytes) -> str: """ Replace link_refs in bytecode with 0's. """ all_offsets = [y for x in link_refs.values() for y in x.values()] # Link ref validation. validate_link_ref_fns = ( validate_link_ref(ref["start"] * 2, ref["length"] * 2) for ref in concat(all_offsets) ) pipe(bytecode, *validate_link_ref_fns) # Convert link_refs in bytecode to 0's link_fns = ( replace_link_ref_in_bytecode(ref["start"] * 2, ref["length"] * 2) for ref in concat(all_offsets) ) processed_bytecode = pipe(bytecode, *link_fns) return add_0x_prefix(processed_bytecode)
python
def process_bytecode(link_refs: Dict[str, Any], bytecode: bytes) -> str: """ Replace link_refs in bytecode with 0's. """ all_offsets = [y for x in link_refs.values() for y in x.values()] # Link ref validation. validate_link_ref_fns = ( validate_link_ref(ref["start"] * 2, ref["length"] * 2) for ref in concat(all_offsets) ) pipe(bytecode, *validate_link_ref_fns) # Convert link_refs in bytecode to 0's link_fns = ( replace_link_ref_in_bytecode(ref["start"] * 2, ref["length"] * 2) for ref in concat(all_offsets) ) processed_bytecode = pipe(bytecode, *link_fns) return add_0x_prefix(processed_bytecode)
[ "def", "process_bytecode", "(", "link_refs", ":", "Dict", "[", "str", ",", "Any", "]", ",", "bytecode", ":", "bytes", ")", "->", "str", ":", "all_offsets", "=", "[", "y", "for", "x", "in", "link_refs", ".", "values", "(", ")", "for", "y", "in", "x"...
Replace link_refs in bytecode with 0's.
[ "Replace", "link_refs", "in", "bytecode", "with", "0", "s", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/tools/builder.py#L462-L479
train
35,753
ethpm/py-ethpm
ethpm/tools/builder.py
deployment_type
def deployment_type( *, contract_instance: str, contract_type: str, deployment_bytecode: Dict[str, Any] = None, runtime_bytecode: Dict[str, Any] = None, compiler: Dict[str, Any] = None, ) -> Manifest: """ Returns a callable that allows the user to add deployments of the same type across multiple chains. """ return _deployment_type( contract_instance, contract_type, deployment_bytecode, runtime_bytecode, compiler, )
python
def deployment_type( *, contract_instance: str, contract_type: str, deployment_bytecode: Dict[str, Any] = None, runtime_bytecode: Dict[str, Any] = None, compiler: Dict[str, Any] = None, ) -> Manifest: """ Returns a callable that allows the user to add deployments of the same type across multiple chains. """ return _deployment_type( contract_instance, contract_type, deployment_bytecode, runtime_bytecode, compiler, )
[ "def", "deployment_type", "(", "*", ",", "contract_instance", ":", "str", ",", "contract_type", ":", "str", ",", "deployment_bytecode", ":", "Dict", "[", "str", ",", "Any", "]", "=", "None", ",", "runtime_bytecode", ":", "Dict", "[", "str", ",", "Any", "...
Returns a callable that allows the user to add deployments of the same type across multiple chains.
[ "Returns", "a", "callable", "that", "allows", "the", "user", "to", "add", "deployments", "of", "the", "same", "type", "across", "multiple", "chains", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/tools/builder.py#L532-L550
train
35,754
ethpm/py-ethpm
ethpm/tools/builder.py
deployment
def deployment( *, block_uri: URI, contract_instance: str, contract_type: str, address: HexStr, transaction: HexStr = None, block: HexStr = None, deployment_bytecode: Dict[str, Any] = None, runtime_bytecode: Dict[str, Any] = None, compiler: Dict[str, Any] = None, ) -> Manifest: """ Returns a manifest, with the newly included deployment. Requires a valid blockchain URI, however no validation is provided that this URI is unique amongst the other deployment URIs, so the user must take care that each blockchain URI represents a unique blockchain. """ return _deployment( contract_instance, contract_type, deployment_bytecode, runtime_bytecode, compiler, block_uri, address, transaction, block, )
python
def deployment( *, block_uri: URI, contract_instance: str, contract_type: str, address: HexStr, transaction: HexStr = None, block: HexStr = None, deployment_bytecode: Dict[str, Any] = None, runtime_bytecode: Dict[str, Any] = None, compiler: Dict[str, Any] = None, ) -> Manifest: """ Returns a manifest, with the newly included deployment. Requires a valid blockchain URI, however no validation is provided that this URI is unique amongst the other deployment URIs, so the user must take care that each blockchain URI represents a unique blockchain. """ return _deployment( contract_instance, contract_type, deployment_bytecode, runtime_bytecode, compiler, block_uri, address, transaction, block, )
[ "def", "deployment", "(", "*", ",", "block_uri", ":", "URI", ",", "contract_instance", ":", "str", ",", "contract_type", ":", "str", ",", "address", ":", "HexStr", ",", "transaction", ":", "HexStr", "=", "None", ",", "block", ":", "HexStr", "=", "None", ...
Returns a manifest, with the newly included deployment. Requires a valid blockchain URI, however no validation is provided that this URI is unique amongst the other deployment URIs, so the user must take care that each blockchain URI represents a unique blockchain.
[ "Returns", "a", "manifest", "with", "the", "newly", "included", "deployment", ".", "Requires", "a", "valid", "blockchain", "URI", "however", "no", "validation", "is", "provided", "that", "this", "URI", "is", "unique", "amongst", "the", "other", "deployment", "...
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/tools/builder.py#L553-L580
train
35,755
ethpm/py-ethpm
ethpm/tools/builder.py
_build_deployments_object
def _build_deployments_object( contract_type: str, deployment_bytecode: Dict[str, Any], runtime_bytecode: Dict[str, Any], compiler: Dict[str, Any], address: HexStr, tx: HexStr, block: HexStr, manifest: Dict[str, Any], ) -> Iterable[Tuple[str, Any]]: """ Returns a dict with properly formatted deployment data. """ yield "contract_type", contract_type yield "address", to_hex(address) if deployment_bytecode: yield "deployment_bytecode", deployment_bytecode if compiler: yield "compiler", compiler if tx: yield "transaction", tx if block: yield "block", block if runtime_bytecode: yield "runtime_bytecode", runtime_bytecode
python
def _build_deployments_object( contract_type: str, deployment_bytecode: Dict[str, Any], runtime_bytecode: Dict[str, Any], compiler: Dict[str, Any], address: HexStr, tx: HexStr, block: HexStr, manifest: Dict[str, Any], ) -> Iterable[Tuple[str, Any]]: """ Returns a dict with properly formatted deployment data. """ yield "contract_type", contract_type yield "address", to_hex(address) if deployment_bytecode: yield "deployment_bytecode", deployment_bytecode if compiler: yield "compiler", compiler if tx: yield "transaction", tx if block: yield "block", block if runtime_bytecode: yield "runtime_bytecode", runtime_bytecode
[ "def", "_build_deployments_object", "(", "contract_type", ":", "str", ",", "deployment_bytecode", ":", "Dict", "[", "str", ",", "Any", "]", ",", "runtime_bytecode", ":", "Dict", "[", "str", ",", "Any", "]", ",", "compiler", ":", "Dict", "[", "str", ",", ...
Returns a dict with properly formatted deployment data.
[ "Returns", "a", "dict", "with", "properly", "formatted", "deployment", "data", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/tools/builder.py#L652-L676
train
35,756
ethpm/py-ethpm
ethpm/tools/builder.py
pin_to_ipfs
def pin_to_ipfs( manifest: Manifest, *, backend: BaseIPFSBackend, prettify: Optional[bool] = False ) -> List[Dict[str, str]]: """ Returns the IPFS pin data after pinning the manifest to the provided IPFS Backend. `pin_to_ipfs()` Should *always* be the last argument in a builder, as it will return the pin data and not the manifest. """ contents = format_manifest(manifest, prettify=prettify) with tempfile.NamedTemporaryFile() as temp: temp.write(to_bytes(text=contents)) temp.seek(0) return backend.pin_assets(Path(temp.name))
python
def pin_to_ipfs( manifest: Manifest, *, backend: BaseIPFSBackend, prettify: Optional[bool] = False ) -> List[Dict[str, str]]: """ Returns the IPFS pin data after pinning the manifest to the provided IPFS Backend. `pin_to_ipfs()` Should *always* be the last argument in a builder, as it will return the pin data and not the manifest. """ contents = format_manifest(manifest, prettify=prettify) with tempfile.NamedTemporaryFile() as temp: temp.write(to_bytes(text=contents)) temp.seek(0) return backend.pin_assets(Path(temp.name))
[ "def", "pin_to_ipfs", "(", "manifest", ":", "Manifest", ",", "*", ",", "backend", ":", "BaseIPFSBackend", ",", "prettify", ":", "Optional", "[", "bool", "]", "=", "False", ")", "->", "List", "[", "Dict", "[", "str", ",", "str", "]", "]", ":", "conten...
Returns the IPFS pin data after pinning the manifest to the provided IPFS Backend. `pin_to_ipfs()` Should *always* be the last argument in a builder, as it will return the pin data and not the manifest.
[ "Returns", "the", "IPFS", "pin", "data", "after", "pinning", "the", "manifest", "to", "the", "provided", "IPFS", "Backend", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/tools/builder.py#L776-L790
train
35,757
BrewBlox/brewblox-service
brewblox_service/service.py
create_parser
def create_parser(default_name: str) -> argparse.ArgumentParser: """ Creates the default brewblox_service ArgumentParser. Service-agnostic arguments are added. The parser allows calling code to add additional arguments before using it in create_app() Args: default_name (str): default value for the --name commandline argument. Returns: argparse.ArgumentParser: a Python ArgumentParser with defaults set. """ argparser = argparse.ArgumentParser(fromfile_prefix_chars='@') argparser.add_argument('-H', '--host', help='Host to which the app binds. [%(default)s]', default='0.0.0.0') argparser.add_argument('-p', '--port', help='Port to which the app binds. [%(default)s]', default=5000, type=int) argparser.add_argument('-o', '--output', help='Logging output. [%(default)s]') argparser.add_argument('-n', '--name', help='Service name. This will be used as prefix for all endpoints. [%(default)s]', default=default_name) argparser.add_argument('--debug', help='Run the app in debug mode. [%(default)s]', action='store_true') argparser.add_argument('--eventbus-host', help='Hostname at which the eventbus can be reached [%(default)s]', default='eventbus') argparser.add_argument('--eventbus-port', help='Port at which the eventbus can be reached [%(default)s]', default=5672, type=int) return argparser
python
def create_parser(default_name: str) -> argparse.ArgumentParser: """ Creates the default brewblox_service ArgumentParser. Service-agnostic arguments are added. The parser allows calling code to add additional arguments before using it in create_app() Args: default_name (str): default value for the --name commandline argument. Returns: argparse.ArgumentParser: a Python ArgumentParser with defaults set. """ argparser = argparse.ArgumentParser(fromfile_prefix_chars='@') argparser.add_argument('-H', '--host', help='Host to which the app binds. [%(default)s]', default='0.0.0.0') argparser.add_argument('-p', '--port', help='Port to which the app binds. [%(default)s]', default=5000, type=int) argparser.add_argument('-o', '--output', help='Logging output. [%(default)s]') argparser.add_argument('-n', '--name', help='Service name. This will be used as prefix for all endpoints. [%(default)s]', default=default_name) argparser.add_argument('--debug', help='Run the app in debug mode. [%(default)s]', action='store_true') argparser.add_argument('--eventbus-host', help='Hostname at which the eventbus can be reached [%(default)s]', default='eventbus') argparser.add_argument('--eventbus-port', help='Port at which the eventbus can be reached [%(default)s]', default=5672, type=int) return argparser
[ "def", "create_parser", "(", "default_name", ":", "str", ")", "->", "argparse", ".", "ArgumentParser", ":", "argparser", "=", "argparse", ".", "ArgumentParser", "(", "fromfile_prefix_chars", "=", "'@'", ")", "argparser", ".", "add_argument", "(", "'-H'", ",", ...
Creates the default brewblox_service ArgumentParser. Service-agnostic arguments are added. The parser allows calling code to add additional arguments before using it in create_app() Args: default_name (str): default value for the --name commandline argument. Returns: argparse.ArgumentParser: a Python ArgumentParser with defaults set.
[ "Creates", "the", "default", "brewblox_service", "ArgumentParser", ".", "Service", "-", "agnostic", "arguments", "are", "added", "." ]
f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/service.py#L68-L106
train
35,758
BrewBlox/brewblox-service
brewblox_service/service.py
create_app
def create_app( default_name: str = None, parser: argparse.ArgumentParser = None, raw_args: List[str] = None ) -> web.Application: """ Creates and configures an Aiohttp application. Args: default_name (str, optional): Default value for the --name commandline argument. This value is required if `parser` is not provided. This value will be ignored if `parser` is provided. parser (argparse.ArgumentParser, optional): Application-specific parser. If not provided, the return value of `create_parser()` will be used. raw_args (list of str, optional): Explicit commandline arguments. Defaults to sys.argv[1:] Returns: web.Application: A configured Aiohttp Application object. This Application must be furnished, and is not yet running. """ if parser is None: assert default_name, 'Default service name is required' parser = create_parser(default_name) args = parser.parse_args(raw_args) _init_logging(args) LOGGER.info(f'Creating [{args.name}] application') app = web.Application() app['config'] = vars(args) return app
python
def create_app( default_name: str = None, parser: argparse.ArgumentParser = None, raw_args: List[str] = None ) -> web.Application: """ Creates and configures an Aiohttp application. Args: default_name (str, optional): Default value for the --name commandline argument. This value is required if `parser` is not provided. This value will be ignored if `parser` is provided. parser (argparse.ArgumentParser, optional): Application-specific parser. If not provided, the return value of `create_parser()` will be used. raw_args (list of str, optional): Explicit commandline arguments. Defaults to sys.argv[1:] Returns: web.Application: A configured Aiohttp Application object. This Application must be furnished, and is not yet running. """ if parser is None: assert default_name, 'Default service name is required' parser = create_parser(default_name) args = parser.parse_args(raw_args) _init_logging(args) LOGGER.info(f'Creating [{args.name}] application') app = web.Application() app['config'] = vars(args) return app
[ "def", "create_app", "(", "default_name", ":", "str", "=", "None", ",", "parser", ":", "argparse", ".", "ArgumentParser", "=", "None", ",", "raw_args", ":", "List", "[", "str", "]", "=", "None", ")", "->", "web", ".", "Application", ":", "if", "parser"...
Creates and configures an Aiohttp application. Args: default_name (str, optional): Default value for the --name commandline argument. This value is required if `parser` is not provided. This value will be ignored if `parser` is provided. parser (argparse.ArgumentParser, optional): Application-specific parser. If not provided, the return value of `create_parser()` will be used. raw_args (list of str, optional): Explicit commandline arguments. Defaults to sys.argv[1:] Returns: web.Application: A configured Aiohttp Application object. This Application must be furnished, and is not yet running.
[ "Creates", "and", "configures", "an", "Aiohttp", "application", "." ]
f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/service.py#L109-L147
train
35,759
BrewBlox/brewblox-service
brewblox_service/service.py
furnish
def furnish(app: web.Application): """ Configures Application routes, readying it for running. This function modifies routes and resources that were added by calling code, and must be called immediately prior to `run(app)`. Args: app (web.Application): The Aiohttp Application as created by `create_app()` """ app_name = app['config']['name'] prefix = '/' + app_name.lstrip('/') app.router.add_routes(routes) cors_middleware.enable_cors(app) # Configure CORS and prefixes on all endpoints. known_resources = set() for route in list(app.router.routes()): if route.resource in known_resources: continue known_resources.add(route.resource) route.resource.add_prefix(prefix) # Configure swagger settings # We set prefix explicitly here aiohttp_swagger.setup_swagger(app, swagger_url=prefix + '/api/doc', description='', title=f'Brewblox Service "{app_name}"', api_version='0.0', contact='development@brewpi.com') LOGGER.info('Service info: ' + getenv('SERVICE_INFO', 'UNKNOWN')) for route in app.router.routes(): LOGGER.info(f'Endpoint [{route.method}] {route.resource}') for name, impl in app.get(features.FEATURES_KEY, {}).items(): LOGGER.info(f'Feature [{name}] {impl}')
python
def furnish(app: web.Application): """ Configures Application routes, readying it for running. This function modifies routes and resources that were added by calling code, and must be called immediately prior to `run(app)`. Args: app (web.Application): The Aiohttp Application as created by `create_app()` """ app_name = app['config']['name'] prefix = '/' + app_name.lstrip('/') app.router.add_routes(routes) cors_middleware.enable_cors(app) # Configure CORS and prefixes on all endpoints. known_resources = set() for route in list(app.router.routes()): if route.resource in known_resources: continue known_resources.add(route.resource) route.resource.add_prefix(prefix) # Configure swagger settings # We set prefix explicitly here aiohttp_swagger.setup_swagger(app, swagger_url=prefix + '/api/doc', description='', title=f'Brewblox Service "{app_name}"', api_version='0.0', contact='development@brewpi.com') LOGGER.info('Service info: ' + getenv('SERVICE_INFO', 'UNKNOWN')) for route in app.router.routes(): LOGGER.info(f'Endpoint [{route.method}] {route.resource}') for name, impl in app.get(features.FEATURES_KEY, {}).items(): LOGGER.info(f'Feature [{name}] {impl}')
[ "def", "furnish", "(", "app", ":", "web", ".", "Application", ")", ":", "app_name", "=", "app", "[", "'config'", "]", "[", "'name'", "]", "prefix", "=", "'/'", "+", "app_name", ".", "lstrip", "(", "'/'", ")", "app", ".", "router", ".", "add_routes", ...
Configures Application routes, readying it for running. This function modifies routes and resources that were added by calling code, and must be called immediately prior to `run(app)`. Args: app (web.Application): The Aiohttp Application as created by `create_app()`
[ "Configures", "Application", "routes", "readying", "it", "for", "running", "." ]
f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/service.py#L150-L189
train
35,760
BrewBlox/brewblox-service
brewblox_service/service.py
run
def run(app: web.Application): """ Runs the application in an async context. This function will block indefinitely until the application is shut down. Args: app (web.Application): The Aiohttp Application as created by `create_app()` """ host = app['config']['host'] port = app['config']['port'] # starts app. run_app() will automatically start the async context. web.run_app(app, host=host, port=port)
python
def run(app: web.Application): """ Runs the application in an async context. This function will block indefinitely until the application is shut down. Args: app (web.Application): The Aiohttp Application as created by `create_app()` """ host = app['config']['host'] port = app['config']['port'] # starts app. run_app() will automatically start the async context. web.run_app(app, host=host, port=port)
[ "def", "run", "(", "app", ":", "web", ".", "Application", ")", ":", "host", "=", "app", "[", "'config'", "]", "[", "'host'", "]", "port", "=", "app", "[", "'config'", "]", "[", "'port'", "]", "# starts app. run_app() will automatically start the async context....
Runs the application in an async context. This function will block indefinitely until the application is shut down. Args: app (web.Application): The Aiohttp Application as created by `create_app()`
[ "Runs", "the", "application", "in", "an", "async", "context", ".", "This", "function", "will", "block", "indefinitely", "until", "the", "application", "is", "shut", "down", "." ]
f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/service.py#L192-L205
train
35,761
ethpm/py-ethpm
ethpm/utils/deployments.py
get_linked_deployments
def get_linked_deployments(deployments: Dict[str, Any]) -> Dict[str, Any]: """ Returns all deployments found in a chain URI's deployment data that contain link dependencies. """ linked_deployments = { dep: data for dep, data in deployments.items() if get_in(("runtime_bytecode", "link_dependencies"), data) } for deployment, data in linked_deployments.items(): if any( link_dep["value"] == deployment for link_dep in data["runtime_bytecode"]["link_dependencies"] ): raise BytecodeLinkingError( f"Link dependency found in {deployment} deployment that references its " "own contract instance, which is disallowed" ) return linked_deployments
python
def get_linked_deployments(deployments: Dict[str, Any]) -> Dict[str, Any]: """ Returns all deployments found in a chain URI's deployment data that contain link dependencies. """ linked_deployments = { dep: data for dep, data in deployments.items() if get_in(("runtime_bytecode", "link_dependencies"), data) } for deployment, data in linked_deployments.items(): if any( link_dep["value"] == deployment for link_dep in data["runtime_bytecode"]["link_dependencies"] ): raise BytecodeLinkingError( f"Link dependency found in {deployment} deployment that references its " "own contract instance, which is disallowed" ) return linked_deployments
[ "def", "get_linked_deployments", "(", "deployments", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "linked_deployments", "=", "{", "dep", ":", "data", "for", "dep", ",", "data", "in", "deployments", ".",...
Returns all deployments found in a chain URI's deployment data that contain link dependencies.
[ "Returns", "all", "deployments", "found", "in", "a", "chain", "URI", "s", "deployment", "data", "that", "contain", "link", "dependencies", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/utils/deployments.py#L10-L28
train
35,762
ethpm/py-ethpm
ethpm/contract.py
apply_all_link_refs
def apply_all_link_refs( bytecode: bytes, link_refs: List[Dict[str, Any]], attr_dict: Dict[str, str] ) -> bytes: """ Applies all link references corresponding to a valid attr_dict to the bytecode. """ if link_refs is None: return bytecode link_fns = ( apply_link_ref(offset, ref["length"], attr_dict[ref["name"]]) for ref in link_refs for offset in ref["offsets"] ) linked_bytecode = pipe(bytecode, *link_fns) return linked_bytecode
python
def apply_all_link_refs( bytecode: bytes, link_refs: List[Dict[str, Any]], attr_dict: Dict[str, str] ) -> bytes: """ Applies all link references corresponding to a valid attr_dict to the bytecode. """ if link_refs is None: return bytecode link_fns = ( apply_link_ref(offset, ref["length"], attr_dict[ref["name"]]) for ref in link_refs for offset in ref["offsets"] ) linked_bytecode = pipe(bytecode, *link_fns) return linked_bytecode
[ "def", "apply_all_link_refs", "(", "bytecode", ":", "bytes", ",", "link_refs", ":", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", ",", "attr_dict", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "bytes", ":", "if", "link_refs", "is", ...
Applies all link references corresponding to a valid attr_dict to the bytecode.
[ "Applies", "all", "link", "references", "corresponding", "to", "a", "valid", "attr_dict", "to", "the", "bytecode", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/contract.py#L125-L139
train
35,763
ethpm/py-ethpm
ethpm/contract.py
apply_link_ref
def apply_link_ref(offset: int, length: int, value: bytes, bytecode: bytes) -> bytes: """ Returns the new bytecode with `value` put into the location indicated by `offset` and `length`. """ try: validate_empty_bytes(offset, length, bytecode) except ValidationError: raise BytecodeLinkingError("Link references cannot be applied to bytecode") new_bytes = ( # Ignore linting error b/c conflict b/w black & flake8 bytecode[:offset] + value + bytecode[offset + length :] # noqa: E201, E203 ) return new_bytes
python
def apply_link_ref(offset: int, length: int, value: bytes, bytecode: bytes) -> bytes: """ Returns the new bytecode with `value` put into the location indicated by `offset` and `length`. """ try: validate_empty_bytes(offset, length, bytecode) except ValidationError: raise BytecodeLinkingError("Link references cannot be applied to bytecode") new_bytes = ( # Ignore linting error b/c conflict b/w black & flake8 bytecode[:offset] + value + bytecode[offset + length :] # noqa: E201, E203 ) return new_bytes
[ "def", "apply_link_ref", "(", "offset", ":", "int", ",", "length", ":", "int", ",", "value", ":", "bytes", ",", "bytecode", ":", "bytes", ")", "->", "bytes", ":", "try", ":", "validate_empty_bytes", "(", "offset", ",", "length", ",", "bytecode", ")", "...
Returns the new bytecode with `value` put into the location indicated by `offset` and `length`.
[ "Returns", "the", "new", "bytecode", "with", "value", "put", "into", "the", "location", "indicated", "by", "offset", "and", "length", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/contract.py#L143-L158
train
35,764
ethpm/py-ethpm
ethpm/contract.py
LinkableContract.validate_attr_dict
def validate_attr_dict(self, attr_dict: Dict[str, str]) -> None: """ Validates that ContractType keys in attr_dict reference existing manifest ContractTypes. """ attr_dict_names = list(attr_dict.keys()) if not self.unlinked_references and not self.linked_references: raise BytecodeLinkingError( "Unable to validate attr dict, this contract has no linked/unlinked references." ) unlinked_refs = self.unlinked_references or ({},) linked_refs = self.linked_references or ({},) all_link_refs = unlinked_refs + linked_refs all_link_names = [ref["name"] for ref in all_link_refs] if set(attr_dict_names) != set(all_link_names): raise BytecodeLinkingError( "All link references must be defined when calling " "`link_bytecode` on a contract factory." ) for address in attr_dict.values(): if not is_canonical_address(address): raise BytecodeLinkingError( f"Address: {address} as specified in the attr_dict is not " "a valid canoncial address." )
python
def validate_attr_dict(self, attr_dict: Dict[str, str]) -> None: """ Validates that ContractType keys in attr_dict reference existing manifest ContractTypes. """ attr_dict_names = list(attr_dict.keys()) if not self.unlinked_references and not self.linked_references: raise BytecodeLinkingError( "Unable to validate attr dict, this contract has no linked/unlinked references." ) unlinked_refs = self.unlinked_references or ({},) linked_refs = self.linked_references or ({},) all_link_refs = unlinked_refs + linked_refs all_link_names = [ref["name"] for ref in all_link_refs] if set(attr_dict_names) != set(all_link_names): raise BytecodeLinkingError( "All link references must be defined when calling " "`link_bytecode` on a contract factory." ) for address in attr_dict.values(): if not is_canonical_address(address): raise BytecodeLinkingError( f"Address: {address} as specified in the attr_dict is not " "a valid canoncial address." )
[ "def", "validate_attr_dict", "(", "self", ",", "attr_dict", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "None", ":", "attr_dict_names", "=", "list", "(", "attr_dict", ".", "keys", "(", ")", ")", "if", "not", "self", ".", "unlinked_references", ...
Validates that ContractType keys in attr_dict reference existing manifest ContractTypes.
[ "Validates", "that", "ContractType", "keys", "in", "attr_dict", "reference", "existing", "manifest", "ContractTypes", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/contract.py#L82-L108
train
35,765
ethpm/py-ethpm
ethpm/dependencies.py
Dependencies.items
def items(self) -> Tuple[Tuple[str, "Package"], ...]: # type: ignore """ Return an iterable containing package name and corresponding `Package` instance that are available. """ item_dict = { name: self.build_dependencies.get(name) for name in self.build_dependencies } return tuple(item_dict.items())
python
def items(self) -> Tuple[Tuple[str, "Package"], ...]: # type: ignore """ Return an iterable containing package name and corresponding `Package` instance that are available. """ item_dict = { name: self.build_dependencies.get(name) for name in self.build_dependencies } return tuple(item_dict.items())
[ "def", "items", "(", "self", ")", "->", "Tuple", "[", "Tuple", "[", "str", ",", "\"Package\"", "]", ",", "...", "]", ":", "# type: ignore", "item_dict", "=", "{", "name", ":", "self", ".", "build_dependencies", ".", "get", "(", "name", ")", "for", "n...
Return an iterable containing package name and corresponding `Package` instance that are available.
[ "Return", "an", "iterable", "containing", "package", "name", "and", "corresponding", "Package", "instance", "that", "are", "available", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/dependencies.py#L28-L36
train
35,766
ethpm/py-ethpm
ethpm/dependencies.py
Dependencies.values
def values(self) -> List["Package"]: # type: ignore """ Return an iterable of the available `Package` instances. """ values = [self.build_dependencies.get(name) for name in self.build_dependencies] return values
python
def values(self) -> List["Package"]: # type: ignore """ Return an iterable of the available `Package` instances. """ values = [self.build_dependencies.get(name) for name in self.build_dependencies] return values
[ "def", "values", "(", "self", ")", "->", "List", "[", "\"Package\"", "]", ":", "# type: ignore", "values", "=", "[", "self", ".", "build_dependencies", ".", "get", "(", "name", ")", "for", "name", "in", "self", ".", "build_dependencies", "]", "return", "...
Return an iterable of the available `Package` instances.
[ "Return", "an", "iterable", "of", "the", "available", "Package", "instances", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/dependencies.py#L38-L43
train
35,767
ethpm/py-ethpm
ethpm/dependencies.py
Dependencies.get_dependency_package
def get_dependency_package( self, package_name: str ) -> "Package": # type: ignore # noqa: F821 """ Return the dependency Package for a given package name. """ self._validate_name(package_name) return self.build_dependencies.get(package_name)
python
def get_dependency_package( self, package_name: str ) -> "Package": # type: ignore # noqa: F821 """ Return the dependency Package for a given package name. """ self._validate_name(package_name) return self.build_dependencies.get(package_name)
[ "def", "get_dependency_package", "(", "self", ",", "package_name", ":", "str", ")", "->", "\"Package\"", ":", "# type: ignore # noqa: F821", "self", ".", "_validate_name", "(", "package_name", ")", "return", "self", ".", "build_dependencies", ".", "get", "(", "pac...
Return the dependency Package for a given package name.
[ "Return", "the", "dependency", "Package", "for", "a", "given", "package", "name", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/dependencies.py#L45-L52
train
35,768
BrewBlox/brewblox-service
brewblox_service/features.py
add
def add(app: web.Application, feature: Any, key: Hashable = None, exist_ok: bool = False ): """ Adds a new feature to the app. Features can either be registered as the default feature for the class, or be given an explicit name. Args: app (web.Application): The current Aiohttp application. feature (Any): The new feature that should be registered. It is recommended, but not required to use a `ServiceFeature`. key (Hashable, optional): The key under which the feature should be registered. Defaults to `type(feature)`. exist_ok (bool): If truthy, this function will do nothing if a feature was already registered for `key`. Otherwise, an exception is raised. """ if FEATURES_KEY not in app: app[FEATURES_KEY] = dict() key = key or type(feature) if key in app[FEATURES_KEY]: if exist_ok: return else: raise KeyError(f'Feature "{key}" already registered') app[FEATURES_KEY][key] = feature
python
def add(app: web.Application, feature: Any, key: Hashable = None, exist_ok: bool = False ): """ Adds a new feature to the app. Features can either be registered as the default feature for the class, or be given an explicit name. Args: app (web.Application): The current Aiohttp application. feature (Any): The new feature that should be registered. It is recommended, but not required to use a `ServiceFeature`. key (Hashable, optional): The key under which the feature should be registered. Defaults to `type(feature)`. exist_ok (bool): If truthy, this function will do nothing if a feature was already registered for `key`. Otherwise, an exception is raised. """ if FEATURES_KEY not in app: app[FEATURES_KEY] = dict() key = key or type(feature) if key in app[FEATURES_KEY]: if exist_ok: return else: raise KeyError(f'Feature "{key}" already registered') app[FEATURES_KEY][key] = feature
[ "def", "add", "(", "app", ":", "web", ".", "Application", ",", "feature", ":", "Any", ",", "key", ":", "Hashable", "=", "None", ",", "exist_ok", ":", "bool", "=", "False", ")", ":", "if", "FEATURES_KEY", "not", "in", "app", ":", "app", "[", "FEATUR...
Adds a new feature to the app. Features can either be registered as the default feature for the class, or be given an explicit name. Args: app (web.Application): The current Aiohttp application. feature (Any): The new feature that should be registered. It is recommended, but not required to use a `ServiceFeature`. key (Hashable, optional): The key under which the feature should be registered. Defaults to `type(feature)`. exist_ok (bool): If truthy, this function will do nothing if a feature was already registered for `key`. Otherwise, an exception is raised.
[ "Adds", "a", "new", "feature", "to", "the", "app", "." ]
f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/features.py#L14-L53
train
35,769
BrewBlox/brewblox-service
brewblox_service/features.py
get
def get(app: web.Application, feature_type: Type[Any] = None, key: Hashable = None ) -> Any: """ Finds declared feature. Identification is done based on feature type and key. Args: app (web.Application): The current Aiohttp application. feature_type (Type[Any]): The Python type of the desired feature. If specified, it will be checked against the found feature. key (Hashable): A specific identifier for the desired feature. Defaults to `feature_type` Returns: Any: The feature found for the combination of `feature_type` and `key` """ key = key or feature_type if not key: raise AssertionError('No feature identifier provided') try: found = app[FEATURES_KEY][key] except KeyError: raise KeyError(f'No feature found for "{key}"') if feature_type and not isinstance(found, feature_type): raise AssertionError(f'Found {found} did not match type "{feature_type}"') return found
python
def get(app: web.Application, feature_type: Type[Any] = None, key: Hashable = None ) -> Any: """ Finds declared feature. Identification is done based on feature type and key. Args: app (web.Application): The current Aiohttp application. feature_type (Type[Any]): The Python type of the desired feature. If specified, it will be checked against the found feature. key (Hashable): A specific identifier for the desired feature. Defaults to `feature_type` Returns: Any: The feature found for the combination of `feature_type` and `key` """ key = key or feature_type if not key: raise AssertionError('No feature identifier provided') try: found = app[FEATURES_KEY][key] except KeyError: raise KeyError(f'No feature found for "{key}"') if feature_type and not isinstance(found, feature_type): raise AssertionError(f'Found {found} did not match type "{feature_type}"') return found
[ "def", "get", "(", "app", ":", "web", ".", "Application", ",", "feature_type", ":", "Type", "[", "Any", "]", "=", "None", ",", "key", ":", "Hashable", "=", "None", ")", "->", "Any", ":", "key", "=", "key", "or", "feature_type", "if", "not", "key", ...
Finds declared feature. Identification is done based on feature type and key. Args: app (web.Application): The current Aiohttp application. feature_type (Type[Any]): The Python type of the desired feature. If specified, it will be checked against the found feature. key (Hashable): A specific identifier for the desired feature. Defaults to `feature_type` Returns: Any: The feature found for the combination of `feature_type` and `key`
[ "Finds", "declared", "feature", ".", "Identification", "is", "done", "based", "on", "feature", "type", "and", "key", "." ]
f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/features.py#L56-L92
train
35,770
ethpm/py-ethpm
ethpm/utils/contract.py
validate_minimal_contract_factory_data
def validate_minimal_contract_factory_data(contract_data: Dict[str, str]) -> None: """ Validate that contract data in a package contains at least an "abi" and "deployment_bytecode" necessary to generate a deployable contract factory. """ if not all(key in contract_data.keys() for key in ("abi", "deployment_bytecode")): raise InsufficientAssetsError( "Minimum required contract data to generate a deployable " "contract factory (abi & deployment_bytecode) not found." )
python
def validate_minimal_contract_factory_data(contract_data: Dict[str, str]) -> None: """ Validate that contract data in a package contains at least an "abi" and "deployment_bytecode" necessary to generate a deployable contract factory. """ if not all(key in contract_data.keys() for key in ("abi", "deployment_bytecode")): raise InsufficientAssetsError( "Minimum required contract data to generate a deployable " "contract factory (abi & deployment_bytecode) not found." )
[ "def", "validate_minimal_contract_factory_data", "(", "contract_data", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "None", ":", "if", "not", "all", "(", "key", "in", "contract_data", ".", "keys", "(", ")", "for", "key", "in", "(", "\"abi\"", ","...
Validate that contract data in a package contains at least an "abi" and "deployment_bytecode" necessary to generate a deployable contract factory.
[ "Validate", "that", "contract", "data", "in", "a", "package", "contains", "at", "least", "an", "abi", "and", "deployment_bytecode", "necessary", "to", "generate", "a", "deployable", "contract", "factory", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/utils/contract.py#L10-L19
train
35,771
ethpm/py-ethpm
ethpm/utils/contract.py
generate_contract_factory_kwargs
def generate_contract_factory_kwargs( contract_data: Dict[str, Any] ) -> Generator[Tuple[str, Any], None, None]: """ Build a dictionary of kwargs to be passed into contract factory. """ if "abi" in contract_data: yield "abi", contract_data["abi"] if "deployment_bytecode" in contract_data: yield "bytecode", contract_data["deployment_bytecode"]["bytecode"] if "link_references" in contract_data["deployment_bytecode"]: yield "unlinked_references", tuple( contract_data["deployment_bytecode"]["link_references"] ) if "runtime_bytecode" in contract_data: yield "bytecode_runtime", contract_data["runtime_bytecode"]["bytecode"] if "link_references" in contract_data["runtime_bytecode"]: yield "linked_references", tuple( contract_data["runtime_bytecode"]["link_references"] )
python
def generate_contract_factory_kwargs( contract_data: Dict[str, Any] ) -> Generator[Tuple[str, Any], None, None]: """ Build a dictionary of kwargs to be passed into contract factory. """ if "abi" in contract_data: yield "abi", contract_data["abi"] if "deployment_bytecode" in contract_data: yield "bytecode", contract_data["deployment_bytecode"]["bytecode"] if "link_references" in contract_data["deployment_bytecode"]: yield "unlinked_references", tuple( contract_data["deployment_bytecode"]["link_references"] ) if "runtime_bytecode" in contract_data: yield "bytecode_runtime", contract_data["runtime_bytecode"]["bytecode"] if "link_references" in contract_data["runtime_bytecode"]: yield "linked_references", tuple( contract_data["runtime_bytecode"]["link_references"] )
[ "def", "generate_contract_factory_kwargs", "(", "contract_data", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Generator", "[", "Tuple", "[", "str", ",", "Any", "]", ",", "None", ",", "None", "]", ":", "if", "\"abi\"", "in", "contract_data", ":",...
Build a dictionary of kwargs to be passed into contract factory.
[ "Build", "a", "dictionary", "of", "kwargs", "to", "be", "passed", "into", "contract", "factory", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/utils/contract.py#L36-L57
train
35,772
BrewBlox/brewblox-service
brewblox_service/events.py
EventSubscription._relay
async def _relay(self, channel: aioamqp.channel.Channel, body: str, envelope: aioamqp.envelope.Envelope, properties: aioamqp.properties.Properties): """Relays incoming messages between the queue and the user callback""" try: await channel.basic_client_ack(envelope.delivery_tag) await self.on_message(self, envelope.routing_key, json.loads(body)) except Exception as ex: LOGGER.error(f'Exception relaying message in {self}: {ex}')
python
async def _relay(self, channel: aioamqp.channel.Channel, body: str, envelope: aioamqp.envelope.Envelope, properties: aioamqp.properties.Properties): """Relays incoming messages between the queue and the user callback""" try: await channel.basic_client_ack(envelope.delivery_tag) await self.on_message(self, envelope.routing_key, json.loads(body)) except Exception as ex: LOGGER.error(f'Exception relaying message in {self}: {ex}')
[ "async", "def", "_relay", "(", "self", ",", "channel", ":", "aioamqp", ".", "channel", ".", "Channel", ",", "body", ":", "str", ",", "envelope", ":", "aioamqp", ".", "envelope", ".", "Envelope", ",", "properties", ":", "aioamqp", ".", "properties", ".", ...
Relays incoming messages between the queue and the user callback
[ "Relays", "incoming", "messages", "between", "the", "queue", "and", "the", "user", "callback" ]
f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/events.py#L122-L132
train
35,773
BrewBlox/brewblox-service
brewblox_service/events.py
EventListener._lazy_listen
def _lazy_listen(self): """ Ensures that the listener task only runs when actually needed. This function is a no-op if any of the preconditions is not met. Preconditions are: * The application is running (self._loop is set) * The task is not already running * There are subscriptions: either pending, or active """ if all([ self._loop, not self.running, self._subscriptions or (self._pending and not self._pending.empty()), ]): self._task = self._loop.create_task(self._listen())
python
def _lazy_listen(self): """ Ensures that the listener task only runs when actually needed. This function is a no-op if any of the preconditions is not met. Preconditions are: * The application is running (self._loop is set) * The task is not already running * There are subscriptions: either pending, or active """ if all([ self._loop, not self.running, self._subscriptions or (self._pending and not self._pending.empty()), ]): self._task = self._loop.create_task(self._listen())
[ "def", "_lazy_listen", "(", "self", ")", ":", "if", "all", "(", "[", "self", ".", "_loop", ",", "not", "self", ".", "running", ",", "self", ".", "_subscriptions", "or", "(", "self", ".", "_pending", "and", "not", "self", ".", "_pending", ".", "empty"...
Ensures that the listener task only runs when actually needed. This function is a no-op if any of the preconditions is not met. Preconditions are: * The application is running (self._loop is set) * The task is not already running * There are subscriptions: either pending, or active
[ "Ensures", "that", "the", "listener", "task", "only", "runs", "when", "actually", "needed", ".", "This", "function", "is", "a", "no", "-", "op", "if", "any", "of", "the", "preconditions", "is", "not", "met", "." ]
f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/events.py#L169-L184
train
35,774
BrewBlox/brewblox-service
brewblox_service/events.py
EventListener.subscribe
def subscribe(self, exchange_name: str, routing: str, exchange_type: ExchangeType_ = 'topic', on_message: EVENT_CALLBACK_ = None ) -> EventSubscription: """Adds a new event subscription to the listener. Actual queue declaration to the remote message server is done when connected. If the listener is not currently connected, it defers declaration. All existing subscriptions are redeclared on the remote if `EventListener` loses and recreates the connection. Args: exchange_name (str): Name of the AMQP exchange. Messages are always published to a specific exchange. routing (str): Filter messages passing through the exchange. A routing key is a '.'-separated string, and accepts '#' and '*' wildcards. exchange_type (ExchangeType_, optional): If the exchange does not yet exist, it will be created with this type. Default is `topic`, acceptable values are `topic`, `fanout`, or `direct`. on_message (EVENT_CALLBACK_, optional): The function to be called when a new message is received. If `on_message` is none, it will default to logging the message. Returns: EventSubscription: The newly created subscription. This value can safely be discarded: EventListener keeps its own reference. """ sub = EventSubscription( exchange_name, routing, exchange_type, on_message=on_message ) if self._pending is not None: self._pending.put_nowait(sub) else: self._pending_pre_async.append(sub) LOGGER.info(f'Deferred event bus subscription: [{sub}]') self._lazy_listen() return sub
python
def subscribe(self, exchange_name: str, routing: str, exchange_type: ExchangeType_ = 'topic', on_message: EVENT_CALLBACK_ = None ) -> EventSubscription: """Adds a new event subscription to the listener. Actual queue declaration to the remote message server is done when connected. If the listener is not currently connected, it defers declaration. All existing subscriptions are redeclared on the remote if `EventListener` loses and recreates the connection. Args: exchange_name (str): Name of the AMQP exchange. Messages are always published to a specific exchange. routing (str): Filter messages passing through the exchange. A routing key is a '.'-separated string, and accepts '#' and '*' wildcards. exchange_type (ExchangeType_, optional): If the exchange does not yet exist, it will be created with this type. Default is `topic`, acceptable values are `topic`, `fanout`, or `direct`. on_message (EVENT_CALLBACK_, optional): The function to be called when a new message is received. If `on_message` is none, it will default to logging the message. Returns: EventSubscription: The newly created subscription. This value can safely be discarded: EventListener keeps its own reference. """ sub = EventSubscription( exchange_name, routing, exchange_type, on_message=on_message ) if self._pending is not None: self._pending.put_nowait(sub) else: self._pending_pre_async.append(sub) LOGGER.info(f'Deferred event bus subscription: [{sub}]') self._lazy_listen() return sub
[ "def", "subscribe", "(", "self", ",", "exchange_name", ":", "str", ",", "routing", ":", "str", ",", "exchange_type", ":", "ExchangeType_", "=", "'topic'", ",", "on_message", ":", "EVENT_CALLBACK_", "=", "None", ")", "->", "EventSubscription", ":", "sub", "="...
Adds a new event subscription to the listener. Actual queue declaration to the remote message server is done when connected. If the listener is not currently connected, it defers declaration. All existing subscriptions are redeclared on the remote if `EventListener` loses and recreates the connection. Args: exchange_name (str): Name of the AMQP exchange. Messages are always published to a specific exchange. routing (str): Filter messages passing through the exchange. A routing key is a '.'-separated string, and accepts '#' and '*' wildcards. exchange_type (ExchangeType_, optional): If the exchange does not yet exist, it will be created with this type. Default is `topic`, acceptable values are `topic`, `fanout`, or `direct`. on_message (EVENT_CALLBACK_, optional): The function to be called when a new message is received. If `on_message` is none, it will default to logging the message. Returns: EventSubscription: The newly created subscription. This value can safely be discarded: EventListener keeps its own reference.
[ "Adds", "a", "new", "event", "subscription", "to", "the", "listener", "." ]
f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/events.py#L275-L324
train
35,775
BrewBlox/brewblox-service
brewblox_service/events.py
EventPublisher.publish
async def publish(self, exchange: str, routing: str, message: Union[str, dict], exchange_type: ExchangeType_ = 'topic'): """ Publish a new event message. Connections are created automatically when calling `publish()`, and will attempt to reconnect if connection was lost. For more information on publishing AMQP messages, see https://www.rabbitmq.com/tutorials/tutorial-three-python.html Args: exchange (str): The AMQP message exchange to publish the message to. A new exchange will be created if it does not yet exist. routing (str): The routing identification with which the message should be published. Subscribers use routing information for fine-grained filtering. Routing can be expressed as a '.'-separated path. message (Union[str, dict]): The message body. It will be serialized before transmission. exchange_type (ExchangeType_, optional): When publishing to a previously undeclared exchange, it will be created. `exchange_type` defines how the exchange distributes messages between subscribers. The default is 'topic', and acceptable values are: 'topic', 'direct', or 'fanout'. Raises: aioamqp.exceptions.AioamqpException: * Failed to connect to AMQP host * Failed to send message * `exchange` already exists, but has a different `exchange_type` """ try: await self._ensure_channel() except Exception: # If server has restarted since our last attempt, ensure channel will fail (old connection invalid) # Retry once to check whether a new connection can be made await self._ensure_channel() # json.dumps() also correctly handles strings data = json.dumps(message).encode() await self._channel.exchange_declare( exchange_name=exchange, type_name=exchange_type, auto_delete=True ) await self._channel.basic_publish( payload=data, exchange_name=exchange, routing_key=routing )
python
async def publish(self, exchange: str, routing: str, message: Union[str, dict], exchange_type: ExchangeType_ = 'topic'): """ Publish a new event message. Connections are created automatically when calling `publish()`, and will attempt to reconnect if connection was lost. For more information on publishing AMQP messages, see https://www.rabbitmq.com/tutorials/tutorial-three-python.html Args: exchange (str): The AMQP message exchange to publish the message to. A new exchange will be created if it does not yet exist. routing (str): The routing identification with which the message should be published. Subscribers use routing information for fine-grained filtering. Routing can be expressed as a '.'-separated path. message (Union[str, dict]): The message body. It will be serialized before transmission. exchange_type (ExchangeType_, optional): When publishing to a previously undeclared exchange, it will be created. `exchange_type` defines how the exchange distributes messages between subscribers. The default is 'topic', and acceptable values are: 'topic', 'direct', or 'fanout'. Raises: aioamqp.exceptions.AioamqpException: * Failed to connect to AMQP host * Failed to send message * `exchange` already exists, but has a different `exchange_type` """ try: await self._ensure_channel() except Exception: # If server has restarted since our last attempt, ensure channel will fail (old connection invalid) # Retry once to check whether a new connection can be made await self._ensure_channel() # json.dumps() also correctly handles strings data = json.dumps(message).encode() await self._channel.exchange_declare( exchange_name=exchange, type_name=exchange_type, auto_delete=True ) await self._channel.basic_publish( payload=data, exchange_name=exchange, routing_key=routing )
[ "async", "def", "publish", "(", "self", ",", "exchange", ":", "str", ",", "routing", ":", "str", ",", "message", ":", "Union", "[", "str", ",", "dict", "]", ",", "exchange_type", ":", "ExchangeType_", "=", "'topic'", ")", ":", "try", ":", "await", "s...
Publish a new event message. Connections are created automatically when calling `publish()`, and will attempt to reconnect if connection was lost. For more information on publishing AMQP messages, see https://www.rabbitmq.com/tutorials/tutorial-three-python.html Args: exchange (str): The AMQP message exchange to publish the message to. A new exchange will be created if it does not yet exist. routing (str): The routing identification with which the message should be published. Subscribers use routing information for fine-grained filtering. Routing can be expressed as a '.'-separated path. message (Union[str, dict]): The message body. It will be serialized before transmission. exchange_type (ExchangeType_, optional): When publishing to a previously undeclared exchange, it will be created. `exchange_type` defines how the exchange distributes messages between subscribers. The default is 'topic', and acceptable values are: 'topic', 'direct', or 'fanout'. Raises: aioamqp.exceptions.AioamqpException: * Failed to connect to AMQP host * Failed to send message * `exchange` already exists, but has a different `exchange_type`
[ "Publish", "a", "new", "event", "message", "." ]
f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/events.py#L396-L454
train
35,776
ethpm/py-ethpm
ethpm/utils/registry.py
is_ens_domain
def is_ens_domain(authority: str) -> bool: """ Return false if authority is not a valid ENS domain. """ # check that authority ends with the tld '.eth' # check that there are either 2 or 3 subdomains in the authority # i.e. zeppelinos.eth or packages.zeppelinos.eth if authority[-4:] != ".eth" or len(authority.split(".")) not in [2, 3]: return False return True
python
def is_ens_domain(authority: str) -> bool: """ Return false if authority is not a valid ENS domain. """ # check that authority ends with the tld '.eth' # check that there are either 2 or 3 subdomains in the authority # i.e. zeppelinos.eth or packages.zeppelinos.eth if authority[-4:] != ".eth" or len(authority.split(".")) not in [2, 3]: return False return True
[ "def", "is_ens_domain", "(", "authority", ":", "str", ")", "->", "bool", ":", "# check that authority ends with the tld '.eth'", "# check that there are either 2 or 3 subdomains in the authority", "# i.e. zeppelinos.eth or packages.zeppelinos.eth", "if", "authority", "[", "-", "4",...
Return false if authority is not a valid ENS domain.
[ "Return", "false", "if", "authority", "is", "not", "a", "valid", "ENS", "domain", "." ]
81ed58d7c636fe00c6770edeb0401812b1a5e8fc
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/utils/registry.py#L5-L14
train
35,777
heroku/sf-suds
suds/sudsobject.py
Printer.exclude
def exclude(self, d, item): """ check metadata for excluded items """ try: md = d.__metadata__ pmd = getattr(md, '__print__', None) if pmd is None: return False excludes = getattr(pmd, 'excludes', []) return ( item[0] in excludes ) except: pass return False
python
def exclude(self, d, item): """ check metadata for excluded items """ try: md = d.__metadata__ pmd = getattr(md, '__print__', None) if pmd is None: return False excludes = getattr(pmd, 'excludes', []) return ( item[0] in excludes ) except: pass return False
[ "def", "exclude", "(", "self", ",", "d", ",", "item", ")", ":", "try", ":", "md", "=", "d", ".", "__metadata__", "pmd", "=", "getattr", "(", "md", ",", "'__print__'", ",", "None", ")", "if", "pmd", "is", "None", ":", "return", "False", "excludes", ...
check metadata for excluded items
[ "check", "metadata", "for", "excluded", "items" ]
44b6743a45ff4447157605d6fecc9bf5922ce68a
https://github.com/heroku/sf-suds/blob/44b6743a45ff4447157605d6fecc9bf5922ce68a/suds/sudsobject.py#L379-L390
train
35,778
heroku/sf-suds
suds/resolver.py
Resolver.find
def find(self, name, resolved=True): """ Get the definition object for the schema object by name. @param name: The name of a schema object. @type name: basestring @param resolved: A flag indicating that the fully resolved type should be returned. @type resolved: boolean @return: The found schema I{type} @rtype: L{xsd.sxbase.SchemaObject} """ #log.debug('searching schema for (%s)', name) qref = qualify(name, self.schema.root, self.schema.tns) query = BlindQuery(qref) result = query.execute(self.schema) if result is None: log.error('(%s) not-found', name) return None #log.debug('found (%s) as (%s)', name, Repr(result)) if resolved: result = result.resolve() return result
python
def find(self, name, resolved=True): """ Get the definition object for the schema object by name. @param name: The name of a schema object. @type name: basestring @param resolved: A flag indicating that the fully resolved type should be returned. @type resolved: boolean @return: The found schema I{type} @rtype: L{xsd.sxbase.SchemaObject} """ #log.debug('searching schema for (%s)', name) qref = qualify(name, self.schema.root, self.schema.tns) query = BlindQuery(qref) result = query.execute(self.schema) if result is None: log.error('(%s) not-found', name) return None #log.debug('found (%s) as (%s)', name, Repr(result)) if resolved: result = result.resolve() return result
[ "def", "find", "(", "self", ",", "name", ",", "resolved", "=", "True", ")", ":", "#log.debug('searching schema for (%s)', name)", "qref", "=", "qualify", "(", "name", ",", "self", ".", "schema", ".", "root", ",", "self", ".", "schema", ".", "tns", ")", "...
Get the definition object for the schema object by name. @param name: The name of a schema object. @type name: basestring @param resolved: A flag indicating that the fully resolved type should be returned. @type resolved: boolean @return: The found schema I{type} @rtype: L{xsd.sxbase.SchemaObject}
[ "Get", "the", "definition", "object", "for", "the", "schema", "object", "by", "name", "." ]
44b6743a45ff4447157605d6fecc9bf5922ce68a
https://github.com/heroku/sf-suds/blob/44b6743a45ff4447157605d6fecc9bf5922ce68a/suds/resolver.py#L47-L68
train
35,779
heroku/sf-suds
suds/resolver.py
TreeResolver.getchild
def getchild(self, name, parent): """ get a child by name """ #log.debug('searching parent (%s) for (%s)', Repr(parent), name) if name.startswith('@'): return parent.get_attribute(name[1:]) else: return parent.get_child(name)
python
def getchild(self, name, parent): """ get a child by name """ #log.debug('searching parent (%s) for (%s)', Repr(parent), name) if name.startswith('@'): return parent.get_attribute(name[1:]) else: return parent.get_child(name)
[ "def", "getchild", "(", "self", ",", "name", ",", "parent", ")", ":", "#log.debug('searching parent (%s) for (%s)', Repr(parent), name)", "if", "name", ".", "startswith", "(", "'@'", ")", ":", "return", "parent", ".", "get_attribute", "(", "name", "[", "1", ":",...
get a child by name
[ "get", "a", "child", "by", "name" ]
44b6743a45ff4447157605d6fecc9bf5922ce68a
https://github.com/heroku/sf-suds/blob/44b6743a45ff4447157605d6fecc9bf5922ce68a/suds/resolver.py#L297-L303
train
35,780
heroku/sf-suds
suds/store.py
DocumentStore.find
def find(self, location): """ Find the specified location in the store. @param location: The I{location} part of a URL. @type location: str @return: An input stream to the document. @rtype: StringIO """ try: content = self.store[location] return StringIO(content) except: reason = 'location "%s" not in document store' % location raise Exception, reason
python
def find(self, location): """ Find the specified location in the store. @param location: The I{location} part of a URL. @type location: str @return: An input stream to the document. @rtype: StringIO """ try: content = self.store[location] return StringIO(content) except: reason = 'location "%s" not in document store' % location raise Exception, reason
[ "def", "find", "(", "self", ",", "location", ")", ":", "try", ":", "content", "=", "self", ".", "store", "[", "location", "]", "return", "StringIO", "(", "content", ")", "except", ":", "reason", "=", "'location \"%s\" not in document store'", "%", "location"...
Find the specified location in the store. @param location: The I{location} part of a URL. @type location: str @return: An input stream to the document. @rtype: StringIO
[ "Find", "the", "specified", "location", "in", "the", "store", "." ]
44b6743a45ff4447157605d6fecc9bf5922ce68a
https://github.com/heroku/sf-suds/blob/44b6743a45ff4447157605d6fecc9bf5922ce68a/suds/store.py#L567-L580
train
35,781
heroku/sf-suds
suds/bindings/binding.py
Binding.get_message
def get_message(self, method, args, kwargs, options=None): """ Get the soap message for the specified method, args and soapheaders. This is the entry point for creating the outbound soap message. @param method: The method being invoked. @type method: I{service.Method} @param args: A list of args for the method invoked. @type args: list @param kwargs: Named (keyword) args for the method invoked. @type kwargs: dict @return: The soap envelope. @rtype: L{Document} """ content = self.headercontent(method, options=options) header = self.header(content) content = self.bodycontent(method, args, kwargs) body = self.body(content) env = self.envelope(header, body) if self.options().prefixes: body.normalizePrefixes() env.promotePrefixes() else: env.refitPrefixes() return Document(env)
python
def get_message(self, method, args, kwargs, options=None): """ Get the soap message for the specified method, args and soapheaders. This is the entry point for creating the outbound soap message. @param method: The method being invoked. @type method: I{service.Method} @param args: A list of args for the method invoked. @type args: list @param kwargs: Named (keyword) args for the method invoked. @type kwargs: dict @return: The soap envelope. @rtype: L{Document} """ content = self.headercontent(method, options=options) header = self.header(content) content = self.bodycontent(method, args, kwargs) body = self.body(content) env = self.envelope(header, body) if self.options().prefixes: body.normalizePrefixes() env.promotePrefixes() else: env.refitPrefixes() return Document(env)
[ "def", "get_message", "(", "self", ",", "method", ",", "args", ",", "kwargs", ",", "options", "=", "None", ")", ":", "content", "=", "self", ".", "headercontent", "(", "method", ",", "options", "=", "options", ")", "header", "=", "self", ".", "header",...
Get the soap message for the specified method, args and soapheaders. This is the entry point for creating the outbound soap message. @param method: The method being invoked. @type method: I{service.Method} @param args: A list of args for the method invoked. @type args: list @param kwargs: Named (keyword) args for the method invoked. @type kwargs: dict @return: The soap envelope. @rtype: L{Document}
[ "Get", "the", "soap", "message", "for", "the", "specified", "method", "args", "and", "soapheaders", ".", "This", "is", "the", "entry", "point", "for", "creating", "the", "outbound", "soap", "message", "." ]
44b6743a45ff4447157605d6fecc9bf5922ce68a
https://github.com/heroku/sf-suds/blob/44b6743a45ff4447157605d6fecc9bf5922ce68a/suds/bindings/binding.py#L104-L128
train
35,782
heroku/sf-suds
suds/client.py
SoapClient.send
def send(self, soapenv): """ Send soap message. @param soapenv: A soap envelope to send. @type soapenv: L{Document} @return: The reply to the sent message. @rtype: I{builtin} or I{subclass of} L{Object} """ result = None location = self.location() binding = self.method.binding.input transport = self.options.transport retxml = self.options.retxml prettyxml = self.options.prettyxml log.debug('sending to (%s)\nmessage:\n%s', location, soapenv) try: self.last_sent(soapenv) plugins = PluginContainer(self.options.plugins) plugins.message.marshalled(envelope=soapenv.root()) if prettyxml: soapenv = soapenv.str() else: soapenv = soapenv.plain() soapenv = soapenv.encode('utf-8') plugins.message.sending(envelope=soapenv) request = Request(location, soapenv) request.headers = self.headers() reply = transport.send(request) ctx = plugins.message.received(reply=reply.message) reply.message = ctx.reply if retxml: result = reply.message else: timer = metrics.Timer() timer.start() result = self.succeeded(binding, reply.message) #cProfile.runctx("result = self.succeeded(binding, reply.message)", globals(), locals(), "unmarshal_prof") timer.stop() metrics.log.debug( "succeeded took: %s", timer) except TransportError, e: if e.httpcode in (202,204): result = None else: log.error(self.last_sent()) result = self.failed(binding, e) return result
python
def send(self, soapenv): """ Send soap message. @param soapenv: A soap envelope to send. @type soapenv: L{Document} @return: The reply to the sent message. @rtype: I{builtin} or I{subclass of} L{Object} """ result = None location = self.location() binding = self.method.binding.input transport = self.options.transport retxml = self.options.retxml prettyxml = self.options.prettyxml log.debug('sending to (%s)\nmessage:\n%s', location, soapenv) try: self.last_sent(soapenv) plugins = PluginContainer(self.options.plugins) plugins.message.marshalled(envelope=soapenv.root()) if prettyxml: soapenv = soapenv.str() else: soapenv = soapenv.plain() soapenv = soapenv.encode('utf-8') plugins.message.sending(envelope=soapenv) request = Request(location, soapenv) request.headers = self.headers() reply = transport.send(request) ctx = plugins.message.received(reply=reply.message) reply.message = ctx.reply if retxml: result = reply.message else: timer = metrics.Timer() timer.start() result = self.succeeded(binding, reply.message) #cProfile.runctx("result = self.succeeded(binding, reply.message)", globals(), locals(), "unmarshal_prof") timer.stop() metrics.log.debug( "succeeded took: %s", timer) except TransportError, e: if e.httpcode in (202,204): result = None else: log.error(self.last_sent()) result = self.failed(binding, e) return result
[ "def", "send", "(", "self", ",", "soapenv", ")", ":", "result", "=", "None", "location", "=", "self", ".", "location", "(", ")", "binding", "=", "self", ".", "method", ".", "binding", ".", "input", "transport", "=", "self", ".", "options", ".", "tran...
Send soap message. @param soapenv: A soap envelope to send. @type soapenv: L{Document} @return: The reply to the sent message. @rtype: I{builtin} or I{subclass of} L{Object}
[ "Send", "soap", "message", "." ]
44b6743a45ff4447157605d6fecc9bf5922ce68a
https://github.com/heroku/sf-suds/blob/44b6743a45ff4447157605d6fecc9bf5922ce68a/suds/client.py#L624-L671
train
35,783
heroku/sf-suds
suds/client.py
SoapClient.succeeded
def succeeded(self, binding, reply): """ Request succeeded, process the reply @param binding: The binding to be used to process the reply. @type binding: L{bindings.binding.Binding} @param reply: The raw reply text. @type reply: str @return: The method result. @rtype: I{builtin}, L{Object} @raise WebFault: On server. """ log.debug('http succeeded:\n%s', reply) plugins = PluginContainer(self.options.plugins) if len(reply) > 0: with LocalTimer() as lt: reply, result = binding.get_reply(self.method, reply) self.last_received(reply) metrics.log.debug("Calling binding.get_reply took: %.03f" % lt.interval) else: result = None ctx = plugins.message.unmarshalled(reply=result) result = ctx.reply if self.options.faults: return result else: return (200, result)
python
def succeeded(self, binding, reply): """ Request succeeded, process the reply @param binding: The binding to be used to process the reply. @type binding: L{bindings.binding.Binding} @param reply: The raw reply text. @type reply: str @return: The method result. @rtype: I{builtin}, L{Object} @raise WebFault: On server. """ log.debug('http succeeded:\n%s', reply) plugins = PluginContainer(self.options.plugins) if len(reply) > 0: with LocalTimer() as lt: reply, result = binding.get_reply(self.method, reply) self.last_received(reply) metrics.log.debug("Calling binding.get_reply took: %.03f" % lt.interval) else: result = None ctx = plugins.message.unmarshalled(reply=result) result = ctx.reply if self.options.faults: return result else: return (200, result)
[ "def", "succeeded", "(", "self", ",", "binding", ",", "reply", ")", ":", "log", ".", "debug", "(", "'http succeeded:\\n%s'", ",", "reply", ")", "plugins", "=", "PluginContainer", "(", "self", ".", "options", ".", "plugins", ")", "if", "len", "(", "reply"...
Request succeeded, process the reply @param binding: The binding to be used to process the reply. @type binding: L{bindings.binding.Binding} @param reply: The raw reply text. @type reply: str @return: The method result. @rtype: I{builtin}, L{Object} @raise WebFault: On server.
[ "Request", "succeeded", "process", "the", "reply" ]
44b6743a45ff4447157605d6fecc9bf5922ce68a
https://github.com/heroku/sf-suds/blob/44b6743a45ff4447157605d6fecc9bf5922ce68a/suds/client.py#L685-L710
train
35,784
heroku/sf-suds
suds/client.py
SoapClient.failed
def failed(self, binding, error): """ Request failed, process reply based on reason @param binding: The binding to be used to process the reply. @type binding: L{suds.bindings.binding.Binding} @param error: The http error message @type error: L{transport.TransportError} """ status, reason = (error.httpcode, tostr(error)) reply = error.fp.read() log.debug('http failed:\n%s', reply) if status == 500: if len(reply) > 0: r, p = binding.get_fault(reply) self.last_received(r) return (status, p) else: return (status, None) if self.options.faults: raise HttpWebFault(status, reason) else: return (status, None)
python
def failed(self, binding, error): """ Request failed, process reply based on reason @param binding: The binding to be used to process the reply. @type binding: L{suds.bindings.binding.Binding} @param error: The http error message @type error: L{transport.TransportError} """ status, reason = (error.httpcode, tostr(error)) reply = error.fp.read() log.debug('http failed:\n%s', reply) if status == 500: if len(reply) > 0: r, p = binding.get_fault(reply) self.last_received(r) return (status, p) else: return (status, None) if self.options.faults: raise HttpWebFault(status, reason) else: return (status, None)
[ "def", "failed", "(", "self", ",", "binding", ",", "error", ")", ":", "status", ",", "reason", "=", "(", "error", ".", "httpcode", ",", "tostr", "(", "error", ")", ")", "reply", "=", "error", ".", "fp", ".", "read", "(", ")", "log", ".", "debug",...
Request failed, process reply based on reason @param binding: The binding to be used to process the reply. @type binding: L{suds.bindings.binding.Binding} @param error: The http error message @type error: L{transport.TransportError}
[ "Request", "failed", "process", "reply", "based", "on", "reason" ]
44b6743a45ff4447157605d6fecc9bf5922ce68a
https://github.com/heroku/sf-suds/blob/44b6743a45ff4447157605d6fecc9bf5922ce68a/suds/client.py#L712-L733
train
35,785
asottile/cheetah_lint
cheetah_lint/flake.py
_get_line_no_from_comments
def _get_line_no_from_comments(py_line): """Return the line number parsed from the comment or 0.""" matched = LINECOL_COMMENT_RE.match(py_line) if matched: return int(matched.group(1)) else: return 0
python
def _get_line_no_from_comments(py_line): """Return the line number parsed from the comment or 0.""" matched = LINECOL_COMMENT_RE.match(py_line) if matched: return int(matched.group(1)) else: return 0
[ "def", "_get_line_no_from_comments", "(", "py_line", ")", ":", "matched", "=", "LINECOL_COMMENT_RE", ".", "match", "(", "py_line", ")", "if", "matched", ":", "return", "int", "(", "matched", ".", "group", "(", "1", ")", ")", "else", ":", "return", "0" ]
Return the line number parsed from the comment or 0.
[ "Return", "the", "line", "number", "parsed", "from", "the", "comment", "or", "0", "." ]
1ecd54933e63073a7e77d65c8a2514a21e145c34
https://github.com/asottile/cheetah_lint/blob/1ecd54933e63073a7e77d65c8a2514a21e145c34/cheetah_lint/flake.py#L131-L137
train
35,786
asottile/cheetah_lint
cheetah_lint/flake.py
_find_fuzzy_line
def _find_fuzzy_line( py_line_no, py_by_line_no, cheetah_by_line_no, prefer_first ): """Attempt to fuzzily find matching lines.""" stripped_line = _fuzz_py_line(py_by_line_no[py_line_no]) cheetah_lower_bound, cheetah_upper_bound = _find_bounds( py_line_no, py_by_line_no, cheetah_by_line_no, ) sliced = list(enumerate(cheetah_by_line_no))[ cheetah_lower_bound:cheetah_upper_bound ] if not prefer_first: sliced = reversed(sliced) for line_no, line in sliced: if stripped_line in _fuzz_cheetah_line(line): return line_no else: # We've failed to find a matching line return 0
python
def _find_fuzzy_line( py_line_no, py_by_line_no, cheetah_by_line_no, prefer_first ): """Attempt to fuzzily find matching lines.""" stripped_line = _fuzz_py_line(py_by_line_no[py_line_no]) cheetah_lower_bound, cheetah_upper_bound = _find_bounds( py_line_no, py_by_line_no, cheetah_by_line_no, ) sliced = list(enumerate(cheetah_by_line_no))[ cheetah_lower_bound:cheetah_upper_bound ] if not prefer_first: sliced = reversed(sliced) for line_no, line in sliced: if stripped_line in _fuzz_cheetah_line(line): return line_no else: # We've failed to find a matching line return 0
[ "def", "_find_fuzzy_line", "(", "py_line_no", ",", "py_by_line_no", ",", "cheetah_by_line_no", ",", "prefer_first", ")", ":", "stripped_line", "=", "_fuzz_py_line", "(", "py_by_line_no", "[", "py_line_no", "]", ")", "cheetah_lower_bound", ",", "cheetah_upper_bound", "...
Attempt to fuzzily find matching lines.
[ "Attempt", "to", "fuzzily", "find", "matching", "lines", "." ]
1ecd54933e63073a7e77d65c8a2514a21e145c34
https://github.com/asottile/cheetah_lint/blob/1ecd54933e63073a7e77d65c8a2514a21e145c34/cheetah_lint/flake.py#L184-L204
train
35,787
asottile/cheetah_lint
cheetah_lint/reorder_imports.py
perform_step
def perform_step(file_contents, step): """Performs a step of the transformation. :param text file_contents: Contends of the cheetah template :param function step: Function taking xmldoc and returning new contents :returns: new contents of the file. """ assert type(file_contents) is not bytes xmldoc = parse(file_contents) return step(xmldoc)
python
def perform_step(file_contents, step): """Performs a step of the transformation. :param text file_contents: Contends of the cheetah template :param function step: Function taking xmldoc and returning new contents :returns: new contents of the file. """ assert type(file_contents) is not bytes xmldoc = parse(file_contents) return step(xmldoc)
[ "def", "perform_step", "(", "file_contents", ",", "step", ")", ":", "assert", "type", "(", "file_contents", ")", "is", "not", "bytes", "xmldoc", "=", "parse", "(", "file_contents", ")", "return", "step", "(", "xmldoc", ")" ]
Performs a step of the transformation. :param text file_contents: Contends of the cheetah template :param function step: Function taking xmldoc and returning new contents :returns: new contents of the file.
[ "Performs", "a", "step", "of", "the", "transformation", "." ]
1ecd54933e63073a7e77d65c8a2514a21e145c34
https://github.com/asottile/cheetah_lint/blob/1ecd54933e63073a7e77d65c8a2514a21e145c34/cheetah_lint/reorder_imports.py#L110-L119
train
35,788
Aloomaio/python-sdk
alooma_pysdk/alooma_pysdk.py
_get_sender
def _get_sender(*sender_params, **kwargs): """ Utility function acting as a Sender factory - ensures senders don't get created twice of more for the same target server """ notify_func = kwargs['notify_func'] with _sender_instances_lock: existing_sender = _sender_instances.get(sender_params, None) if existing_sender: sender = existing_sender sender._notify = notify_func else: sender = _Sender(*sender_params, notify=notify_func) _sender_instances[sender_params] = sender return sender
python
def _get_sender(*sender_params, **kwargs): """ Utility function acting as a Sender factory - ensures senders don't get created twice of more for the same target server """ notify_func = kwargs['notify_func'] with _sender_instances_lock: existing_sender = _sender_instances.get(sender_params, None) if existing_sender: sender = existing_sender sender._notify = notify_func else: sender = _Sender(*sender_params, notify=notify_func) _sender_instances[sender_params] = sender return sender
[ "def", "_get_sender", "(", "*", "sender_params", ",", "*", "*", "kwargs", ")", ":", "notify_func", "=", "kwargs", "[", "'notify_func'", "]", "with", "_sender_instances_lock", ":", "existing_sender", "=", "_sender_instances", ".", "get", "(", "sender_params", ","...
Utility function acting as a Sender factory - ensures senders don't get created twice of more for the same target server
[ "Utility", "function", "acting", "as", "a", "Sender", "factory", "-", "ensures", "senders", "don", "t", "get", "created", "twice", "of", "more", "for", "the", "same", "target", "server" ]
e6e7322d0b23d90b1ff0320e9a9c431c82c0c277
https://github.com/Aloomaio/python-sdk/blob/e6e7322d0b23d90b1ff0320e9a9c431c82c0c277/alooma_pysdk/alooma_pysdk.py#L642-L656
train
35,789
Aloomaio/python-sdk
alooma_pysdk/alooma_pysdk.py
terminate
def terminate(): """ Stops all the active Senders by flushing the buffers and closing the underlying sockets """ with _sender_instances_lock: for sender_key, sender in _sender_instances.items(): sender.close() _sender_instances.clear()
python
def terminate(): """ Stops all the active Senders by flushing the buffers and closing the underlying sockets """ with _sender_instances_lock: for sender_key, sender in _sender_instances.items(): sender.close() _sender_instances.clear()
[ "def", "terminate", "(", ")", ":", "with", "_sender_instances_lock", ":", "for", "sender_key", ",", "sender", "in", "_sender_instances", ".", "items", "(", ")", ":", "sender", ".", "close", "(", ")", "_sender_instances", ".", "clear", "(", ")" ]
Stops all the active Senders by flushing the buffers and closing the underlying sockets
[ "Stops", "all", "the", "active", "Senders", "by", "flushing", "the", "buffers", "and", "closing", "the", "underlying", "sockets" ]
e6e7322d0b23d90b1ff0320e9a9c431c82c0c277
https://github.com/Aloomaio/python-sdk/blob/e6e7322d0b23d90b1ff0320e9a9c431c82c0c277/alooma_pysdk/alooma_pysdk.py#L659-L667
train
35,790
Aloomaio/python-sdk
alooma_pysdk/alooma_pysdk.py
_Sender._send_batch
def _send_batch(self, batch): """ Sends a batch to the destination server via HTTP REST API """ try: json_batch = '[' + ','.join(batch) + ']' # Make JSON array string logger.debug(consts.LOG_MSG_SENDING_BATCH, len(batch), len(json_batch), self._rest_url) res = self._session.post(self._rest_url, data=json_batch, headers=consts.CONTENT_TYPE_JSON) logger.debug(consts.LOG_MSG_BATCH_SENT_RESULT, res.status_code, res.content) if res.status_code == 400: self._notify(logging.CRITICAL, consts.LOG_MSG_BAD_TOKEN) raise exceptions.BadToken(consts.LOG_MSG_BAD_TOKEN) elif not res.ok: raise exceptions.SendFailed("Got bad response code - %s: %s" % ( res.status_code, res.content if res.content else 'No info')) except broken_pipe_errors as ex: self._is_connected.clear() raise exceptions.BatchTooBig(consts.LOG_MSG_BATCH_TOO_BIG % str(ex)) except requests.exceptions.RequestException as ex: raise exceptions.SendFailed(str(ex))
python
def _send_batch(self, batch): """ Sends a batch to the destination server via HTTP REST API """ try: json_batch = '[' + ','.join(batch) + ']' # Make JSON array string logger.debug(consts.LOG_MSG_SENDING_BATCH, len(batch), len(json_batch), self._rest_url) res = self._session.post(self._rest_url, data=json_batch, headers=consts.CONTENT_TYPE_JSON) logger.debug(consts.LOG_MSG_BATCH_SENT_RESULT, res.status_code, res.content) if res.status_code == 400: self._notify(logging.CRITICAL, consts.LOG_MSG_BAD_TOKEN) raise exceptions.BadToken(consts.LOG_MSG_BAD_TOKEN) elif not res.ok: raise exceptions.SendFailed("Got bad response code - %s: %s" % ( res.status_code, res.content if res.content else 'No info')) except broken_pipe_errors as ex: self._is_connected.clear() raise exceptions.BatchTooBig(consts.LOG_MSG_BATCH_TOO_BIG % str(ex)) except requests.exceptions.RequestException as ex: raise exceptions.SendFailed(str(ex))
[ "def", "_send_batch", "(", "self", ",", "batch", ")", ":", "try", ":", "json_batch", "=", "'['", "+", "','", ".", "join", "(", "batch", ")", "+", "']'", "# Make JSON array string", "logger", ".", "debug", "(", "consts", ".", "LOG_MSG_SENDING_BATCH", ",", ...
Sends a batch to the destination server via HTTP REST API
[ "Sends", "a", "batch", "to", "the", "destination", "server", "via", "HTTP", "REST", "API" ]
e6e7322d0b23d90b1ff0320e9a9c431c82c0c277
https://github.com/Aloomaio/python-sdk/blob/e6e7322d0b23d90b1ff0320e9a9c431c82c0c277/alooma_pysdk/alooma_pysdk.py#L457-L479
train
35,791
Aloomaio/python-sdk
alooma_pysdk/alooma_pysdk.py
_Sender.__get_event
def __get_event(self, block=True, timeout=1): """ Retrieves an event. If self._exceeding_event is not None, it'll be returned. Otherwise, an event is dequeued from the event buffer. If The event which was retrieved is bigger than the permitted batch size, it'll be omitted, and the next event in the event buffer is returned """ while True: if self._exceeding_event: # An event was omitted from last batch event = self._exceeding_event self._exceeding_event = None else: # No omitted event, get an event from the queue event = self._event_queue.get(block, timeout) event_size = len(event) # If the event is bigger than the permitted batch size, ignore it # The ( - 2 ) accounts for the parentheses enclosing the batch if event_size - 2 >= self._batch_max_size: self._notify(logging.WARNING, consts.LOG_MSG_OMITTED_OVERSIZED_EVENT % event_size) else: # Event is of valid size, return it return event
python
def __get_event(self, block=True, timeout=1): """ Retrieves an event. If self._exceeding_event is not None, it'll be returned. Otherwise, an event is dequeued from the event buffer. If The event which was retrieved is bigger than the permitted batch size, it'll be omitted, and the next event in the event buffer is returned """ while True: if self._exceeding_event: # An event was omitted from last batch event = self._exceeding_event self._exceeding_event = None else: # No omitted event, get an event from the queue event = self._event_queue.get(block, timeout) event_size = len(event) # If the event is bigger than the permitted batch size, ignore it # The ( - 2 ) accounts for the parentheses enclosing the batch if event_size - 2 >= self._batch_max_size: self._notify(logging.WARNING, consts.LOG_MSG_OMITTED_OVERSIZED_EVENT % event_size) else: # Event is of valid size, return it return event
[ "def", "__get_event", "(", "self", ",", "block", "=", "True", ",", "timeout", "=", "1", ")", ":", "while", "True", ":", "if", "self", ".", "_exceeding_event", ":", "# An event was omitted from last batch", "event", "=", "self", ".", "_exceeding_event", "self",...
Retrieves an event. If self._exceeding_event is not None, it'll be returned. Otherwise, an event is dequeued from the event buffer. If The event which was retrieved is bigger than the permitted batch size, it'll be omitted, and the next event in the event buffer is returned
[ "Retrieves", "an", "event", ".", "If", "self", ".", "_exceeding_event", "is", "not", "None", "it", "ll", "be", "returned", ".", "Otherwise", "an", "event", "is", "dequeued", "from", "the", "event", "buffer", ".", "If", "The", "event", "which", "was", "re...
e6e7322d0b23d90b1ff0320e9a9c431c82c0c277
https://github.com/Aloomaio/python-sdk/blob/e6e7322d0b23d90b1ff0320e9a9c431c82c0c277/alooma_pysdk/alooma_pysdk.py#L591-L614
train
35,792
limdauto/drf_openapi
drf_openapi/entities.py
OpenApiSchemaGenerator.get_links
def get_links(self, request=None): """ Return a dictionary containing all the links that should be included in the API schema. """ links = LinkNode() # Generate (path, method, view) given (path, method, callback). paths = [] view_endpoints = [] for path, method, callback in self.endpoints: view = self.create_view(callback, method, request) if getattr(view, 'exclude_from_schema', False): continue path = self.coerce_path(path, method, view) paths.append(path) view_endpoints.append((path, method, view)) # Only generate the path prefix for paths that will be included if not paths: return None prefix = self.determine_path_prefix(paths) for path, method, view in view_endpoints: if not self.has_view_permissions(path, method, view): continue link = self.get_link(path, method, view, version=getattr(request, 'version', None)) subpath = path[len(prefix):] keys = self.get_keys(subpath, method, view) try: insert_into(links, keys, link) except Exception: continue return links
python
def get_links(self, request=None): """ Return a dictionary containing all the links that should be included in the API schema. """ links = LinkNode() # Generate (path, method, view) given (path, method, callback). paths = [] view_endpoints = [] for path, method, callback in self.endpoints: view = self.create_view(callback, method, request) if getattr(view, 'exclude_from_schema', False): continue path = self.coerce_path(path, method, view) paths.append(path) view_endpoints.append((path, method, view)) # Only generate the path prefix for paths that will be included if not paths: return None prefix = self.determine_path_prefix(paths) for path, method, view in view_endpoints: if not self.has_view_permissions(path, method, view): continue link = self.get_link(path, method, view, version=getattr(request, 'version', None)) subpath = path[len(prefix):] keys = self.get_keys(subpath, method, view) try: insert_into(links, keys, link) except Exception: continue return links
[ "def", "get_links", "(", "self", ",", "request", "=", "None", ")", ":", "links", "=", "LinkNode", "(", ")", "# Generate (path, method, view) given (path, method, callback).", "paths", "=", "[", "]", "view_endpoints", "=", "[", "]", "for", "path", ",", "method", ...
Return a dictionary containing all the links that should be included in the API schema.
[ "Return", "a", "dictionary", "containing", "all", "the", "links", "that", "should", "be", "included", "in", "the", "API", "schema", "." ]
1673c6e039eec7f089336a83bdc31613f32f7e21
https://github.com/limdauto/drf_openapi/blob/1673c6e039eec7f089336a83bdc31613f32f7e21/drf_openapi/entities.py#L111-L144
train
35,793
limdauto/drf_openapi
drf_openapi/entities.py
OpenApiSchemaGenerator.get_path_fields
def get_path_fields(self, path, method, view): """ Return a list of `coreapi.Field` instances corresponding to any templated path variables. """ model = getattr(getattr(view, 'queryset', None), 'model', None) fields = [] for variable in uritemplate.variables(path): if variable == 'version': continue title = '' description = '' schema_cls = coreschema.String kwargs = {} if model is not None: # Attempt to infer a field description if possible. try: model_field = model._meta.get_field(variable) except: model_field = None if model_field is not None and model_field.verbose_name: title = force_text(model_field.verbose_name) if model_field is not None and model_field.help_text: description = force_text(model_field.help_text) elif model_field is not None and model_field.primary_key: description = get_pk_description(model, model_field) if hasattr(view, 'lookup_value_regex') and view.lookup_field == variable: kwargs['pattern'] = view.lookup_value_regex elif isinstance(model_field, models.AutoField): schema_cls = coreschema.Integer field = Field( name=variable, location='path', required=True, schema=schema_cls(title=title, description=description, **kwargs) ) fields.append(field) return fields
python
def get_path_fields(self, path, method, view): """ Return a list of `coreapi.Field` instances corresponding to any templated path variables. """ model = getattr(getattr(view, 'queryset', None), 'model', None) fields = [] for variable in uritemplate.variables(path): if variable == 'version': continue title = '' description = '' schema_cls = coreschema.String kwargs = {} if model is not None: # Attempt to infer a field description if possible. try: model_field = model._meta.get_field(variable) except: model_field = None if model_field is not None and model_field.verbose_name: title = force_text(model_field.verbose_name) if model_field is not None and model_field.help_text: description = force_text(model_field.help_text) elif model_field is not None and model_field.primary_key: description = get_pk_description(model, model_field) if hasattr(view, 'lookup_value_regex') and view.lookup_field == variable: kwargs['pattern'] = view.lookup_value_regex elif isinstance(model_field, models.AutoField): schema_cls = coreschema.Integer field = Field( name=variable, location='path', required=True, schema=schema_cls(title=title, description=description, **kwargs) ) fields.append(field) return fields
[ "def", "get_path_fields", "(", "self", ",", "path", ",", "method", ",", "view", ")", ":", "model", "=", "getattr", "(", "getattr", "(", "view", ",", "'queryset'", ",", "None", ")", ",", "'model'", ",", "None", ")", "fields", "=", "[", "]", "for", "...
Return a list of `coreapi.Field` instances corresponding to any templated path variables.
[ "Return", "a", "list", "of", "coreapi", ".", "Field", "instances", "corresponding", "to", "any", "templated", "path", "variables", "." ]
1673c6e039eec7f089336a83bdc31613f32f7e21
https://github.com/limdauto/drf_openapi/blob/1673c6e039eec7f089336a83bdc31613f32f7e21/drf_openapi/entities.py#L231-L276
train
35,794
limdauto/drf_openapi
drf_openapi/entities.py
OpenApiSchemaGenerator.get_serializer_class
def get_serializer_class(self, view, method_func): """ Try to get the serializer class from view method. If view method don't have request serializer, fallback to serializer_class on view class """ if hasattr(method_func, 'request_serializer'): return getattr(method_func, 'request_serializer') if hasattr(view, 'serializer_class'): return getattr(view, 'serializer_class') if hasattr(view, 'get_serializer_class'): return getattr(view, 'get_serializer_class')() return None
python
def get_serializer_class(self, view, method_func): """ Try to get the serializer class from view method. If view method don't have request serializer, fallback to serializer_class on view class """ if hasattr(method_func, 'request_serializer'): return getattr(method_func, 'request_serializer') if hasattr(view, 'serializer_class'): return getattr(view, 'serializer_class') if hasattr(view, 'get_serializer_class'): return getattr(view, 'get_serializer_class')() return None
[ "def", "get_serializer_class", "(", "self", ",", "view", ",", "method_func", ")", ":", "if", "hasattr", "(", "method_func", ",", "'request_serializer'", ")", ":", "return", "getattr", "(", "method_func", ",", "'request_serializer'", ")", "if", "hasattr", "(", ...
Try to get the serializer class from view method. If view method don't have request serializer, fallback to serializer_class on view class
[ "Try", "to", "get", "the", "serializer", "class", "from", "view", "method", ".", "If", "view", "method", "don", "t", "have", "request", "serializer", "fallback", "to", "serializer_class", "on", "view", "class" ]
1673c6e039eec7f089336a83bdc31613f32f7e21
https://github.com/limdauto/drf_openapi/blob/1673c6e039eec7f089336a83bdc31613f32f7e21/drf_openapi/entities.py#L278-L292
train
35,795
limdauto/drf_openapi
drf_openapi/entities.py
OpenApiSchemaGenerator.fallback_schema_from_field
def fallback_schema_from_field(self, field): """ Fallback schema for field that isn't inspected properly by DRF and probably won't land in upstream canon due to its hacky nature only for doc purposes """ title = force_text(field.label) if field.label else '' description = force_text(field.help_text) if field.help_text else '' # since we can't really inspect dictfield and jsonfield, at least display object as type # instead of string if isinstance(field, (serializers.DictField, serializers.JSONField)): return coreschema.Object( properties={}, title=title, description=description )
python
def fallback_schema_from_field(self, field): """ Fallback schema for field that isn't inspected properly by DRF and probably won't land in upstream canon due to its hacky nature only for doc purposes """ title = force_text(field.label) if field.label else '' description = force_text(field.help_text) if field.help_text else '' # since we can't really inspect dictfield and jsonfield, at least display object as type # instead of string if isinstance(field, (serializers.DictField, serializers.JSONField)): return coreschema.Object( properties={}, title=title, description=description )
[ "def", "fallback_schema_from_field", "(", "self", ",", "field", ")", ":", "title", "=", "force_text", "(", "field", ".", "label", ")", "if", "field", ".", "label", "else", "''", "description", "=", "force_text", "(", "field", ".", "help_text", ")", "if", ...
Fallback schema for field that isn't inspected properly by DRF and probably won't land in upstream canon due to its hacky nature only for doc purposes
[ "Fallback", "schema", "for", "field", "that", "isn", "t", "inspected", "properly", "by", "DRF", "and", "probably", "won", "t", "land", "in", "upstream", "canon", "due", "to", "its", "hacky", "nature", "only", "for", "doc", "purposes" ]
1673c6e039eec7f089336a83bdc31613f32f7e21
https://github.com/limdauto/drf_openapi/blob/1673c6e039eec7f089336a83bdc31613f32f7e21/drf_openapi/entities.py#L294-L308
train
35,796
limdauto/drf_openapi
examples/snippets/serializers.py
SnippetSerializerV1.update
def update(self, instance, validated_data): """ Update and return an existing `Snippet` instance, given the validated data. """ instance.title = validated_data.get('title', instance.title) instance.code = validated_data.get('code', instance.code) instance.linenos = validated_data.get('linenos', instance.linenos) instance.language = validated_data.get('language', instance.language) instance.style = validated_data.get('style', instance.style) instance.save() return instance
python
def update(self, instance, validated_data): """ Update and return an existing `Snippet` instance, given the validated data. """ instance.title = validated_data.get('title', instance.title) instance.code = validated_data.get('code', instance.code) instance.linenos = validated_data.get('linenos', instance.linenos) instance.language = validated_data.get('language', instance.language) instance.style = validated_data.get('style', instance.style) instance.save() return instance
[ "def", "update", "(", "self", ",", "instance", ",", "validated_data", ")", ":", "instance", ".", "title", "=", "validated_data", ".", "get", "(", "'title'", ",", "instance", ".", "title", ")", "instance", ".", "code", "=", "validated_data", ".", "get", "...
Update and return an existing `Snippet` instance, given the validated data.
[ "Update", "and", "return", "an", "existing", "Snippet", "instance", "given", "the", "validated", "data", "." ]
1673c6e039eec7f089336a83bdc31613f32f7e21
https://github.com/limdauto/drf_openapi/blob/1673c6e039eec7f089336a83bdc31613f32f7e21/examples/snippets/serializers.py#L39-L49
train
35,797
limdauto/drf_openapi
drf_openapi/codec.py
_generate_openapi_object
def _generate_openapi_object(document): """ Generates root of the Swagger spec. """ parsed_url = urlparse.urlparse(document.url) swagger = OrderedDict() swagger['swagger'] = '2.0' swagger['info'] = OrderedDict() swagger['info']['title'] = document.title swagger['info']['description'] = document.description swagger['info']['version'] = document.version if parsed_url.netloc: swagger['host'] = parsed_url.netloc if parsed_url.scheme: swagger['schemes'] = [parsed_url.scheme] swagger['paths'] = _get_paths_object(document) return swagger
python
def _generate_openapi_object(document): """ Generates root of the Swagger spec. """ parsed_url = urlparse.urlparse(document.url) swagger = OrderedDict() swagger['swagger'] = '2.0' swagger['info'] = OrderedDict() swagger['info']['title'] = document.title swagger['info']['description'] = document.description swagger['info']['version'] = document.version if parsed_url.netloc: swagger['host'] = parsed_url.netloc if parsed_url.scheme: swagger['schemes'] = [parsed_url.scheme] swagger['paths'] = _get_paths_object(document) return swagger
[ "def", "_generate_openapi_object", "(", "document", ")", ":", "parsed_url", "=", "urlparse", ".", "urlparse", "(", "document", ".", "url", ")", "swagger", "=", "OrderedDict", "(", ")", "swagger", "[", "'swagger'", "]", "=", "'2.0'", "swagger", "[", "'info'",...
Generates root of the Swagger spec.
[ "Generates", "root", "of", "the", "Swagger", "spec", "." ]
1673c6e039eec7f089336a83bdc31613f32f7e21
https://github.com/limdauto/drf_openapi/blob/1673c6e039eec7f089336a83bdc31613f32f7e21/drf_openapi/codec.py#L120-L141
train
35,798
limdauto/drf_openapi
drf_openapi/codec.py
_get_responses
def _get_responses(link): """ Returns an OpenApi-compliant response """ template = link.response_schema template.update({'description': 'Success'}) res = {200: template} res.update(link.error_status_codes) return res
python
def _get_responses(link): """ Returns an OpenApi-compliant response """ template = link.response_schema template.update({'description': 'Success'}) res = {200: template} res.update(link.error_status_codes) return res
[ "def", "_get_responses", "(", "link", ")", ":", "template", "=", "link", ".", "response_schema", "template", ".", "update", "(", "{", "'description'", ":", "'Success'", "}", ")", "res", "=", "{", "200", ":", "template", "}", "res", ".", "update", "(", ...
Returns an OpenApi-compliant response
[ "Returns", "an", "OpenApi", "-", "compliant", "response" ]
1673c6e039eec7f089336a83bdc31613f32f7e21
https://github.com/limdauto/drf_openapi/blob/1673c6e039eec7f089336a83bdc31613f32f7e21/drf_openapi/codec.py#L183-L190
train
35,799