text_prompt
stringlengths 157
13.1k
| code_prompt
stringlengths 7
19.8k
⌀ |
---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def addPSF(self, psf, date=None, info='', light_spectrum='visible'):
'''
add a new point spread function
'''
self._registerLight(light_spectrum)
date = _toDate(date)
f = self.coeffs['psf']
if light_spectrum not in f:
f[light_spectrum] = []
f[light_spectrum].insert(_insertDateIndex(date, f[light_spectrum]),
[date, info, psf]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def addFlatField(self, arr, date=None, info='', error=None,
light_spectrum='visible'):
'''
light_spectrum = light, IR ...
'''
self._registerLight(light_spectrum)
self._checkShape(arr)
date = _toDate(date)
f = self.coeffs['flat field']
if light_spectrum not in f:
f[light_spectrum] = []
f[light_spectrum].insert(_insertDateIndex(date, f[light_spectrum]),
[date, info, arr, error]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def addLens(self, lens, date=None, info='', light_spectrum='visible'):
'''
lens -> instance of LensDistortion or saved file
'''
self._registerLight(light_spectrum)
date = _toDate(date)
if not isinstance(lens, LensDistortion):
l = LensDistortion()
l.readFromFile(lens)
lens = l
f = self.coeffs['lens']
if light_spectrum not in f:
f[light_spectrum] = []
f[light_spectrum].insert(_insertDateIndex(date, f[light_spectrum]),
[date, info, lens.coeffs]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def clearOldCalibrations(self, date=None):
'''
if not only a specific date than remove all except of the youngest calibration
'''
self.coeffs['dark current'] = [self.coeffs['dark current'][-1]]
self.coeffs['noise'] = [self.coeffs['noise'][-1]]
for light in self.coeffs['flat field']:
self.coeffs['flat field'][light] = [
self.coeffs['flat field'][light][-1]]
for light in self.coeffs['lens']:
self.coeffs['lens'][light] = [self.coeffs['lens'][light][-1]] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _correctNoise(self, image):
'''
denoise using non-local-means
with guessing best parameters
'''
from skimage.restoration import denoise_nl_means # save startup time
image[np.isnan(image)] = 0 # otherwise result =nan
out = denoise_nl_means(image,
patch_size=7,
patch_distance=11,
#h=signalStd(image) * 0.1
)
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _correctArtefacts(self, image, threshold):
'''
Apply a thresholded median replacing high gradients
and values beyond the boundaries
'''
image = np.nan_to_num(image)
medianThreshold(image, threshold, copy=False)
return image |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getCoeff(self, name, light=None, date=None):
'''
try to get calibration for right light source, but
use another if they is none existent
'''
d = self.coeffs[name]
try:
c = d[light]
except KeyError:
try:
k, i = next(iter(d.items()))
if light is not None:
print(
'no calibration found for [%s] - using [%s] instead' % (light, k))
except StopIteration:
return None
c = i
except TypeError:
# coeff not dependent on light source
c = d
return _getFromDate(c, date) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def error(self, nCells=15):
'''
calculate the standard deviation of all fitted images,
averaged to a grid
'''
s0, s1 = self.fits[0].shape
aR = s0 / s1
if aR > 1:
ss0 = int(nCells)
ss1 = int(ss0 / aR)
else:
ss1 = int(nCells)
ss0 = int(ss1 * aR)
L = len(self.fits)
arr = np.array(self.fits)
arr[np.array(self._fit_masks)] = np.nan
avg = np.tile(np.nanmean(arr, axis=0), (L, 1, 1))
arr = (arr - avg) / avg
out = np.empty(shape=(L, ss0, ss1))
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
for n, f in enumerate(arr):
out[n] = subCell2DFnArray(f, np.nanmean, (ss0, ss1))
return np.nanmean(out**2)**0.5 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _fitImg(self, img):
'''
fit perspective and size of the input image to the reference image
'''
img = imread(img, 'gray')
if self.bg is not None:
img = cv2.subtract(img, self.bg)
if self.lens is not None:
img = self.lens.correct(img, keepSize=True)
(H, _, _, _, _, _, _, n_matches) = self.findHomography(img)
H_inv = self.invertHomography(H)
s = self.obj_shape
fit = cv2.warpPerspective(img, H_inv, (s[1], s[0]))
return fit, img, H, H_inv, n_matches |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _findObject(self, img):
'''
Create a bounding box around the object within an image
'''
from imgProcessor.imgSignal import signalMinimum
# img is scaled already
i = img > signalMinimum(img) # img.max()/2.5
# filter noise, single-time-effects etc. from mask:
i = minimum_filter(i, 4)
return boundingBox(i) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filterVerticalLines(arr, min_line_length=4):
"""
Remove vertical lines in boolean array if linelength >=min_line_length
""" |
gy = arr.shape[0]
gx = arr.shape[1]
mn = min_line_length-1
for i in range(gy):
for j in range(gx):
if arr[i,j]:
for d in range(min_line_length):
if not arr[i+d,j]:
break
if d == mn:
d = 0
while True:
if not arr[i+d,j]:
break
arr[i+d,j] = 0
d +=1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def imgAverage(images, copy=True):
'''
returns an image average
works on many, also unloaded images
minimises RAM usage
'''
i0 = images[0]
out = imread(i0, dtype='float')
if copy and id(i0) == id(out):
out = out.copy()
for i in images[1:]:
out += imread(i, dtype='float')
out /= len(images)
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def poisson(x, a, b, c, d=0):
'''
Poisson function
a -> height of the curve's peak
b -> position of the center of the peak
c -> standard deviation
d -> offset
'''
from scipy.misc import factorial #save startup time
lamb = 1
X = (x/(2*c)).astype(int)
return a * (( lamb**X/factorial(X)) * np.exp(-lamb) ) +d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def gaussian(x, a, b, c, d=0):
'''
a -> height of the curve's peak
b -> position of the center of the peak
c -> standard deviation or Gaussian RMS width
d -> offset
'''
return a * np.exp( -(((x-b)**2 )/ (2*(c**2))) ) + d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def imread(img, color=None, dtype=None):
'''
dtype = 'noUint', uint8, float, 'float', ...
'''
COLOR2CV = {'gray': cv2.IMREAD_GRAYSCALE,
'all': cv2.IMREAD_COLOR,
None: cv2.IMREAD_ANYCOLOR
}
c = COLOR2CV[color]
if callable(img):
img = img()
elif isinstance(img, string_types):
# from_file = True
# try:
# ftype = img[img.find('.'):]
# img = READERS[ftype](img)[0]
# except KeyError:
# open with openCV
# grey - 8 bit
if dtype in (None, "noUint") or np.dtype(dtype) != np.uint8:
c |= cv2.IMREAD_ANYDEPTH
img2 = cv2.imread(img, c)
if img2 is None:
raise IOError("image '%s' is not existing" % img)
img = img2
elif color == 'gray' and img.ndim == 3: # multi channel img like rgb
# cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #cannot handle float64
img = toGray(img)
# transform array to uint8 array due to openCV restriction
if dtype is not None:
if isinstance(img, np.ndarray):
img = _changeArrayDType(img, dtype, cutHigh=False)
return img |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def linearBlend(img1, img2, overlap, backgroundColor=None):
'''
Stitch 2 images vertically together.
Smooth the overlap area of both images with a linear fade from img1 to img2
@param img1: numpy.2dArray
@param img2: numpy.2dArray of the same shape[1,2] as img1
@param overlap: number of pixels both images overlap
@returns: stitched-image
'''
(sizex, sizey) = img1.shape[:2]
overlapping = True
if overlap < 0:
overlapping = False
overlap = -overlap
# linear transparency change:
alpha = np.tile(np.expand_dims(np.linspace(1, 0, overlap), 1), sizey)
if len(img2.shape) == 3: # multi channel img like rgb
# make alpha 3d with n channels
alpha = np.dstack(([alpha for _ in range(img2.shape[2])]))
if overlapping:
img1_cut = img1[sizex - overlap:sizex, :]
img2_cut = img2[0:overlap, :]
else:
# take average of last 5 rows:
img1_cut = np.tile(img1[-min(sizex, 5):, :].mean(
axis=0), (overlap, 1)).reshape(alpha.shape)
img2_cut = np.tile(img2[:min(img2.shape[0], 5), :].mean(
axis=0), (overlap, 1)).reshape(alpha.shape)
# fill intermediate area as mixture of both images
#################bg transparent############
inter = (img1_cut * alpha + img2_cut * (1 - alpha)).astype(img1.dtype)
# set background areas to value of respective other img:
if backgroundColor is not None:
mask = np.logical_and(img1_cut == backgroundColor,
img2_cut != backgroundColor)
inter[mask] = img2_cut[mask]
mask = np.logical_and(img2_cut == backgroundColor,
img1_cut != backgroundColor)
inter[mask] = img1_cut[mask]
if not overlapping:
overlap = 0
return np.vstack((img1[0:sizex - overlap, :],
inter,
img2[overlap:, :])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def maskedConvolve(arr, kernel, mask, mode='reflect'):
'''
same as scipy.ndimage.convolve but is only executed on mask==True
... which should speed up everything
'''
arr2 = extendArrayForConvolution(arr, kernel.shape, modex=mode, modey=mode)
print(arr2.shape)
out = np.zeros_like(arr)
return _calc(arr2, kernel, mask, out) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def closestDirectDistance(arr, ksize=30, dtype=np.uint16):
'''
return an array with contains the closest distance to the next positive
value given in arr within a given kernel size
'''
out = np.zeros_like(arr, dtype=dtype)
_calc(out, arr, ksize)
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def setImgShape(self, shape):
'''
image shape must be known for calculating camera matrix
if method==Manual and addPoints is used instead of addImg
this method must be called before .coeffs are obtained
'''
self.img = type('Dummy', (object,), {})
# if imgProcessor.ARRAYS_ORDER_IS_XY:
# self.img.shape = shape[::-1]
# else:
self.img.shape = shape |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def addImgStream(self, img):
'''
add images using a continous stream
- stop when max number of images is reached
'''
if self.findCount > self.max_images:
raise EnoughImages('have enough images')
return self.addImg(img) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def addImg(self, img):
'''
add one chessboard image for detection lens distortion
'''
# self.opts['imgs'].append(img)
self.img = imread(img, 'gray', 'uint8')
didFindCorners, corners = self.method()
self.opts['foundPattern'].append(didFindCorners)
if didFindCorners:
self.findCount += 1
self.objpoints.append(self.objp)
self.opts['imgPoints'].append(corners)
return didFindCorners |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getCoeffStr(self):
'''
get the distortion coeffs in a formated string
'''
txt = ''
for key, val in self.coeffs.items():
txt += '%s = %s\n' % (key, val)
return txt |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def drawChessboard(self, img=None):
'''
draw a grid fitting to the last added image
on this one or an extra image
img == None
==False -> draw chessbord on empty image
==img
'''
assert self.findCount > 0, 'cannot draw chessboard if nothing found'
if img is None:
img = self.img
elif isinstance(img, bool) and not img:
img = np.zeros(shape=(self.img.shape), dtype=self.img.dtype)
else:
img = imread(img, dtype='uint8')
gray = False
if img.ndim == 2:
gray = True
# need a color 8 bit image
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
# Draw and display the corners
cv2.drawChessboardCorners(img, self.opts['size'],
self.opts['imgPoints'][-1],
self.opts['foundPattern'][-1])
if gray:
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
return img |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def readFromFile(self, filename):
'''
read the distortion coeffs from file
'''
s = dict(np.load(filename))
try:
self.coeffs = s['coeffs'][()]
except KeyError:
#LEGENCY - remove
self.coeffs = s
try:
self.opts = s['opts'][()]
except KeyError:
pass
return self.coeffs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def correct(self, image, keepSize=False, borderValue=0):
'''
remove lens distortion from given image
'''
image = imread(image)
(h, w) = image.shape[:2]
mapx, mapy = self.getUndistortRectifyMap(w, h)
self.img = cv2.remap(image, mapx, mapy, cv2.INTER_LINEAR,
borderMode=cv2.BORDER_CONSTANT,
borderValue=borderValue
)
if not keepSize:
xx, yy, ww, hh = self.roi
self.img = self.img[yy: yy + hh, xx: xx + ww]
return self.img |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def distortImage(self, image):
'''
opposite of 'correct'
'''
image = imread(image)
(imgHeight, imgWidth) = image.shape[:2]
mapx, mapy = self.getDistortRectifyMap(imgWidth, imgHeight)
return cv2.remap(image, mapx, mapy, cv2.INTER_LINEAR,
borderValue=(0, 0, 0)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _scaleTo8bit(self, img):
'''
The pattern comparator need images to be 8 bit
-> find the range of the signal and scale the image
'''
r = scaleSignalCutParams(img, 0.02) # , nSigma=3)
self.signal_ranges.append(r)
return toUIntArray(img, dtype=np.uint8, range=r) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def findHomography(self, img, drawMatches=False):
'''
Find homography of the image through pattern
comparison with the base image
'''
print("\t Finding points...")
# Find points in the next frame
img = self._prepareImage(img)
features, descs = self.detector.detectAndCompute(img, None)
######################
# TODO: CURRENTLY BROKEN IN OPENCV3.1 - WAITNG FOR NEW RELEASE 3.2
# matches = self.matcher.knnMatch(descs,#.astype(np.float32),
# self.base_descs,
# k=3)
# print("\t Match Count: ", len(matches))
# matches_subset = self._filterMatches(matches)
# its working alternative (for now):
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches_subset = bf.match(descs, self.base_descs)
######################
# matches = bf.knnMatch(descs,self.base_descs, k=2)
# # Apply ratio test
# matches_subset = []
# medDist = np.median([m.distance for m in matches])
# matches_subset = [m for m in matches if m.distance < medDist]
# for m in matches:
# print(m.distance)
# for m,n in matches:
# if m.distance < 0.75*n.distance:
# matches_subset.append([m])
if not len(matches_subset):
raise Exception('no matches found')
print("\t Filtered Match Count: ", len(matches_subset))
distance = sum([m.distance for m in matches_subset])
print("\t Distance from Key Image: ", distance)
averagePointDistance = distance / (len(matches_subset))
print("\t Average Distance: ", averagePointDistance)
kp1 = []
kp2 = []
for match in matches_subset:
kp1.append(self.base_features[match.trainIdx])
kp2.append(features[match.queryIdx])
# /self._fH #scale with _fH, if image was resized
p1 = np.array([k.pt for k in kp1])
p2 = np.array([k.pt for k in kp2]) # /self._fH
H, status = cv2.findHomography(p1, p2,
cv2.RANSAC, # method
5.0 # max reprojection error (1...10)
)
if status is None:
raise Exception('no homography found')
else:
inliers = np.sum(status)
print('%d / %d inliers/matched' % (inliers, len(status)))
inlierRatio = inliers / len(status)
if self.minInlierRatio > inlierRatio or inliers < self.minInliers:
raise Exception('bad fit!')
# scale with _fH, if image was resized
# see
# http://answers.opencv.org/question/26173/the-relationship-between-homography-matrix-and-scaling-images/
s = np.eye(3, 3)
s[0, 0] = 1 / self._fH
s[1, 1] = 1 / self._fH
H = s.dot(H).dot(np.linalg.inv(s))
if drawMatches:
# s0,s1 = img.shape
# out = np.empty(shape=(s0,s1,3), dtype=np.uint8)
img = draw_matches(self.base8bit, self.base_features, img, features,
matches_subset[:20], # None,#out,
# flags=2
thickness=5
)
return (H, inliers, inlierRatio, averagePointDistance,
img, features,
descs, len(matches_subset)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def patCircles(s0):
'''make circle array'''
arr = np.zeros((s0,s0), dtype=np.uint8)
col = 255
for rad in np.linspace(s0,s0/7.,10):
cv2.circle(arr, (0,0), int(round(rad)), color=col,
thickness=-1, lineType=cv2.LINE_AA )
if col:
col = 0
else:
col = 255
return arr.astype(float) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def patText(s0):
'''make text pattern'''
arr = np.zeros((s0,s0), dtype=np.uint8)
s = int(round(s0/100.))
p1 = 0
pp1 = int(round(s0/10.))
for pos0 in np.linspace(0,s0,10):
cv2.putText(arr, 'helloworld', (p1,int(round(pos0))),
cv2.FONT_HERSHEY_COMPLEX_SMALL, fontScale=s,
color=255, thickness=s,
lineType=cv2.LINE_AA )
if p1:
p1 = 0
else:
p1 = pp1
return arr.astype(float) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def removeSinglePixels(img):
'''
img - boolean array
remove all pixels that have no neighbour
'''
gx = img.shape[0]
gy = img.shape[1]
for i in range(gx):
for j in range(gy):
if img[i, j]:
found_neighbour = False
for ii in range(max(0, i - 1), min(gx, i + 2)):
for jj in range(max(0, j - 1), min(gy, j + 2)):
if ii == i and jj == j:
continue
if img[ii, jj]:
found_neighbour = True
break
if found_neighbour:
break
if not found_neighbour:
img[i, j] = 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def numbaGaussian2d(psf, sy, sx):
'''
2d Gaussian to be used in numba code
'''
ps0, ps1 = psf.shape
c0,c1 = ps0//2, ps1//2
ssx = 2*sx**2
ssy = 2*sy**2
for i in range(ps0):
for j in range(ps1):
psf[i,j]=exp( -( (i-c0)**2/ssy
+(j-c1)**2/ssx) )
psf/=psf.sum() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def estimateBackgroundLevel(img, image_is_artefact_free=False,
min_rel_size=0.05, max_abs_size=11):
'''
estimate background level through finding the most homogeneous area
and take its average
min_size - relative size of the examined area
'''
s0,s1 = img.shape[:2]
s = min(max_abs_size, int(max(s0,s1)*min_rel_size))
arr = np.zeros(shape=(s0-2*s, s1-2*s), dtype=img.dtype)
#fill arr:
_spatialStd(img, arr, s)
#most homogeneous area:
i,j = np.unravel_index(arr.argmin(), arr.shape)
sub = img[int(i+0.5*s):int(i+s*1.5),
int(j+s*0.5):int(j+s*1.5)]
return np.median(sub) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def shiftImage(u, v, t, img, interpolation=cv2.INTER_LANCZOS4):
'''
remap an image using velocity field
'''
ny,nx = u.shape
sy, sx = np.mgrid[:float(ny):1,:float(nx):1]
sx += u*t
sy += v*t
return cv2.remap(img.astype(np.float32),
(sx).astype(np.float32),
(sy).astype(np.float32), interpolation) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def stdDev(self):
'''
get the standard deviation
from the PSF is evaluated as 2d Gaussian
'''
if self._corrPsf is None:
self.psf()
p = self._corrPsf.copy()
mn = p.min()
p[p<0.05*p.max()] = mn
p-=mn
p/=p.sum()
x,y = self._psfGridCoords()
x = x.flatten()
y = y.flatten()
guess = (1,1,0)
param, _ = curve_fit(self._fn, (x,y), p.flatten(), guess)
self._fitParam = param
stdx,stdy = param[:2]
self._std = (stdx+stdy) / 2
return self._std |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def calcAspectRatioFromCorners(corners, in_plane=False):
'''
simple and better alg. than below
in_plane -> whether object has no tilt, but only rotation and translation
'''
q = corners
l0 = [q[0, 0], q[0, 1], q[1, 0], q[1, 1]]
l1 = [q[0, 0], q[0, 1], q[-1, 0], q[-1, 1]]
l2 = [q[2, 0], q[2, 1], q[3, 0], q[3, 1]]
l3 = [q[2, 0], q[2, 1], q[1, 0], q[1, 1]]
a1 = line.length(l0) / line.length(l1)
a2 = line.length(l2) / line.length(l3)
if in_plane:
# take aspect ration from more rectangular corner
if (abs(0.5 * np.pi - abs(line.angle2(l0, l1)))
< abs(0.5 * np.pi - abs(line.angle2(l2, l3)))):
return a1
else:
return a2
return 0.5 * (a1 + a2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def fastMean(img, f=10, inplace=False):
'''
for bigger ksizes it if often faster to resize an image
rather than blur it...
'''
s0,s1 = img.shape[:2]
ss0 = int(round(s0/f))
ss1 = int(round(s1/f))
small = cv2.resize(img,(ss1,ss0), interpolation=cv2.INTER_AREA)
#bigger
k = {'interpolation':cv2.INTER_LINEAR}
if inplace:
k['dst']=img
return cv2.resize(small,(s1,s0), **k) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def averageSameExpTimes(imgs_path):
'''
average background images with same exposure time
'''
firsts = imgs_path[:2]
imgs = imgs_path[2:]
for n, i in enumerate(firsts):
firsts[n] = np.asfarray(imread(i))
d = DarkCurrentMap(firsts)
for i in imgs:
i = imread(i)
d.addImg(i)
return d.map() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def sortForSameExpTime(expTimes, img_paths): # , excludeSingleImg=True):
'''
return image paths sorted for same exposure time
'''
d = {}
for e, i in zip(expTimes, img_paths):
if e not in d:
d[e] = []
d[e].append(i)
# for key in list(d.keys()):
# if len(d[key]) == 1:
# print('have only one image of exposure time [%s]' % key)
# print('--> exclude that one')
# d.pop(key)
d = OrderedDict(sorted(d.items()))
return list(d.keys()), list(d.values()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getDarkCurrentAverages(exposuretimes, imgs):
'''
return exposure times, image averages for each exposure time
'''
x, imgs_p = sortForSameExpTime(exposuretimes, imgs)
s0, s1 = imgs[0].shape
imgs = np.empty(shape=(len(x), s0, s1),
dtype=imgs[0].dtype)
for i, ip in zip(imgs, imgs_p):
if len(ip) == 1:
i[:] = ip[0]
else:
i[:] = averageSameExpTimes(ip)
return x, imgs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getDarkCurrentFunction(exposuretimes, imgs, **kwargs):
'''
get dark current function from given images and exposure times
'''
exposuretimes, imgs = getDarkCurrentAverages(exposuretimes, imgs)
offs, ascent, rmse = getLinearityFunction(exposuretimes, imgs, **kwargs)
return offs, ascent, rmse |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def alignImageAlongLine(img, line, height=15, length=None,
zoom=1, fast=False, borderValue=0):
'''
return a sub image aligned along given line
@param img - numpy.2darray input image to get subimage from
@param line - list of 2 points [x0,y0,x1,y1])
@param height - height of output array in y
@param length - width of output array
@param zoom - zoom factor
@param fast - speed up calculation using nearest neighbour interpolation
@returns transformed image as numpy.2darray with found line as in the middle
'''
height = int(round(height))
if height % 2 == 0: # ->is even number
height += 1 # only take uneven numbers to have line in middle
if length is None:
length = int(round(ln.length(line)))
hh = (height - 1)
ll = (length - 1)
# end points of the line:
p0 = np.array(line[0:2], dtype=float)
p1 = np.array(line[2:], dtype=float)
# p2 is above middle of p0,p1:
norm = np.array(ln.normal(line))
if not ln.isHoriz(line):
norm *= -1
p2 = (p0 + p1) * 0.5 + norm * hh * 0.5
middleY = hh / 2
pp0 = [0, middleY]
pp1 = [ll, middleY]
pp2 = [ll * 0.5, hh]
pts1 = np.array([p0, p1, p2], dtype=np.float32)
pts2 = np.array([pp0, pp1, pp2], dtype=np.float32)
if zoom != 1:
length = int(round(length * zoom))
height = int(round(height * zoom))
pts2 *= zoom
# TRANSFORM:
M = cv2.getAffineTransform(pts1, pts2)
dst = cv2.warpAffine(
img, M, (length, height),
flags=cv2.INTER_NEAREST if fast else cv2.INTER_LINEAR,
borderValue=borderValue)
return dst |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def nan_maximum_filter(arr, ksize):
'''
same as scipy.filters.maximum_filter
but working excluding nans
'''
out = np.empty_like(arr)
_calc(arr, out, ksize//2)
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def fitImg(self, img_rgb):
'''
fit perspective and size of the input image to the base image
'''
H = self.pattern.findHomography(img_rgb)[0]
H_inv = self.pattern.invertHomography(H)
s = self.img_orig.shape
warped = cv2.warpPerspective(img_rgb, H_inv, (s[1], s[0]))
return warped |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def scaleSignalCut(img, ratio, nbins=100):
'''
scaling img cutting x percent of top and bottom part of histogram
'''
start, stop = scaleSignalCutParams(img, ratio, nbins)
img = img - start
img /= (stop - start)
return img |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getBackgroundRange(fitParams):
'''
return minimum, average, maximum of the background peak
'''
smn, _, _ = getSignalParameters(fitParams)
bg = fitParams[0]
_, avg, std = bg
bgmn = max(0, avg - 3 * std)
if avg + 4 * std < smn:
bgmx = avg + 4 * std
if avg + 3 * std < smn:
bgmx = avg + 3 * std
if avg + 2 * std < smn:
bgmx = avg + 2 * std
else:
bgmx = avg + std
return bgmn, avg, bgmx |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def hasBackground(fitParams):
'''
compare the height of putative bg and signal peak
if ratio if too height assume there is no background
'''
signal = getSignalPeak(fitParams)
bg = getBackgroundPeak(fitParams)
if signal == bg:
return False
r = signal[0] / bg[0]
if r < 1:
r = 1 / r
return r < 100 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def signalMinimum2(img, bins=None):
'''
minimum position between signal and background peak
'''
f = FitHistogramPeaks(img, bins=bins)
i = signalPeakIndex(f.fitParams)
spos = f.fitParams[i][1]
# spos = getSignalPeak(f.fitParams)[1]
# bpos = getBackgroundPeak(f.fitParams)[1]
bpos = f.fitParams[i - 1][1]
ind = np.logical_and(f.xvals > bpos, f.xvals < spos)
try:
i = np.argmin(f.yvals[ind])
return f.xvals[ind][i]
except ValueError as e:
if bins is None:
return signalMinimum2(img, bins=400)
else:
raise e |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def signalMinimum(img, fitParams=None, n_std=3):
'''
intersection between signal and background peak
'''
if fitParams is None:
fitParams = FitHistogramPeaks(img).fitParams
assert len(fitParams) > 1, 'need 2 peaks so get minimum signal'
i = signalPeakIndex(fitParams)
signal = fitParams[i]
bg = getBackgroundPeak(fitParams)
smn = signal[1] - n_std * signal[2]
bmx = bg[1] + n_std * bg[2]
if smn > bmx:
return smn
# peaks are overlapping
# define signal min. as intersection between both Gaussians
def solve(p1, p2):
s1, m1, std1 = p1
s2, m2, std2 = p2
a = (1 / (2 * std1**2)) - (1 / (2 * std2**2))
b = (m2 / (std2**2)) - (m1 / (std1**2))
c = (m1**2 / (2 * std1**2)) - (m2**2 / (2 * std2**2)) - \
np.log(((std2 * s1) / (std1 * s2)))
return np.roots([a, b, c])
i = solve(bg, signal)
try:
return i[np.logical_and(i > bg[1], i < signal[1])][0]
except IndexError:
# this error shouldn't occur... well
return max(smn, bmx) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getSignalParameters(fitParams, n_std=3):
'''
return minimum, average, maximum of the signal peak
'''
signal = getSignalPeak(fitParams)
mx = signal[1] + n_std * signal[2]
mn = signal[1] - n_std * signal[2]
if mn < fitParams[0][1]:
mn = fitParams[0][1] # set to bg
return mn, signal[1], mx |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def drawQuad(self, img=None, quad=None, thickness=30):
'''
Draw the quad into given img
'''
if img is None:
img = self.img
if quad is None:
quad = self.quad
q = np.int32(quad)
c = int(img.max())
cv2.line(img, tuple(q[0]), tuple(q[1]), c, thickness)
cv2.line(img, tuple(q[1]), tuple(q[2]), c, thickness)
cv2.line(img, tuple(q[2]), tuple(q[3]), c, thickness)
cv2.line(img, tuple(q[3]), tuple(q[0]), c, thickness)
return img |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def flatFieldFromFunction(self):
'''
calculate flatField from fitting vignetting function to averaged fit-image
returns flatField, average background level, fitted image, valid indices mask
'''
fitimg, mask = self._prepare()
mask = ~mask
s0, s1 = fitimg.shape
#f-value, alpha, fx, cx, cy
guess = (s1 * 0.7, 0, 1, s0 / 2, s1 / 2)
# set assume normal plane - no tilt and rotation:
fn = lambda xy, f, alpha, fx, cx, cy: vignetting((xy[0] * fx, xy[1]), f, alpha,
cx=cx, cy=cy)
# mask = fitimg>0.5
flatfield = fit2dArrayToFn(fitimg, fn, mask=mask,
guess=guess, output_shape=self._orig_shape)[0]
return flatfield, self.bglevel / self._n, fitimg, mask |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def flatFieldFromFit(self):
'''
calculate flatField from 2d-polynomal fit filling
all high gradient areas within averaged fit-image
returns flatField, average background level, fitted image, valid indices mask
'''
fitimg, mask = self._prepare()
out = fitimg.copy()
lastm = 0
for _ in range(10):
out = polyfit2dGrid(out, mask, 2)
mask = highGrad(out)
m = mask.sum()
if m == lastm:
break
lastm = m
out = np.clip(out, 0.1, 1)
out = resize(out, self._orig_shape, mode='reflect')
return out, self.bglevel / self._n, fitimg, mask |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def register_array_types_from_sources(self, source_files):
'''Add array type definitions from a file list to internal registry
Args:
source_files (list of str): Files to parse for array definitions
'''
for fname in source_files:
if is_vhdl(fname):
self._register_array_types(self.extract_objects(fname)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def run(self, text):
'''Run lexer rules against a source text
Args:
text (str): Text to apply lexer to
Yields:
A sequence of lexer matches.
'''
stack = ['root']
pos = 0
patterns = self.tokens[stack[-1]]
while True:
for pat, action, new_state in patterns:
m = pat.match(text, pos)
if m:
if action:
#print('## MATCH: {} -> {}'.format(m.group(), action))
yield (pos, m.end()-1), action, m.groups()
pos = m.end()
if new_state:
if isinstance(new_state, int): # Pop states
del stack[new_state:]
else:
stack.append(new_state)
#print('## CHANGE STATE:', pos, new_state, stack)
patterns = self.tokens[stack[-1]]
break
else:
try:
if text[pos] == '\n':
pos += 1
continue
pos += 1
except IndexError:
break |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_package_version(verfile):
'''Scan the script for the version string'''
version = None
with open(verfile) as fh:
try:
version = [line.split('=')[1].strip().strip("'") for line in fh if \
line.startswith('__version__')][0]
except IndexError:
pass
return version |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def parse_verilog(text):
'''Parse a text buffer of Verilog code
Args:
text (str): Source code to parse
Returns:
List of parsed objects.
'''
lex = VerilogLexer
name = None
kind = None
saved_type = None
mode = 'input'
ptype = 'wire'
metacomments = []
parameters = []
param_items = []
generics = []
ports = collections.OrderedDict()
sections = []
port_param_index = 0
last_item = None
array_range_start_pos = 0
objects = []
for pos, action, groups in lex.run(text):
if action == 'metacomment':
if last_item is None:
metacomments.append(groups[0])
else:
last_item.desc = groups[0]
if action == 'section_meta':
sections.append((port_param_index, groups[0]))
elif action == 'module':
kind = 'module'
name = groups[0]
generics = []
ports = collections.OrderedDict()
param_items = []
sections = []
port_param_index = 0
elif action == 'parameter_start':
net_type, vec_range = groups
new_ptype = ''
if net_type is not None:
new_ptype += net_type
if vec_range is not None:
new_ptype += ' ' + vec_range
ptype = new_ptype
elif action == 'param_item':
generics.append(VerilogParameter(groups[0], 'in', ptype))
elif action == 'module_port_start':
new_mode, net_type, signed, vec_range = groups
new_ptype = ''
if net_type is not None:
new_ptype += net_type
if signed is not None:
new_ptype += ' ' + signed
if vec_range is not None:
new_ptype += ' ' + vec_range
# Complete pending items
for i in param_items:
ports[i] = VerilogParameter(i, mode, ptype)
param_items = []
if len(ports) > 0:
last_item = next(reversed(ports))
# Start with new mode
mode = new_mode
ptype = new_ptype
elif action == 'port_param':
ident = groups[0]
param_items.append(ident)
port_param_index += 1
elif action == 'end_module':
# Finish any pending ports
for i in param_items:
ports[i] = VerilogParameter(i, mode, ptype)
vobj = VerilogModule(name, ports.values(), generics, dict(sections), metacomments)
objects.append(vobj)
last_item = None
metacomments = []
return objects |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def extract_objects(self, fname, type_filter=None):
'''Extract objects from a source file
Args:
fname(str): Name of file to read from
type_filter (class, optional): Object class to filter results
Returns:
List of objects extracted from the file.
'''
objects = []
if fname in self.object_cache:
objects = self.object_cache[fname]
else:
with io.open(fname, 'rt', encoding='utf-8') as fh:
text = fh.read()
objects = parse_verilog(text)
self.object_cache[fname] = objects
if type_filter:
objects = [o for o in objects if isinstance(o, type_filter)]
return objects |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_json_from_file(file_path):
"""Load schema from a JSON file""" |
try:
with open(file_path) as f:
json_data = json.load(f)
except ValueError as e:
raise ValueError('Given file {} is not a valid JSON file: {}'.format(file_path, e))
else:
return json_data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_json_from_string(string):
"""Load schema from JSON string""" |
try:
json_data = json.loads(string)
except ValueError as e:
raise ValueError('Given string is not valid JSON: {}'.format(e))
else:
return json_data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generate_one_fake(self, schema):
""" Recursively traverse schema dictionary and for each "leaf node", evaluate the fake value Implementation: For each key-value pair: 1) If value is not an iterable (i.e. dict or list), evaluate the fake data (base case) 2) If value is a dictionary, recurse 3) If value is a list, iteratively recurse over each item """ |
data = {}
for k, v in schema.items():
if isinstance(v, dict):
data[k] = self._generate_one_fake(v)
elif isinstance(v, list):
data[k] = [self._generate_one_fake(item) for item in v]
else:
data[k] = getattr(self._faker, v)()
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_and_parse(method, uri, params_prefix=None, **params):
"""Fetch the given uri and return the root Element of the response.""" |
doc = ElementTree.parse(fetch(method, uri, params_prefix, **params))
return _parse(doc.getroot()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse(root):
"""Recursively convert an Element into python data types""" |
if root.tag == "nil-classes":
return []
elif root.get("type") == "array":
return [_parse(child) for child in root]
d = {}
for child in root:
type = child.get("type") or "string"
if child.get("nil"):
value = None
elif type == "boolean":
value = True if child.text.lower() == "true" else False
elif type == "dateTime":
value = iso8601.parse_date(child.text)
elif type == "decimal":
value = decimal.Decimal(child.text)
elif type == "integer":
value = int(child.text)
else:
value = child.text
d[child.tag] = value
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expandDescendants(self, branches):
""" Expand descendants from list of branches :param list branches: list of immediate children as TreeOfContents objs :return: list of all descendants """ |
return sum([b.descendants() for b in branches], []) + \
[b.source for b in branches] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parseBranches(self, descendants):
""" Parse top level of markdown :param list elements: list of source objects :return: list of filtered TreeOfContents objects """ |
parsed, parent, cond = [], False, lambda b: (b.string or '').strip()
for branch in filter(cond, descendants):
if self.getHeadingLevel(branch) == self.depth:
parsed.append({'root':branch.string, 'source':branch})
parent = True
elif not parent:
parsed.append({'root':branch.string, 'source':branch})
else:
parsed[-1].setdefault('descendants', []).append(branch)
return [TOC(depth=self.depth+1, **kwargs) for kwargs in parsed] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fromHTML(html, *args, **kwargs):
""" Creates abstraction using HTML :param str html: HTML :return: TreeOfContents object """ |
source = BeautifulSoup(html, 'html.parser', *args, **kwargs)
return TOC('[document]',
source=source,
descendants=source.children) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_data(cls, type, **data):
"""Create an attachment from data. :param str type: attachment type :param kwargs data: additional attachment data :return: an attachment subclass object :rtype: `~groupy.api.attachments.Attachment` """ |
try:
return cls._types[type](**data)
except KeyError:
return cls(type=type, **data)
except TypeError as e:
error = 'could not create {!r} attachment'.format(type)
raise TypeError('{}: {}'.format(error, e.args[0])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_file(self, fp):
"""Create a new image attachment from an image file. :param file fp: a file object containing binary image data :return: an image attachment :rtype: :class:`~groupy.api.attachments.Image` """ |
image_urls = self.upload(fp)
return Image(image_urls['url'], source_url=image_urls['picture_url']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload(self, fp):
"""Upload image data to the image service. Call this, rather than :func:`from_file`, you don't want to create an attachment of the image. :param file fp: a file object containing binary image data :return: the URLs for the image uploaded :rtype: dict """ |
url = utils.urljoin(self.url, 'pictures')
response = self.session.post(url, data=fp.read())
image_urls = response.data
return image_urls |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(self, image, url_field='url', suffix=None):
"""Download the binary data of an image attachment. :param image: an image attachment :type image: :class:`~groupy.api.attachments.Image` :param str url_field: the field of the image with the right URL :param str suffix: an optional URL suffix :return: binary image data :rtype: bytes """ |
url = getattr(image, url_field)
if suffix is not None:
url = '.'.join(url, suffix)
response = self.session.get(url)
return response.content |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_preview(self, image, url_field='url'):
"""Downlaod the binary data of an image attachment at preview size. :param str url_field: the field of the image with the right URL :return: binary image data :rtype: bytes """ |
return self.download(image, url_field=url_field, suffix='preview') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_large(self, image, url_field='url'):
"""Downlaod the binary data of an image attachment at large size. :param str url_field: the field of the image with the right URL :return: binary image data :rtype: bytes """ |
return self.download(image, url_field=url_field, suffix='large') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_avatar(self, image, url_field='url'):
"""Downlaod the binary data of an image attachment at avatar size. :param str url_field: the field of the image with the right URL :return: binary image data :rtype: bytes """ |
return self.download(image, url_field=url_field, suffix='avatar') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def autopage(self):
"""Iterate through results from all pages. :return: all results :rtype: generator """ |
while self.items:
yield from self.items
self.items = self.fetch_next() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def detect_mode(cls, **params):
"""Detect which listing mode of the given params. :params kwargs params: the params :return: one of the available modes :rtype: str :raises ValueError: if multiple modes are detected """ |
modes = []
for mode in cls.modes:
if params.get(mode) is not None:
modes.append(mode)
if len(modes) > 1:
error_message = 'ambiguous mode, must be one of {}'
modes_csv = ', '.join(list(cls.modes))
raise ValueError(error_message.format(modes_csv))
return modes[0] if modes else cls.default_mode |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_next_page_params(self):
"""Set the params so that the next page is fetched.""" |
if self.items:
index = self.get_last_item_index()
self.params[self.mode] = self.get_next_page_param(self.items[index]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list(self):
"""List the users you have blocked. :return: a list of :class:`~groupy.api.blocks.Block`'s :rtype: :class:`list` """ |
params = {'user': self.user_id}
response = self.session.get(self.url, params=params)
blocks = response.data['blocks']
return [Block(self, **block) for block in blocks] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def between(self, other_user_id):
"""Check if there is a block between you and the given user. :return: ``True`` if the given user has been blocked :rtype: bool """ |
params = {'user': self.user_id, 'otherUser': other_user_id}
response = self.session.get(self.url, params=params)
return response.data['between'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def block(self, other_user_id):
"""Block the given user. :param str other_user_id: the ID of the user to block :return: the block created :rtype: :class:`~groupy.api.blocks.Block` """ |
params = {'user': self.user_id, 'otherUser': other_user_id}
response = self.session.post(self.url, params=params)
block = response.data['block']
return Block(self, **block) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unblock(self, other_user_id):
"""Unblock the given user. :param str other_user_id: the ID of the user to unblock :return: ``True`` if successful :rtype: bool """ |
params = {'user': self.user_id, 'otherUser': other_user_id}
response = self.session.delete(self.url, params=params)
return response.ok |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list(self, page=1, per_page=10):
"""List a page of chats. :param int page: which page :param int per_page: how many chats per page :return: chats with other users :rtype: :class:`~groupy.pagers.ChatList` """ |
return pagers.ChatList(self, self._raw_list, per_page=per_page,
page=page) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list(self, before_id=None, since_id=None, after_id=None, limit=20):
"""Return a page of group messages. The messages come in reversed order (newest first). Note you can only provide _one_ of ``before_id``, ``since_id``, or ``after_id``. :param str before_id: message ID for paging backwards :param str after_id: message ID for paging forwards :param str since_id: message ID for most recent messages since :param int limit: maximum number of messages per page :return: group messages :rtype: :class:`~groupy.pagers.MessageList` """ |
return pagers.MessageList(self, self._raw_list, before_id=before_id,
after_id=after_id, since_id=since_id,
limit=limit) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_since(self, message_id, limit=None):
"""Return a page of group messages created since a message. This is used to fetch the most recent messages after another. There may exist messages between the one given and the ones returned. Use :func:`list_after` to retrieve newer messages without skipping any. :param str message_id: the ID of a message :param int limit: maximum number of messages per page :return: group messages :rtype: :class:`~groupy.pagers.MessageList` """ |
return self.list(since_id=message_id, limit=limit) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_after(self, message_id, limit=None):
"""Return a page of group messages created after a message. This is used to page forwards through messages. :param str message_id: the ID of a message :param int limit: maximum number of messages per page :return: group messages :rtype: :class:`~groupy.pagers.MessageList` """ |
return self.list(after_id=message_id, limit=limit) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_all_before(self, message_id, limit=None):
"""Return all group messages created before a message. :param str message_id: the ID of a message :param int limit: maximum number of messages per page :return: group messages :rtype: generator """ |
return self.list_before(message_id, limit=limit).autopage() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_all_after(self, message_id, limit=None):
"""Return all group messages created after a message. :param str message_id: the ID of a message :param int limit: maximum number of messages per page :return: group messages :rtype: generator """ |
return self.list_after(message_id, limit=limit).autopage() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, text=None, attachments=None, source_guid=None):
"""Create a new message in the group. :param str text: the text of the message :param attachments: a list of attachments :type attachments: :class:`list` :param str source_guid: a unique identifier for the message :return: the created message :rtype: :class:`~groupy.api.messages.Message` """ |
message = {
'source_guid': source_guid or str(time.time()),
}
if text is not None:
message['text'] = text
if attachments is not None:
message['attachments'] = [a.to_json() for a in attachments]
payload = {'message': message}
response = self.session.post(self.url, json=payload)
message = response.data['message']
return Message(self, **message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list(self, before_id=None, since_id=None, **kwargs):
"""Return a page of direct messages. The messages come in reversed order (newest first). Note you can only provide _one_ of ``before_id``, ``since_id``. :param str before_id: message ID for paging backwards :param str since_id: message ID for most recent messages since :return: direct messages :rtype: :class:`~groupy.pagers.MessageList` """ |
return pagers.MessageList(self, self._raw_list, before_id=before_id,
since_id=since_id, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_all(self, before_id=None, since_id=None, **kwargs):
"""Return all direct messages. The messages come in reversed order (newest first). Note you can only provide _one_ of ``before_id``, ``since_id``. :param str before_id: message ID for paging backwards :param str since_id: message ID for most recent messages since :return: direct messages :rtype: generator """ |
return self.list(before_id=before_id, since_id=since_id, **kwargs).autopage() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, nickname, email=None, phone_number=None, user_id=None):
"""Add a user to the group. You must provide either the email, phone number, or user_id that uniquely identifies a user. :param str nickname: new name for the user in the group :param str email: email address of the user :param str phone_number: phone number of the user :param str user_id: user_id of the user :return: a membership request :rtype: :class:`MembershipRequest` """ |
member = {
'nickname': nickname,
'email': email,
'phone_number': phone_number,
'user_id': user_id,
}
return self.add_multiple(member) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_multiple(self, *users):
"""Add multiple users to the group at once. Each given user must be a dictionary containing a nickname and either an email, phone number, or user_id. :param args users: the users to add :return: a membership request :rtype: :class:`MembershipRequest` """ |
guid = uuid.uuid4()
for i, user_ in enumerate(users):
user_['guid'] = '{}-{}'.format(guid, i)
payload = {'members': users}
url = utils.urljoin(self.url, 'add')
response = self.session.post(url, json=payload)
return MembershipRequest(self, *users, group_id=self.group_id,
**response.data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check(self, results_id):
"""Check for results of a membership request. :param str results_id: the ID of a membership request :return: successfully created memberships :rtype: :class:`list` :raises groupy.exceptions.ResultsNotReady: if the results are not ready :raises groupy.exceptions.ResultsExpired: if the results have expired """ |
path = 'results/{}'.format(results_id)
url = utils.urljoin(self.url, path)
response = self.session.get(url)
if response.status_code == 503:
raise exceptions.ResultsNotReady(response)
if response.status_code == 404:
raise exceptions.ResultsExpired(response)
return response.data['members'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(self, membership_id):
"""Remove a member from the group. :param str membership_id: the ID of a member in this group :return: ``True`` if the member was successfully removed :rtype: bool """ |
path = '{}/remove'.format(membership_id)
url = utils.urljoin(self.url, path)
payload = {'membership_id': membership_id}
response = self.session.post(url, json=payload)
return response.ok |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post(self, text=None, attachments=None, source_guid=None):
"""Post a direct message to the user. :param str text: the message content :param attachments: message attachments :param str source_guid: a client-side unique ID for the message :return: the message sent :rtype: :class:`~groupy.api.messages.DirectMessage` """ |
return self.messages.create(text=text, attachments=attachments,
source_guid=source_guid) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_to_group(self, group_id, nickname=None):
"""Add the member to another group. If a nickname is not provided the member's current nickname is used. :param str group_id: the group_id of a group :param str nickname: a new nickname :return: a membership request :rtype: :class:`MembershipRequest` """ |
if nickname is None:
nickname = self.nickname
memberships = Memberships(self.manager.session, group_id=group_id)
return memberships.add(nickname, user_id=self.user_id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_if_ready(self):
"""Check for and fetch the results if ready.""" |
try:
results = self.manager.check(self.results_id)
except exceptions.ResultsNotReady as e:
self._is_ready = False
self._not_ready_exception = e
except exceptions.ResultsExpired as e:
self._is_ready = True
self._expired_exception = e
else:
failures = self.get_failed_requests(results)
members = self.get_new_members(results)
self.results = self.__class__.Results(list(members), list(failures))
self._is_ready = True
self._not_ready_exception = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_failed_requests(self, results):
"""Return the requests that failed. :param results: the results of a membership request check :type results: :class:`list` :return: the failed requests :rtype: generator """ |
data = {member['guid']: member for member in results}
for request in self.requests:
if request['guid'] not in data:
yield request |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_new_members(self, results):
"""Return the newly added members. :param results: the results of a membership request check :type results: :class:`list` :return: the successful requests, as :class:`~groupy.api.memberships.Members` :rtype: generator """ |
for member in results:
guid = member.pop('guid')
yield Member(self.manager, self.group_id, **member)
member['guid'] = guid |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_ready(self, check=True):
"""Return ``True`` if the results are ready. If you pass ``check=False``, no attempt is made to check again for results. :param bool check: whether to query for the results :return: ``True`` if the results are ready :rtype: bool """ |
if not self._is_ready and check:
self.check_if_ready()
return self._is_ready |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def poll(self, timeout=30, interval=2):
"""Return the results when they become ready. :param int timeout: the maximum time to wait for the results :param float interval: the number of seconds between checks :return: the membership request result :rtype: :class:`~groupy.api.memberships.MembershipResult.Results` """ |
time.sleep(interval)
start = time.time()
while time.time() - start < timeout and not self.is_ready():
time.sleep(interval)
return self.get() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.