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 extract_cylinder(im, r=None, axis=0): r""" Returns a cylindrical section of the image of specified radius. This is useful for making square images look like cylindrical cores such as those obtained from X-ray tomography. Parameters im : ND-array The image of the porous material. Can be any data type. r : scalr The radius of the cylinder to extract. If ``None`` is given then the default is the largest cylinder that can fit inside the specified plane. axis : scalar The axis along with the cylinder will be oriented. Returns ------- image : ND-array A copy of ``im`` with values outside the cylindrical area set to 0 or ``False``. """
if r is None: a = list(im.shape) a.pop(axis) r = sp.floor(sp.amin(a) / 2) dim = [range(int(-s / 2), int(s / 2) + s % 2) for s in im.shape] inds = sp.meshgrid(*dim, indexing='ij') inds[axis] = inds[axis] * 0 d = sp.sqrt(sp.sum(sp.square(inds), axis=0)) mask = d < r im_temp = im*mask return im_temp
<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_subsection(im, shape): r""" Extracts the middle section of a image Parameters im : ND-array Image from which to extract the subsection shape : array_like Can either specify the size of the extracted section or the fractional size of the image to extact. Returns ------- image : ND-array An ND-array of size given by the ``shape`` argument, taken from the center of the image. Examples -------- [[1 1 1 1] [1 2 2 2] [1 2 3 3] [1 2 3 4]] [[2 2] [2 3]] """
# Check if shape was given as a fraction shape = sp.array(shape) if shape[0] < 1: shape = sp.array(im.shape) * shape center = sp.array(im.shape) / 2 s_im = [] for dim in range(im.ndim): r = shape[dim] / 2 lower_im = sp.amax((center[dim] - r, 0)) upper_im = sp.amin((center[dim] + r, im.shape[dim])) s_im.append(slice(int(lower_im), int(upper_im))) return im[tuple(s_im)]
<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_planes(im, squeeze=True): r""" Extracts three planar images from the volumetric image, one for each principle axis. The planes are taken from the middle of the domain. Parameters im : ND-array The volumetric image from which the 3 planar images are to be obtained squeeze : boolean, optional If True (default) the returned images are 2D (i.e. squeezed). If False, the images are 1 element deep along the axis where the slice was obtained. Returns ------- planes : list A list of 2D-images """
x, y, z = (sp.array(im.shape) / 2).astype(int) planes = [im[x, :, :], im[:, y, :], im[:, :, z]] if not squeeze: imx = planes[0] planes[0] = sp.reshape(imx, [1, imx.shape[0], imx.shape[1]]) imy = planes[1] planes[1] = sp.reshape(imy, [imy.shape[0], 1, imy.shape[1]]) imz = planes[2] planes[2] = sp.reshape(imz, [imz.shape[0], imz.shape[1], 1]) return planes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extend_slice(s, shape, pad=1): r""" Adjust slice indices to include additional voxles around the slice. This function does bounds checking to ensure the indices don't extend outside the image. Parameters s : list of slice objects A list (or tuple) of N slice objects, where N is the number of dimensions in the image. shape : array_like The shape of the image into which the slice objects apply. This is used to check the bounds to prevent indexing beyond the image. pad : int The number of voxels to expand in each direction. Returns ------- slices : list of slice objects A list slice of objects with the start and stop attributes respectively incremented and decremented by 1, without extending beyond the image boundaries. Examples -------- Using the slices returned by ``find_objects``, set the first label to 3 [[3 0 0] [3 0 0] [0 0 2]] Next extend the slice, and use it to set the values to 4 [[4 4 0] [4 4 0] [4 4 2]] As can be seen by the location of the 4s, the slice was extended by 1, and also handled the extension beyond the boundary correctly. """
pad = int(pad) a = [] for i, dim in zip(s, shape): start = 0 stop = dim if i.start - pad >= 0: start = i.start - pad if i.stop + pad < dim: stop = i.stop + pad a.append(slice(start, stop, None)) return tuple(a)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def randomize_colors(im, keep_vals=[0]): r''' Takes a greyscale image and randomly shuffles the greyscale values, so that all voxels labeled X will be labelled Y, and all voxels labeled Y will be labeled Z, where X, Y, Z and so on are randomly selected from the values in the input image. This function is useful for improving the visibility of images with neighboring regions that are only incrementally different from each other, such as that returned by `scipy.ndimage.label`. Parameters ---------- im : array_like An ND image of greyscale values. keep_vals : array_like Indicate which voxel values should NOT be altered. The default is `[0]` which is useful for leaving the background of the image untouched. Returns ------- image : ND-array An image the same size and type as ``im`` but with the greyscale values reassigned. The unique values in both the input and output images will be identical. Notes ----- If the greyscale values in the input image are not contiguous then the neither will they be in the output. Examples -------- >>> import porespy as ps >>> import scipy as sp >>> sp.random.seed(0) >>> im = sp.random.randint(low=0, high=5, size=[4, 4]) >>> print(im) [[4 0 3 3] [3 1 3 2] [4 0 0 4] [2 1 0 1]] >>> im_rand = ps.tools.randomize_colors(im) >>> print(im_rand) [[2 0 4 4] [4 1 4 3] [2 0 0 2] [3 1 0 1]] As can be seen, the 2's have become 3, 3's have become 4, and 4's have become 2. 1's remained 1 by random accident. 0's remain zeros by default, but this can be controlled using the `keep_vals` argument. ''' im_flat = im.flatten() keep_vals = sp.array(keep_vals) swap_vals = ~sp.in1d(im_flat, keep_vals) im_vals = sp.unique(im_flat[swap_vals]) new_vals = sp.random.permutation(im_vals) im_map = sp.zeros(shape=[sp.amax(im_vals) + 1, ], dtype=int) im_map[im_vals] = new_vals im_new = im_map[im_flat] im_new = sp.reshape(im_new, newshape=sp.shape(im)) return im_new
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_contiguous(im, keep_zeros=True): r""" Take an image with arbitrary greyscale values and adjust them to ensure all values fall in a contiguous range starting at 0. This function will handle negative numbers such that most negative number will become 0, *unless* ``keep_zeros`` is ``True`` in which case it will become 1, and all 0's in the original image remain 0. Parameters im : array_like An ND array containing greyscale values keep_zeros : Boolean If ``True`` (default) then 0 values remain 0, regardless of how the other numbers are adjusted. This is mostly relevant when the array contains negative numbers, and means that -1 will become +1, while 0 values remain 0. Returns ------- image : ND-array An ND-array the same size as ``im`` but with all values in contiguous orders. Example ------- [[0 1 5] [3 4 2]] """
im = sp.copy(im) if keep_zeros: mask = (im == 0) im[mask] = im.min() - 1 im = im - im.min() im_flat = im.flatten() im_vals = sp.unique(im_flat) im_map = sp.zeros(shape=sp.amax(im_flat) + 1) im_map[im_vals] = sp.arange(0, sp.size(sp.unique(im_flat))) im_new = im_map[im_flat] im_new = sp.reshape(im_new, newshape=sp.shape(im)) im_new = sp.array(im_new, dtype=im_flat.dtype) return im_new
<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_border(shape, thickness=1, mode='edges', return_indices=False): r""" Creates an array of specified size with corners, edges or faces labelled as True. This can be used as mask to manipulate values laying on the perimeter of an image. Parameters shape : array_like The shape of the array to return. Can be either 2D or 3D. thickness : scalar (default is 1) The number of pixels/voxels to place along perimeter. mode : string The type of border to create. Options are 'faces', 'edges' (default) and 'corners'. In 2D 'faces' and 'edges' give the same result. return_indices : boolean If ``False`` (default) an image is returned with the border voxels set to ``True``. If ``True``, then a tuple with the x, y, z (if ``im`` is 3D) indices is returned. This tuple can be used directly to index into the image, such as ``im[tup] = 2``. Returns ------- image : ND-array An ND-array of specified shape with ``True`` values at the perimeter and ``False`` elsewhere Notes ----- TODO: This function uses brute force to create an image then fill the edges using location-based logic, and if the user requests ``return_indices`` it finds them using ``np.where``. Since these arrays are cubic it should be possible to use more elegant and efficient index-based logic to find the indices, then use them to fill an empty image with ``True`` using these indices. Examples -------- [[ True False True] [False False False] [ True False True]] [[ True True True] [ True False True] [ True True True]] """
ndims = len(shape) t = thickness border = sp.ones(shape, dtype=bool) if mode == 'faces': if ndims == 2: border[t:-t, t:-t] = False if ndims == 3: border[t:-t, t:-t, t:-t] = False elif mode == 'edges': if ndims == 2: border[t:-t, t:-t] = False if ndims == 3: border[0::, t:-t, t:-t] = False border[t:-t, 0::, t:-t] = False border[t:-t, t:-t, 0::] = False elif mode == 'corners': if ndims == 2: border[t:-t, 0::] = False border[0::, t:-t] = False if ndims == 3: border[t:-t, 0::, 0::] = False border[0::, t:-t, 0::] = False border[0::, 0::, t:-t] = False if return_indices: border = sp.where(border) return border
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def in_hull(points, hull): """ Test if a list of coordinates are inside a given convex hull Parameters points : array_like (N x ndims) The spatial coordinates of the points to check hull : scipy.spatial.ConvexHull object **OR** array_like Can be either a convex hull object as returned by ``scipy.spatial.ConvexHull`` or simply the coordinates of the points that define the convex hull. Returns ------- result : 1D-array A 1D-array Boolean array of length *N* indicating whether or not the given points in ``points`` lies within the provided ``hull``. """
from scipy.spatial import Delaunay, ConvexHull if isinstance(hull, ConvexHull): hull = hull.points hull = Delaunay(hull) return hull.find_simplex(points) >= 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 functions_to_table(mod, colwidth=[27, 48]): r""" Given a module of functions, returns a ReST formatted text string that outputs a table when printed. Parameters mod : module The module containing the functions to be included in the table, such as 'porespy.filters'. colwidths : list of ints The width of the first and second columns. Note that because of the vertical lines separating columns and define the edges of the table, the total table width will be 3 characters wider than the total sum of the specified column widths. """
temp = mod.__dir__() funcs = [i for i in temp if not i[0].startswith('_')] funcs.sort() row = '+' + '-'*colwidth[0] + '+' + '-'*colwidth[1] + '+' fmt = '{0:1s} {1:' + str(colwidth[0]-2) + 's} {2:1s} {3:' \ + str(colwidth[1]-2) + 's} {4:1s}' lines = [] lines.append(row) lines.append(fmt.format('|', 'Method', '|', 'Description', '|')) lines.append(row.replace('-', '=')) for i, item in enumerate(funcs): try: s = getattr(mod, item).__doc__.strip() end = s.find('\n') if end > colwidth[1] - 2: s = s[:colwidth[1] - 5] + '...' lines.append(fmt.format('|', item, '|', s[:end], '|')) lines.append(row) except AttributeError: pass s = '\n'.join(lines) return s
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mesh_region(region: bool, strel=None): r""" Creates a tri-mesh of the provided region using the marching cubes algorithm Parameters im : ND-array A boolean image with ``True`` values indicating the region of interest strel : ND-array The structuring element to use when blurring the region. The blur is perfomed using a simple convolution filter. The point is to create a greyscale region to allow the marching cubes algorithm some freedom to conform the mesh to the surface. As the size of ``strel`` increases the region will become increasingly blurred and inaccurate. The default is a spherical element with a radius of 1. Returns ------- mesh : tuple A named-tuple containing ``faces``, ``verts``, ``norm``, and ``val`` as returned by ``scikit-image.measure.marching_cubes`` function. """
im = region if im.ndim != im.squeeze().ndim: warnings.warn('Input image conains a singleton axis:' + str(im.shape) + ' Reduce dimensionality with np.squeeze(im) to avoid' + ' unexpected behavior.') if strel is None: if region.ndim == 3: strel = ball(1) if region.ndim == 2: strel = disk(1) pad_width = sp.amax(strel.shape) if im.ndim == 3: padded_mask = sp.pad(im, pad_width=pad_width, mode='constant') padded_mask = spim.convolve(padded_mask * 1.0, weights=strel) / sp.sum(strel) else: padded_mask = sp.reshape(im, (1,) + im.shape) padded_mask = sp.pad(padded_mask, pad_width=pad_width, mode='constant') verts, faces, norm, val = marching_cubes_lewiner(padded_mask) result = namedtuple('mesh', ('verts', 'faces', 'norm', 'val')) result.verts = verts - pad_width result.faces = faces result.norm = norm result.val = val return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ps_disk(radius): r""" Creates circular disk structuring element for morphological operations Parameters radius : float or int The desired radius of the structuring element Returns ------- strel : 2D-array A 2D numpy bool array of the structring element """
rad = int(sp.ceil(radius)) other = sp.ones((2 * rad + 1, 2 * rad + 1), dtype=bool) other[rad, rad] = False disk = spim.distance_transform_edt(other) < radius return disk
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ps_ball(radius): r""" Creates spherical ball structuring element for morphological operations Parameters radius : float or int The desired radius of the structuring element Returns ------- strel : 3D-array A 3D numpy array of the structuring element """
rad = int(sp.ceil(radius)) other = sp.ones((2 * rad + 1, 2 * rad + 1, 2 * rad + 1), dtype=bool) other[rad, rad, rad] = False ball = spim.distance_transform_edt(other) < radius return ball
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def overlay(im1, im2, c): r""" Overlays ``im2`` onto ``im1``, given voxel coords of center of ``im2`` in ``im1``. Parameters im1 : ND-array Original voxelated image im2 : ND-array Template voxelated image c : array_like [x, y, z] coordinates in ``im1`` where ``im2`` will be centered Returns ------- image : ND-array A modified version of ``im1``, with ``im2`` overlaid at the specified location """
shape = im2.shape for ni in shape: if ni % 2 == 0: raise Exception("Structuring element must be odd-voxeled...") nx, ny, nz = [(ni - 1) // 2 for ni in shape] cx, cy, cz = c im1[cx-nx:cx+nx+1, cy-ny:cy+ny+1, cz-nz:cz+nz+1] += im2 return im1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert_sphere(im, c, r): r""" Inserts a sphere of a specified radius into a given image Parameters im : array_like Image into which the sphere should be inserted c : array_like The [x, y, z] coordinate indicating the center of the sphere r : int The radius of sphere to insert Returns ------- image : ND-array The original image with a sphere inerted at the specified location """
c = sp.array(c, dtype=int) if c.size != im.ndim: raise Exception('Coordinates do not match dimensionality of image') bbox = [] [bbox.append(sp.clip(c[i] - r, 0, im.shape[i])) for i in range(im.ndim)] [bbox.append(sp.clip(c[i] + r, 0, im.shape[i])) for i in range(im.ndim)] bbox = sp.ravel(bbox) s = bbox_to_slices(bbox) temp = im[s] blank = sp.ones_like(temp) blank[tuple(c - bbox[0:im.ndim])] = 0 blank = spim.distance_transform_edt(blank) < r im[s] = blank return im
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert_cylinder(im, xyz0, xyz1, r): r""" Inserts a cylinder of given radius onto a given image Parameters im : array_like Original voxelated image xyz0, xyz1 : 3-by-1 array_like Voxel coordinates of the two end points of the cylinder r : int Radius of the cylinder Returns ------- im : ND-array Original voxelated image overlayed with the cylinder Notes ----- This function is only implemented for 3D images """
if im.ndim != 3: raise Exception('This function is only implemented for 3D images') # Converting coordinates to numpy array xyz0, xyz1 = [sp.array(xyz).astype(int) for xyz in (xyz0, xyz1)] r = int(r) L = sp.absolute(xyz0 - xyz1).max() + 1 xyz_line = [sp.linspace(xyz0[i], xyz1[i], L).astype(int) for i in range(3)] xyz_min = sp.amin(xyz_line, axis=1) - r xyz_max = sp.amax(xyz_line, axis=1) + r shape_template = xyz_max - xyz_min + 1 template = sp.zeros(shape=shape_template) # Shortcut for orthogonal cylinders if (xyz0 == xyz1).sum() == 2: unique_dim = [xyz0[i] != xyz1[i] for i in range(3)].index(True) shape_template[unique_dim] = 1 template_2D = disk(radius=r).reshape(shape_template) template = sp.repeat(template_2D, repeats=L, axis=unique_dim) xyz_min[unique_dim] += r xyz_max[unique_dim] += -r else: xyz_line_in_template_coords = [xyz_line[i] - xyz_min[i] for i in range(3)] template[tuple(xyz_line_in_template_coords)] = 1 template = spim.distance_transform_edt(template == 0) <= r im[xyz_min[0]:xyz_max[0]+1, xyz_min[1]:xyz_max[1]+1, xyz_min[2]:xyz_max[2]+1] += template return im
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pad_faces(im, faces): r""" Pads the input image at specified faces. This shape of image is same as the output image of add_boundary_regions function. Parameters im : ND_array The image that needs to be padded faces : list of strings Labels indicating where image needs to be padded. Given a 3D image of shape ``[x, y, z] = [i, j, k]``, the following conventions are used to indicate along which axis the padding should be applied: * 'left' -> ``x = 0`` * 'right' -> ``x = i`` * 'front' -> ``y = 0`` * 'back' -> ``y = j`` * 'bottom' -> ``z = 0`` * 'top' -> ``z = k`` Returns ------- A image padded at specified face(s) See also -------- add_boundary_regions """
if im.ndim != im.squeeze().ndim: warnings.warn('Input image conains a singleton axis:' + str(im.shape) + ' Reduce dimensionality with np.squeeze(im) to avoid' + ' unexpected behavior.') f = faces if f is not None: if im.ndim == 2: faces = [(int('left' in f) * 3, int('right' in f) * 3), (int(('front') in f) * 3 or int(('bottom') in f) * 3, int(('back') in f) * 3 or int(('top') in f) * 3)] if im.ndim == 3: faces = [(int('left' in f) * 3, int('right' in f) * 3), (int('front' in f) * 3, int('back' in f) * 3), (int('top' in f) * 3, int('bottom' in f) * 3)] im = sp.pad(im, pad_width=faces, mode='edge') else: im = im return im
<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_alias_map(im, alias=None): r""" Creates an alias mapping between phases in original image and identifyable names. This mapping is used during network extraction to label interconnection between and properties of each phase. Parameters im : ND-array Image of porous material where each phase is represented by unique integer. Phase integer should start from 1. Boolean image will extract only one network labeled with True's only. alias : dict (Optional) A dictionary that assigns unique image label to specific phase. For example {1: 'Solid'} will show all structural properties associated with label 1 as Solid phase properties. If ``None`` then default labelling will be used i.e {1: 'Phase1',..}. Returns ------- A dictionary with numerical phase labels as key, and readable phase names as valuies. If no alias is provided then default labelling is used i.e {1: 'Phase1',..} """
# ------------------------------------------------------------------------- # Get alias if provided by user phases_num = sp.unique(im * 1) phases_num = sp.trim_zeros(phases_num) al = {} for values in phases_num: al[values] = 'phase{}'.format(values) if alias is not None: alias_sort = dict(sorted(alias.items())) phase_labels = sp.array([*alias_sort]) al = alias if set(phase_labels) != set(phases_num): raise Exception('Alias labels does not match with image labels ' 'please provide correct image labels') return al
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _filehash(filepath, blocksize=4096): """ Return the hash object for the file `filepath', processing the file by chunk of `blocksize'. :type filepath: str :param filepath: Path to file :type blocksize: int :param blocksize: Size of the chunk when processing the file """
sha = hashlib.sha256() with open(filepath, 'rb') as fp: while 1: data = fp.read(blocksize) if data: sha.update(data) else: break return sha
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compress_to(self, archive_path=None): """ Compress the directory with gzip using tarlib. :type archive_path: str :param archive_path: Path to the archive, if None, a tempfile is created """
if archive_path is None: archive = tempfile.NamedTemporaryFile(delete=False) tar_args = () tar_kwargs = {'fileobj': archive} _return = archive.name else: tar_args = (archive_path) tar_kwargs = {} _return = archive_path tar_kwargs.update({'mode': 'w:gz'}) with closing(tarfile.open(*tar_args, **tar_kwargs)) as tar: tar.add(self.path, arcname=self.file) return _return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iterfiles(self, pattern=None, abspath=False): """ Generator for all the files not excluded recursively. Return relative path. :type pattern: str :param pattern: Unix style (glob like/gitignore like) pattern """
if pattern is not None: globster = Globster([pattern]) for root, dirs, files in self.walk(): for f in files: if pattern is None or (pattern is not None and globster.match(f)): if abspath: yield os.path.join(root, f) else: yield self.relpath(os.path.join(root, f))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def size(self): """ Return directory size in bytes. :rtype: int :return: Total directory size in bytes. """
dir_size = 0 for f in self.iterfiles(abspath=True): dir_size += os.path.getsize(f) return dir_size
<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_excluded(self, path): """ Return True if `path' should be excluded given patterns in the `exclude_file'. """
match = self.globster.match(self.relpath(path)) if match: log.debug("{0} matched {1} for exclusion".format(path, match)) return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_projects(self, file_identifier=".project"): """ Search all directory recursively for subdirs with `file_identifier' in it. :type file_identifier: str :param file_identifier: File identier, .project by default. :rtype: list :return: The list of subdirs with a `file_identifier' in it. """
projects = [] for d in self.subdirs(): project_file = os.path.join(self.directory, d, file_identifier) if os.path.isfile(project_file): projects.append(d) return projects
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def relpath(self, path): """ Return a relative filepath to path from Dir path. """
return os.path.relpath(path, start=self.path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute_state(self): """ Generate the index. """
data = {} data['directory'] = self._dir.path data['files'] = list(self._dir.files()) data['subdirs'] = list(self._dir.subdirs()) data['index'] = self.index() 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 basic_auth_required(view_func): """ A decorator that can be used to protect specific views with HTTP basic access authentication. Conditional on having BASIC_AUTH_USERNAME and BASIC_AUTH_PASSWORD set as env vars. """
@wraps(view_func) def wrapper(*args, **kwargs): if app.config.get('BASIC_AUTH_ACTIVE', False): if basic_auth.authenticate(): return view_func(*args, **kwargs) else: return basic_auth.challenge() else: return view_func(*args, **kwargs) return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def badge(pipeline_id): '''An individual pipeline status''' if not pipeline_id.startswith('./'): pipeline_id = './' + pipeline_id pipeline_status = status.get(pipeline_id) status_color = 'lightgray' if pipeline_status.pipeline_details: status_text = pipeline_status.state().lower() last_execution = pipeline_status.get_last_execution() success = last_execution.success if last_execution else None if success is True: stats = last_execution.stats if last_execution else None record_count = stats.get('count_of_rows') if record_count is not None: status_text += ' (%d records)' % record_count status_color = 'brightgreen' elif success is False: status_color = 'red' else: status_text = "not found" return _make_badge_response('pipeline', status_text, status_color)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def badge_collection(pipeline_path): '''Status badge for a collection of pipelines.''' all_pipeline_ids = sorted(status.all_pipeline_ids()) if not pipeline_path.startswith('./'): pipeline_path = './' + pipeline_path # Filter pipeline ids to only include those that start with pipeline_path. path_pipeline_ids = \ [p for p in all_pipeline_ids if p.startswith(pipeline_path)] statuses = [] for pipeline_id in path_pipeline_ids: pipeline_status = status.get(pipeline_id) if pipeline_status is None: abort(404) status_text = pipeline_status.state().lower() statuses.append(status_text) status_color = 'lightgray' status_counter = Counter(statuses) if status_counter: if len(status_counter) == 1 and status_counter['succeeded'] > 0: status_color = 'brightgreen' elif status_counter['failed'] > 0: status_color = 'red' elif status_counter['failed'] == 0: status_color = 'yellow' status_text = \ ', '.join(['{} {}'.format(v, k) for k, v in status_counter.items()]) else: status_text = "not found" return _make_badge_response('pipelines', status_text, status_color)
<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_pipelines(pipeline_id_pattern, root_dir, use_cache=True, dirty=False, force=False, concurrency=1, verbose_logs=True, progress_cb=None, slave=False): """Run a pipeline by pipeline-id. pipeline-id supports the '%' wildcard for any-suffix matching. Use 'all' or '%' for running all pipelines"""
with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency, thread_name_prefix='T') as executor: try: results = [] pending_futures = set() done_futures = set() finished_futures = [] progress_thread = None progress_queue = None status_manager = status_mgr(root_dir) if progress_cb is not None: progress_queue = Queue() progress_thread = threading.Thread(target=progress_report_handler, args=(progress_cb, progress_queue)) progress_thread.start() all_specs = specs_to_execute(pipeline_id_pattern, root_dir, status_manager, force, dirty, results) while True: done = None if len(done_futures) > 0: done = done_futures.pop() finished_futures.append(done) done = done.result()[0] try: spec = all_specs.send(done) except StopIteration: spec = None if spec is None: # Wait for all runners to idle... if len(done_futures) == 0: if len(pending_futures) > 0: done_futures, pending_futures = \ concurrent.futures.wait(pending_futures, return_when=concurrent.futures.FIRST_COMPLETED) continue else: break else: continue if len(spec.validation_errors) > 0: results.append( ExecutionResult(spec.pipeline_id, False, {}, ['init'] + list(map(str, spec.validation_errors))) ) continue if slave: ps = status_manager.get(spec.pipeline_id) ps.init(spec.pipeline_details, spec.source_details, spec.validation_errors, spec.cache_hash) eid = gen_execution_id() if ps.queue_execution(eid, 'manual'): success, stats, errors = \ execute_pipeline(spec, eid, use_cache=use_cache) results.append(ExecutionResult( spec.pipeline_id, success, stats, errors )) else: results.append( ExecutionResult(spec.pipeline_id, False, None, ['Already Running']) ) else: f = executor.submit(remote_execute_pipeline, spec, root_dir, use_cache, verbose_logs, progress_queue) pending_futures.add(f) for f in finished_futures: ret = f.result() results.append(ExecutionResult(*ret)) except KeyboardInterrupt: pass finally: if slave: finalize() if progress_thread is not None: progress_queue.put(None) progress_thread.join() return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert(self, index, key): """Adds an element at a dedicated position in an OrderedSet. This implementation is meant for the OrderedSet from the ordered_set package only. """
if key in self.map: return # compute the right index size = len(self.items) if index < 0: index = size + index if size + index > 0 else 0 else: index = index if index < size else size # insert the value self.items.insert(index, key) for k, v in self.map.items(): if v >= index: self.map[k] = v + 1 self.map[key] = 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 pop(self, index=None): """Removes an element at the tail of the OrderedSet or at a dedicated position. This implementation is meant for the OrderedSet from the ordered_set package only. """
if not self.items: raise KeyError('Set is empty') def remove_index(i): elem = self.items[i] del self.items[i] del self.map[elem] return elem if index is None: elem = remove_index(-1) else: size = len(self.items) if index < 0: index = size + index if index < 0: raise IndexError('assignement index out of range') elif index >= size: raise IndexError('assignement index out of range') elem = remove_index(index) for k, v in self.map.items(): if v >= index and v > 0: self.map[k] = v - 1 return elem
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def EMetaclass(cls): """Class decorator for creating PyEcore metaclass."""
superclass = cls.__bases__ if not issubclass(cls, EObject): sclasslist = list(superclass) if object in superclass: index = sclasslist.index(object) sclasslist.insert(index, EObject) sclasslist.remove(object) else: sclasslist.insert(0, EObject) superclass = tuple(sclasslist) orig_vars = cls.__dict__.copy() slots = orig_vars.get('__slots__') if slots is not None: if isinstance(slots, str): slots = [slots] for slots_var in slots: orig_vars.pop(slots_var) orig_vars.pop('__dict__', None) orig_vars.pop('__weakref__', None) return MetaEClass(cls.__name__, superclass, orig_vars)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getEAnnotation(self, source): """Return the annotation with a matching source attribute."""
for annotation in self.eAnnotations: if annotation.source == source: return annotation return 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_week_URL(date, day=0): """ Returns the week view URL for a given date. :param date: A date instance. :param day: Day number in a month. """
if day < 1: day = 1 date = datetime(year=date.year, month=date.month, day=day, tzinfo=utc) return reverse('calendar_week', kwargs={'year': date.isocalendar()[0], 'week': date.isocalendar()[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 monday_of_week(year, week): """ Returns a datetime for the monday of the given week of the given year. """
str_time = time.strptime('{0} {1} 1'.format(year, week), '%Y %W %w') date = timezone.datetime(year=str_time.tm_year, month=str_time.tm_mon, day=str_time.tm_mday, tzinfo=timezone.utc) if timezone.datetime(year, 1, 4).isoweekday() > 4: # ISO 8601 where week 1 is the first week that has at least 4 days in # the current year date -= timezone.timedelta(days=7) return 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 get_occurrence(self, occ): """ Return a persisted occurrences matching the occ and remove it from lookup since it has already been matched """
return self.lookup.pop( (occ.event, occ.original_start, occ.original_end), occ)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _request(self, uri, method='GET', params=None, files=None, headers=None, auth=None): """Robustness wrapper. Tries up to 3 times to dance with the Sandbox API. :type uri: str :param uri: URI to append to base_url. :type params: dict :param params: Optional parameters for API. :type files: dict :param files: Optional dictionary of files for multipart post. :type headers: dict :param headers: Optional headers to send to the API. :type auth: dict :param auth: Optional authentication object to send to the API. :rtype: requests.response. :return: Response object. :raises SandboxError: If all attempts failed. """
# make up to three attempts to dance with the API, use a jittered # exponential back-off delay for i in range(3): try: full_url = '{b}{u}'.format(b=self.api_url, u=uri) response = None if method == 'POST': response = requests.post(full_url, data=params, files=files, headers=headers, verify=self.verify_ssl, auth=auth, proxies=self.proxies) else: response = requests.get(full_url, params=params, headers=headers, verify=self.verify_ssl, auth=auth, proxies=self.proxies) # if the status code is 503, is no longer available. if response.status_code >= 500: # server error self.server_available = False raise SandboxError("server returned {c} status code on {u}, assuming unavailable...".format( c=response.status_code, u=response.url)) else: return response # 0.4, 1.6, 6.4, 25.6, ... except requests.exceptions.RequestException: time.sleep(random.uniform(0, 4 ** i * 100 / 1000.0)) # if we couldn't reach the API, we assume that the box is down and lower availability flag. self.server_available = False # raise an exception. msg = "exceeded 3 attempts with sandbox API: {u}, p:{p}, f:{f}".format(u=full_url, p=params, f=files) try: msg += "\n" + response.content.decode('utf-8') except AttributeError: pass raise SandboxError(msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def analyses(self): """Retrieve a list of analyzed samples. :rtype: list :return: List of objects referencing each analyzed file. """
response = self._request("tasks/list") return json.loads(response.content.decode('utf-8'))['tasks']
<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, item_id): """Check if an analysis is complete :type item_id: int :param item_id: task_id to check. :rtype: bool :return: Boolean indicating if a report is done or not. """
response = self._request("tasks/view/{id}".format(id=item_id)) if response.status_code == 404: # probably an unknown task id return False try: content = json.loads(response.content.decode('utf-8')) status = content['task']["status"] if status == 'completed' or status == "reported": return True except ValueError as e: raise sandboxapi.SandboxError(e) return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, item_id): """Delete the reports associated with the given item_id. :type item_id: int :param item_id: Report ID to delete. :rtype: bool :return: True on success, False otherwise. """
try: response = self._request("tasks/delete/{id}".format(id=item_id)) if response.status_code == 200: return True except sandboxapi.SandboxError: pass return False
<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_available(self): """Determine if the Cuckoo Sandbox API servers are alive or in maintenance mode. :rtype: bool :return: True if service is available, False otherwise. """
# if the availability flag is raised, return True immediately. # NOTE: subsequent API failures will lower this flag. we do this here # to ensure we don't keep hitting Cuckoo with requests while # availability is there. if self.server_available: return True # otherwise, we have to check with the cloud. else: try: response = self._request("cuckoo/status") # we've got cuckoo. if response.status_code == 200: self.server_available = True return True except sandboxapi.SandboxError: pass self.server_available = False return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def queue_size(self): """Determine Cuckoo sandbox queue length There isn't a built in way to do this like with Joe :rtype: int :return: Number of submissions in sandbox queue. """
response = self._request("tasks/list") tasks = json.loads(response.content.decode('utf-8'))["tasks"] return len([t for t in tasks if t['status'] == 'pending'])
<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_available(self): """Determine if the Joe Sandbox API server is alive. :rtype: bool :return: True if service is available, False otherwise. """
# if the availability flag is raised, return True immediately. # NOTE: subsequent API failures will lower this flag. we do this here # to ensure we don't keep hitting Joe with requests while availability # is there. if self.server_available: return True # otherwise, we have to check with the cloud. else: try: self.server_available = self.jbx.server_online() return self.server_available except jbxapi.JoeException: pass self.server_available = False return False
<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_isolated_cpus(): """Get the list of isolated CPUs. Return a sorted list of CPU identifiers, or return None if no CPU is isolated. """
# The cpu/isolated sysfs was added in Linux 4.2 # (commit 59f30abe94bff50636c8cad45207a01fdcb2ee49) path = sysfs_path('devices/system/cpu/isolated') isolated = read_first_line(path) if isolated: return parse_cpu_list(isolated) cmdline = read_first_line(proc_path('cmdline')) if cmdline: match = re.search(r'\bisolcpus=([^ ]+)', cmdline) if match: isolated = match.group(1) return parse_cpu_list(isolated) return 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 has_same_unique_benchmark(self): "True if all suites have one benchmark with the same name" if any(len(suite) > 1 for suite in self.suites): return False names = self.suites[0].get_benchmark_names() return all(suite.get_benchmark_names() == names for suite in self.suites[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 send_message(message, params, site, logger): """Send a message to the Sentry server"""
client.capture( 'Message', message=message, params=tuple(params), data={ 'site': site, 'logger': logger, }, )
<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_command_line_args(): """CLI command line arguments handling"""
parser = argparse.ArgumentParser(description='Send logs to Django Sentry.') parser.add_argument('--sentryconfig', '-c', default=None, help='A configuration file (.ini, .yaml) of some ' 'Sentry integration to extract the Sentry DSN from') parser.add_argument('--sentrydsn', '-s', default="", help='The Sentry DSN string (overrides -c)') parser.add_argument('--daemonize', '-d', default=False, action='store_const', const=True, help='Run this script in background') parser.add_argument('--follow', '-f', default="all", help='Which logs to follow, default ALL') parser.add_argument('--nginxerrorpath', '-n', default=None, help='Nginx error log path') return parser.parse_args()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_arguments(args): """Deal with arguments passed on the command line"""
if args.sentryconfig: print('Parsing DSN from %s' % args.sentryconfig) os.environ['SENTRY_DSN'] = parse_sentry_configuration(args.sentryconfig) if args.sentrydsn: print('Using the DSN %s' % args.sentrydsn) os.environ['SENTRY_DSN'] = args.sentrydsn if args.nginxerrorpath: print('Using the Nginx error log path %s' % args.nginxerrorpath) os.environ['NGINX_ERROR_PATH'] = args.nginxerrorpath from ..conf import settings # noqa; pylint: disable=unused-variable if args.daemonize: print('Running process in background') from ..daemonize import create_daemon create_daemon()
<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_sentry_configuration(filename): """Parse Sentry DSN out of an application or Sentry configuration file"""
filetype = os.path.splitext(filename)[-1][1:].lower() if filetype == 'ini': # Pyramid, Pylons config = ConfigParser() config.read(filename) ini_key = 'dsn' ini_sections = ['sentry', 'filter:raven'] for section in ini_sections: if section in config: print('- Using value from [{section}]:[{key}]' .format(section=section, key=ini_key)) try: return config[section][ini_key] except KeyError: print('- Warning: Key "{key}" not found in section ' '[{section}]'.format(section=section, key=ini_key)) raise SystemExit('No DSN found in {file}. Tried sections [{sec_list}]' .format( file=filename, sec_list='], ['.join(ini_sections), )) elif filetype == 'py': # Django, Flask, Bottle, ... raise SystemExit('Parsing configuration from pure Python (Django,' 'Flask, Bottle, etc.) not implemented yet.') else: raise SystemExit('Configuration file type not supported for parsing: ' '%s' % filetype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_file(filename): """Read the contents of a file located relative to setup.py"""
with open(join(abspath(dirname(__file__)), filename)) as file: return file.read()
<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(self, line): """Parse a line of the Nginx error log"""
csv_list = line.split(",") date_time_message = csv_list.pop(0).split(" ", 2) otherinfo = dict() for item in csv_list: key_value_pair = item.split(":", 1) key = key_value_pair[0].strip() if len(key_value_pair) > 1: value = key_value_pair[1].strip() if not value: value = "-" else: value = "-" otherinfo[key] = value self.message = '%s\n' \ 'Date: %s\n' \ 'Time: %s\n' \ 'Request: %s\n' \ 'Referrer: %s\n' \ 'Server: %s\n' \ 'Client: %s\n' \ 'Host: %s\n' \ 'Upstream: %s\n' self.params = [ date_time_message[2], date_time_message[0], date_time_message[1], otherinfo.get("request", "-"), otherinfo.get("referrer", "-"), otherinfo.get("server", "-"), otherinfo.get("client", "-"), otherinfo.get("host", "-"), otherinfo.get("upstream", "-"), ] self.site = otherinfo.get("referrer", "-")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_json(self): """ Ensure that the checksum matches. """
if not hasattr(self, 'guidance_json'): return False checksum = self.guidance_json.get('checksum') contents = self.guidance_json.get('db') hash_key = ("{}{}".format(json.dumps(contents, sort_keys=True), self.assignment.endpoint).encode()) digest = hashlib.md5(hash_key).hexdigest() if not checksum: log.warning("Checksum on guidance not found. Invalidating file") return False if digest != checksum: log.warning("Checksum %s did not match actual digest %s", checksum, digest) return False return True
<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_tg(self): """ Try to grab the treatment group number for the student. If there is no treatment group number available, request it from the server. """
# Checks to see the student currently has a treatment group number. if not os.path.isfile(self.current_working_dir + LOCAL_TG_FILE): cur_email = self.assignment.get_student_email() log.info("Current email is %s", cur_email) if not cur_email: self.tg_id = -1 return EMPTY_MISUCOUNT_TGID_PRNTEDMSG tg_url = ("{}{}/{}{}" .format(TGSERVER, cur_email, self.assignment_name, TG_SERVER_ENDING)) try: log.info("Accessing treatment server at %s", tg_url) data = requests.get(tg_url, timeout=1).json() except IOError: data = {"tg": -1} log.warning("Failed to communicate to server", exc_info=True) if data.get("tg") is None: log.warning("Server returned back a bad treatment group ID.") data = {"tg": -1} with open(self.current_working_dir + LOCAL_TG_FILE, "w") as fd: fd.write(str(data["tg"])) tg_file = open(self.current_working_dir + LOCAL_TG_FILE, 'r') self.tg_id = int(tg_file.read())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prompt_with_prob(self, orig_response=None, prob=None): """Ask for rationale with a specific level of probability. """
# Disable opt-out. # if self.assignment.cmd_args.no_experiments: # log.info("Skipping prompt due to --no-experiments") # return "Skipped due to --no-experiments" if self.load_error: return 'Failed to read guidance config file' if hasattr(self.assignment, 'is_test'): log.info("Skipping prompt due to test mode") return "Test response" if prob is None: prob = self.prompt_probability if random.random() > prob: log.info("Did not prompt for rationale: Insufficient Probability") return "Did not prompt for rationale" with format.block(style="-"): rationale = prompt.explanation_msg(EXPLANTION_PROMPT, short_msg=CONFIRM_BLANK_EXPLANATION) if prob is None: # Reduce future prompt likelihood self.prompt_probability = 0 if orig_response: print('Thanks! Your original response was: {}'.format('\n'.join(orig_response))) return rationale
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch_requests(): """ Customize the cacerts.pem file that requests uses. Automatically updates the cert file if the contents are different. """
config.create_config_directory() ca_certs_file = config.CERT_FILE ca_certs_contents = requests.__loader__.get_data('requests/cacert.pem') should_write_certs = True if os.path.isfile(ca_certs_file): with open(ca_certs_file, 'rb') as f: existing_certs = f.read() if existing_certs != ca_certs_contents: should_write_certs = True print("Updating local SSL certificates") else: should_write_certs = False if should_write_certs: with open(ca_certs_file, 'wb') as f: f.write(ca_certs_contents) os.environ['REQUESTS_CA_BUNDLE'] = ca_certs_file
<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, messages): """Find all source files and return their complete contents. Source files are considered to be files listed self.assignment.src. If a certain source filepath is not a valid file (e.g. does not exist or is not a file), then the contents associated with that filepath will be an empty string. RETURNS: dict; a mapping of source filepath -> contents as strings. """
files = {} # TODO(albert): move this to AnalyticsProtocol if self.args.submit: files['submit'] = True for file in self.assignment.src: if not self.is_file(file): # TODO(albert): add an error message contents = '' log.warning('File {} does not exist'.format(file)) else: contents = self.read_file(file) log.info('Loaded contents of {} to send to server'.format(file)) files[file] = contents messages['file_contents'] = files
<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, messages): """Responsible for locking each test."""
if not self.args.lock: return format.print_line('~') print('Locking tests') print() for test in self.assignment.test_map.values(): log.info('Locking {}'.format(test.name)) test.lock(self._hash_fn)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pick_free_port(hostname=REDIRECT_HOST, port=0): """ Try to bind a port. Default=0 selects a free port. """
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((hostname, port)) # port=0 finds an open port except OSError as e: log.warning("Could not bind to %s:%s %s", hostname, port, e) if port == 0: print('Unable to find an open port for authentication.') raise AuthenticationException(e) else: return pick_free_port(hostname, 0) addr, port = s.getsockname() s.close() return port
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_token_post(server, data): """Try getting an access token from the server. If successful, returns the JSON response. If unsuccessful, raises an OAuthException. """
try: response = requests.post(server + TOKEN_ENDPOINT, data=data, timeout=TIMEOUT) body = response.json() except Exception as e: log.warning('Other error when exchanging code', exc_info=True) raise OAuthException( error='Authentication Failed', error_description=str(e)) if 'error' in body: log.error(body) raise OAuthException( error=body.get('error', 'Unknown Error'), error_description = body.get('error_description', '')) return body
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticate(cmd_args, endpoint='', force=False): """Returns an OAuth token that can be passed to the server for identification. If FORCE is False, it will attempt to use a cached token or refresh the OAuth token. """
server = server_url(cmd_args) network.check_ssl() access_token = None try: assert not force access_token = refresh_local_token(server) except Exception: print('Performing authentication') access_token = perform_oauth(get_code, cmd_args, endpoint) email = display_student_email(cmd_args, access_token) if not email: log.warning('Could not get login email. Try logging in again.') log.debug('Authenticated with access token={}'.format(access_token)) return access_token
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def notebook_authenticate(cmd_args, force=False, silent=True): """ Similiar to authenticate but prints student emails after all calls and uses a different way to get codes. If SILENT is True, it will suppress the error message and redirect to FORCE=True """
server = server_url(cmd_args) network.check_ssl() access_token = None if not force: try: access_token = refresh_local_token(server) except OAuthException as e: # Account for Invalid Grant Error During make_token_post if not silent: raise e return notebook_authenticate(cmd_args, force=True, silent=False) if not access_token: access_token = perform_oauth( get_code_via_terminal, cmd_args, copy_msg=NOTEBOOK_COPY_MESSAGE, paste_msg=NOTEBOOK_PASTE_MESSAGE) # Always display email email = display_student_email(cmd_args, access_token) if email is None and not force: return notebook_authenticate(cmd_args, force=True) # Token has expired elif email is None: # Did not get a valid token even after a fresh login log.warning('Could not get login email. You may have been logged out. ' ' Try logging in again.') return access_token
<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_student_email(cmd_args, endpoint=''): """Attempts to get the student's email. Returns the email, or None."""
log.info("Attempting to get student email") if cmd_args.local: return None access_token = authenticate(cmd_args, endpoint=endpoint, force=False) if not access_token: return None try: return get_info(cmd_args, access_token)['email'] except IOError as e: return 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_identifier(cmd_args, endpoint=''): """ Obtain anonmyzied identifier."""
student_email = get_student_email(cmd_args, endpoint) if not student_email: return "Unknown" return hashlib.md5(student_email.encode()).hexdigest()
<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_version(server, version, filename, timeout=SHORT_TIMEOUT): """Check for the latest version of OK and update accordingly."""
address = VERSION_ENDPOINT.format(server=server) print('Checking for software updates...') log.info('Existing OK version: %s', version) log.info('Checking latest version from %s', address) try: response = requests.get(address, timeout=timeout) response.raise_for_status() except (requests.exceptions.RequestException, requests.exceptions.BaseHTTPError) as e: print('Network error when checking for updates.') log.warning('Network error when checking version from %s: %s', address, str(e), stack_info=True) return False response_json = response.json() if not _validate_api_response(response_json): print('Error while checking updates: malformed server response') log.info('Malformed response from %s: %s', address, response.text) return False current_version = response_json['data']['results'][0]['current_version'] if current_version == version: print('OK is up to date') return True download_link = response_json['data']['results'][0]['download_link'] log.info('Downloading version %s from %s', current_version, download_link) try: response = requests.get(download_link, timeout=timeout) response.raise_for_status() except (requests.exceptions.RequestException, requests.exceptions.BaseHTTPError) as e: print('Error when downloading new version of OK') log.warning('Error when downloading new version of OK: %s', str(e), stack_info=True) return False log.info('Writing new version to %s', filename) zip_binary = response.content try: _write_zip(filename, zip_binary) except IOError as e: print('Error when downloading new version of OK') log.warning('Error writing to %s: %s', filename, str(e)) return False else: print('Updated to version: {}'.format(current_version)) log.info('Successfully wrote to %s', filename) return True
<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): """Implements the GradedTestCase interface."""
self.console.load(self.lines, setup=self.setup, teardown=self.teardown) return self.console.interpret()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unlock(self, unique_id_prefix, case_id, interact): """Unlocks the CodeCase. PARAMETERS: unique_id_prefix -- string; a prefix of a unique identifier for this Case, for purposes of analytics. case_id -- string; an identifier for this Case, for purposes of analytics. interact -- function; handles user interaction during the unlocking phase. """
print(self.setup.strip()) prompt_num = 0 current_prompt = [] try: for line in self.lines: if isinstance(line, str) and line: print(line) current_prompt.append(line) elif isinstance(line, CodeAnswer): prompt_num += 1 if not line.locked: print('\n'.join(line.output)) continue unique_id = self._construct_unique_id(unique_id_prefix, self.lines) line.output = interact(unique_id, case_id + ' > Prompt {}'.format(prompt_num), '\n'.join(current_prompt), line.output, line.choices) line.locked = False current_prompt = [] self.locked = False finally: self._sync_code()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def split_code(cls, code, PS1, PS2): """Splits the given string of code based on the provided PS1 and PS2 symbols. PARAMETERS: code -- str; lines of interpretable code, using PS1 and PS2 prompts PS1 -- str; first-level prompt symbol PS2 -- str; second-level prompt symbol RETURN: list; a processed sequence of lines corresponding to the input code. """
processed_lines = [] for line in textwrap.dedent(code).splitlines(): if not line or line.startswith(PS1) or line.startswith(PS2): processed_lines.append(line) continue assert len(processed_lines) > 0, 'code improperly formatted: {}'.format(code) if not isinstance(processed_lines[-1], CodeAnswer): processed_lines.append(CodeAnswer()) processed_lines[-1].update(line) return processed_lines
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sync_code(self): """Syncs the current state of self.lines with self.code, the serializable string representing the set of code. """
new_code = [] for line in self.lines: if isinstance(line, CodeAnswer): new_code.append(line.dump()) else: new_code.append(line) self.code = '\n'.join(new_code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _construct_unique_id(self, id_prefix, lines): """Constructs a unique ID for a particular prompt in this case, based on the id_prefix and the lines in the prompt. """
text = [] for line in lines: if isinstance(line, str): text.append(line) elif isinstance(line, CodeAnswer): text.append(line.dump()) return id_prefix + '\n' + '\n'.join(text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interpret(self): """Interprets the console on the loaded code. RETURNS: bool; True if the code passes, False otherwise. """
if not self._interpret_lines(self._setup): return False success = self._interpret_lines(self._code, compare_all=True) success &= self._interpret_lines(self._teardown) return success
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _interpret_lines(self, lines, compare_all=False): """Interprets the set of lines. PARAMTERS: lines -- list of str; lines of code compare_all -- bool; if True, check for no output for lines that are not followed by a CodeAnswer RETURNS: bool; True if successful, False otherwise. """
current = [] for line in lines + ['']: if isinstance(line, str): if current and (line.startswith(self.PS1) or not line): # Previous prompt ends when PS1 or a blank line occurs try: if compare_all: self._compare(CodeAnswer(), '\n'.join(current)) else: self.evaluate('\n'.join(current)) except ConsoleException: return False current = [] if line: print(line) line = self._strip_prompt(line) current.append(line) elif isinstance(line, CodeAnswer): assert len(current) > 0, 'Answer without a prompt' try: self._compare(line, '\n'.join(current)) except ConsoleException: return False current = [] return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump(self): """Serialize a test case to a string."""
result = list(self.output_lines()) if self.locked: result.append('# locked') if self.choices: for choice in self.choices: result.append('# choice: ' + choice) if self.explanation: result.append('# explanation: ' + self.explanation) return '\n'.join(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def output_lines(self): """Return a sequence of lines, suitable for printing or comparing answers. """
if self.exception: return [self.EXCEPTION_HEADERS[0], ' ...'] + self.exception_detail else: return self.output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prettyjson(json, indentation=' '): """Formats a Python-object into a string in a JSON like way, but uses triple quotes for multiline strings. PARAMETERS: json -- Python object that is serializable into json. indentation -- str; represents one level of indentation NOTES: All multiline strings are treated as raw strings. RETURNS: str; the formatted json-like string. """
if isinstance(json, int) or isinstance(json, float): return str(json) elif isinstance(json, str): if '\n' in json: return 'r"""\n' + dedent(json) + '\n"""' return repr(json) elif isinstance(json, list): lst = [indent(prettyjson(el, indentation), indentation) for el in json] return '[\n' + ',\n'.join(lst) + '\n]' elif isinstance(json, dict): pairs = [] for k, v in sorted(json.items()): k = prettyjson(k, indentation) v = prettyjson(v, indentation) pairs.append(indent(k + ': ' + v, indentation)) return '{\n' + ',\n'.join(pairs) + '\n}' else: raise exceptions.SerializeException('Invalid json type: {}'.format(json))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_contents(file_contents): """Ensures that all ipynb files in FILE_CONTENTS are valid JSON files."""
for name, contents in file_contents.items(): if os.path.splitext(name)[1] != '.ipynb': continue if not contents: return False try: json_object = json.loads(contents) except ValueError: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_for_save(filename, timeout=5): """Waits for FILENAME to update, waiting up to TIMEOUT seconds. Returns True if a save was detected, and False otherwise. """
modification_time = os.path.getmtime(filename) start_time = time.time() while time.time() < start_time + timeout: if (os.path.getmtime(filename) > modification_time and os.path.getsize(filename) > 0): return True time.sleep(0.2) return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def score(self, env=None, score_out=None): """ Run the scoring protocol. score_out -- str; a file name to write the point breakdown into. Returns: dict; maps score tag (str) -> points (float) """
messages = {} self.assignment.set_args( score=True, score_out=score_out, ) if env is None: import __main__ env = __main__.__dict__ self.run('scoring', messages, env=env) return messages['scoring']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_notebook(self): """ Saves the current notebook by injecting JavaScript to save to .ipynb file. """
try: from IPython.display import display, Javascript except ImportError: log.warning("Could not import IPython Display Function") print("Make sure to save your notebook before sending it to OK!") return if self.mode == "jupyter": display(Javascript('IPython.notebook.save_checkpoint();')) display(Javascript('IPython.notebook.save_notebook();')) elif self.mode == "jupyterlab": display(Javascript('document.querySelector(\'[data-command="docmanager:save"]\').click();')) print('Saving notebook...', end=' ') ipynbs = [path for path in self.assignment.src if os.path.splitext(path)[1] == '.ipynb'] # Wait for first .ipynb to save if ipynbs: if wait_for_save(ipynbs[0]): print("Saved '{}'.".format(ipynbs[0])) else: log.warning("Timed out waiting for IPython save") print("Could not automatically save \'{}\'".format(ipynbs[0])) print("Make sure your notebook" " is correctly named and saved before submitting to OK!".format(ipynbs[0])) return False else: print("No valid file sources found") return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """Run the LockingProtocol."""
args = parse_input() args.lock = True args.question = [] args.all = False args.timeout = 0 args.verbose = False args.interactive = False try: assign = assignment.load_assignment(args.config, args) msgs = messages.Messages() lock.protocol(args, assign).run(msgs) except (ex.LoadingException, ex.SerializeException) as e: log.warning('Assignment could not instantiate', exc_info=True) print('Error: ' + str(e).strip()) exit(1) except (KeyboardInterrupt, EOFError): log.info('Quitting...') else: assign.dump_tests()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_tree(zipf, src_directory, dst_directory): """Write all .py files in a source directory to a destination directory inside a zip archive. """
if not os.path.exists(src_directory): abort('Tree ' + src_directory + ' does not exist.') for root, _, files in os.walk(src_directory): for filename in files: if not filename.endswith(('.py', '.pem')): continue fullname = os.path.join(root, filename) arcname = fullname.replace(src_directory, dst_directory) zipf.write(fullname, arcname=arcname)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new_log(self): """Registers a new log so that calls to write will append to the log. RETURN: int; a unique ID to reference the log. """
log_id = self._num_logs self._logs[log_id] = [] self._num_logs += 1 return log_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 display_breakdown(scores, outfile=None): """Writes the point breakdown to `outfile` given a dictionary of scores. `outfile` should be a string. If `outfile` is None, write to stdout. RETURNS: dict; 'Total' -> finalized score (float) """
total = 0 outfile = open(outfile, 'w') if outfile else sys.stdout format.print_line('-') print('Point breakdown', file=outfile) for name, (score, max_score) in scores.items(): print(' {}: {}/{}'.format(name, score, max_score), file=outfile) total += score print(file=outfile) print('Score:', file=outfile) print(' Total: {}'.format(total), file=outfile) return {'Total': total}
<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, messages, env=None): """Score tests and print results. Tests are taken from self.assignment.specified_tests. A score breakdown by question and the total score are both printed. ENV is used by the programatic API for Python doctests only. """
if not self.args.score or self.args.testing: return format.print_line('~') print('Scoring tests') print() raw_scores = OrderedDict() for test in self.assignment.specified_tests: assert isinstance(test, sources_models.Test), 'ScoringProtocol received invalid test' log.info('Scoring test {}'.format(test.name)) # A hack that allows programmatic API users to plumb a custom # environment through to Python tests. # Use type to ensure is an actual OkTest and not a subclass if type(test) == ok_test_models.OkTest: score = test.score(env=env) else: score = test.score() raw_scores[test.name] = (score, test.points) messages['scoring'] = display_breakdown(raw_scores, self.args.score_out) print()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lock(key, text): """Locks the given text using the given key and returns the result"""
return hmac.new(key.encode('utf-8'), text.encode('utf-8')).hexdigest()
<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, messages): """Responsible for unlocking each test. The unlocking process can be aborted by raising a KeyboardInterrupt or an EOFError. RETURNS: dict; mapping of test name (str) -> JSON-serializable object. It is up to each test to determine what information is significant for analytics. """
if not self.args.unlock: return format.print_line('~') print('Unlocking tests') print() print('At each "{}", type what you would expect the output to be.'.format( self.PROMPT)) print('Type {} to quit'.format(self.EXIT_INPUTS[0])) print() for test in self.assignment.specified_tests: log.info('Unlocking test {}'.format(test.name)) self.current_test = test.name # Reset guidance explanation probability for every question self.guidance_util.prompt_probability = guidance.DEFAULT_PROMPT_PROBABILITY try: test.unlock(self.interact) except (KeyboardInterrupt, EOFError): try: # TODO(albert): When you use Ctrl+C in Windows, it # throws two exceptions, so you need to catch both # of them. Find a cleaner fix for this. print() print('-- Exiting unlocker --') except (KeyboardInterrupt, EOFError): pass print() break messages['unlock'] = self.analytics
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interact(self, unique_id, case_id, question_prompt, answer, choices=None, randomize=True): """Reads student input for unlocking tests until the student answers correctly. PARAMETERS: unique_id -- str; the ID that is recorded with this unlocking attempt. case_id -- str; the ID that is recorded with this unlocking attempt. question_prompt -- str; the question prompt answer -- list; a list of locked lines in a test case answer. choices -- list or None; a list of choices. If None or an empty list, signifies the question is not multiple choice. randomize -- bool; if True, randomizes the choices on first invocation. DESCRIPTION: Continually prompt the student for an answer to an unlocking question until one of the folliwng happens: 1. The student supplies the correct answer, in which case the supplied answer is returned 2. The student aborts abnormally (either by typing 'exit()' or using Ctrl-C/D. In this case, return None Correctness is determined by the verify method. RETURNS: list; the correct solution (that the student supplied). Each element in the list is a line of the correct output. """
if randomize and choices: choices = random.sample(choices, len(choices)) correct = False while not correct: if choices: assert len(answer) == 1, 'Choices must have 1 line of output' choice_map = self._display_choices(choices) question_timestamp = datetime.now() input_lines = [] for line_number, line in enumerate(answer): if len(answer) == 1: prompt = self.PROMPT else: prompt = '(line {}){}'.format(line_number + 1, self.PROMPT) student_input = format.normalize(self._input(prompt)) self._add_history(student_input) if student_input in self.EXIT_INPUTS: raise EOFError if choices and student_input in choice_map: student_input = choice_map[student_input] correct_answer = self._verify_student_input(student_input, line) if correct_answer: input_lines.append(correct_answer) else: input_lines.append(student_input) break else: correct = True tg_id = -1 misU_count_dict = {} rationale = "Unknown - Default Value" if not correct: guidance_data = self.guidance_util.show_guidance_msg(unique_id, input_lines, self.hash_key) misU_count_dict, tg_id, printed_msg, rationale = guidance_data else: rationale = self.guidance_util.prompt_with_prob() print("-- OK! --") printed_msg = ["-- OK! --"] self.analytics.append({ 'id': unique_id, 'case_id': case_id, 'question timestamp': self.unix_time(question_timestamp), 'answer timestamp': self.unix_time(datetime.now()), 'prompt': question_prompt, 'answer': input_lines, 'correct': correct, 'treatment group id': tg_id, 'rationale': rationale, 'misU count': misU_count_dict, 'printed msg': printed_msg }) print() return input_lines
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _verify_student_input(self, student_input, locked): """If the student's answer is correct, returns the normalized answer. Otherwise, returns None. """
guesses = [student_input] try: guesses.append(repr(ast.literal_eval(student_input))) except Exception: pass if student_input.title() in self.SPECIAL_INPUTS: guesses.append(student_input.title()) for guess in guesses: if self._verify(guess, locked): return guess
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _display_choices(self, choices): """Prints a mapping of numbers to choices and returns the mapping as a dictionary. """
print("Choose the number of the correct choice:") choice_map = {} for i, choice in enumerate(choices): i = str(i) print('{}) {}'.format(i, format.indent(choice, ' ' * (len(i) + 2)).strip())) choice = format.normalize(choice) choice_map[i] = choice return choice_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 timed(timeout, fn, args=(), kargs={}): """For a nonzero timeout, evaluates a call expression in a separate thread. If the timeout is 0, the expression is evaluated in the main thread. PARAMETERS: fn -- function; Python function to be evaluated args -- tuple; positional arguments for fn kargs -- dict; keyword arguments for fn timeout -- int; number of seconds before timer interrupt RETURN: Result of calling fn(*args, **kargs). RAISES: Timeout -- if thread takes longer than timeout to execute Error -- if calling fn raises an error, raise it """
if timeout == 0: return fn(*args, **kargs) submission = __ReturningThread(fn, args, kargs) submission.start() submission.join(timeout) if submission.is_alive(): raise exceptions.Timeout(timeout) if submission.error is not None: raise submission.error return submission.result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def grade(self, question, env=None, skip_locked_cases=False): """Runs tests for a particular question. The setup and teardown will always be executed. question -- str; a question name (as would be entered at the command line env -- dict; an environment in which to execute the tests. If None, uses the environment of __main__. The original dictionary is never modified; each test is given a duplicate of env. skip_locked_cases -- bool; if False, locked cases will be tested Returns: dict; maps question names (str) -> results (dict). The results dictionary contains the following fields: - "passed": int (number of test cases passed) - "failed": int (number of test cases failed) - "locked": int (number of test cases locked) """
if env is None: import __main__ env = __main__.__dict__ messages = {} tests = self._resolve_specified_tests([question], all_tests=False) for test in tests: try: for suite in test.suites: suite.skip_locked_cases = skip_locked_cases suite.console.skip_locked_cases = skip_locked_cases suite.console.hash_key = self.name except AttributeError: pass test_name = tests[0].name grade(tests, messages, env) return messages['grading'][test_name]
<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, messages): """Returns some analytics about this autograder run."""
statistics = {} statistics['time'] = str(datetime.now()) statistics['time-utc'] = str(datetime.utcnow()) statistics['unlock'] = self.args.unlock if self.args.question: statistics['question'] = [t.name for t in self.assignment.specified_tests] statistics['requested-questions'] = self.args.question if self.args.suite: statistics['requested-suite'] = self.args.suite if self.args.case: statistics['requested-case'] = self.args.case messages['analytics'] = statistics self.log_run(messages)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_run(self, messages): """Record this run of the autograder to a local file. If the student does not specify what question(s) the student is running ok against, assume that the student is aiming to work on the question with the first failed test. If a student finishes questions 1 - N-1, the first test to fail will be N. """
# Load the contents of the local analytics file history = self.read_history() history['all_attempts'] += 1 # List of question names that the student asked to have graded questions = messages['analytics'].get('question', []) # The output of the grading protocol grading = messages.get('grading') # Attempt to figure out what the student is currently implementing if not questions and grading: # If questions are unspecified by the user, use the first failed test failed = first_failed_test(self.assignment.specified_tests, grading) logging.info('First failed test: {}'.format(failed)) if failed: questions = [failed] # Update question correctness status from previous attempts for saved_q, details in history['questions'].items(): finished = details['solved'] if not finished and saved_q in grading: scoring = grading[saved_q] details['solved'] = is_correct(scoring) # The question(s) that the student is testing right now. history['question'] = questions # Update attempt and correctness counts for the graded questions for question in questions: detail = history['questions'] if grading and question in grading: scoring = is_correct(grading[question]) else: scoring = False # Update attempt counts or initialize counts if question in history['questions']: q_info = detail[question] if grading and question in grading: if q_info['solved'] != True: q_info['solved'] = scoring else: continue # Already solved. Do not change total q_info['attempts'] += 1 else: detail[question] = { 'attempts': 1, 'solved': scoring } logging.info('Attempt %d for Question %s : %r', history['questions'], question, scoring) with open(self.ANALYTICS_FILE, 'wb') as f: log.info('Saving history to %s', self.ANALYTICS_FILE) pickle.dump(history, f) os.fsync(f) messages['analytics']['history'] = history
<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_ssl(): """Attempts to import SSL or raises an exception."""
try: import ssl except: log.warning('Error importing SSL module', stack_info=True) print(SSL_ERROR_MESSAGE) sys.exit(1) else: log.info('SSL module is available') return ssl
<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, messages, env=None): """Run gradeable tests and print results and return analytics. RETURNS: dict; a mapping of test name -> JSON-serializable object. It is up to each test to determine what kind of data it wants to return as significant for analytics. However, all tests must include the number passed, the number of locked tests and the number of failed tests. """
if self.args.score or self.args.unlock or self.args.testing: return tests = self.assignment.specified_tests for test in tests: if self.args.suite and hasattr(test, 'suites'): test.run_only = int(self.args.suite) try: suite = test.suites[int(self.args.suite) - 1] except IndexError as e: sys.exit(('python3 ok: error: ' 'Suite number must be valid.({})'.format(len(test.suites)))) if self.args.case: suite.run_only = [int(c) for c in self.args.case] grade(tests, messages, env, verbose=self.args.verbose)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def coerce(self, value): """Subclasses should override this method for type coercion. Default version will simply return the argument. If the argument is not valid, a SerializeException is raised. For primitives like booleans, ints, floats, and strings, use this default version to avoid unintended type conversions."""
if not self.is_valid(value): raise ex.SerializeException('{} is not a valid value for ' 'type {}'.format(value, self.__class__.__name__)) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_json(self, value): """Subclasses should override this method for JSON encoding."""
if not self.is_valid(value): raise ex.SerializeException('Invalid value: {}'.format(value)) return value
<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_content_encoding(self, response_headers, response_data): """ Parses a response that contains Content-Encoding to retrieve response_data """
if response_headers['content-encoding'] == 'gzip': buf = StringIO.StringIO(response_data) zipbuf = gzip.GzipFile(fileobj=buf) response_data = zipbuf.read() elif response_headers['content-encoding'] == 'deflate': data = StringIO.StringIO(zlib.decompress(response_data)) response_data = data.read() else: raise errors.TestError( 'Received unknown Content-Encoding', { 'content-encoding': str(response_headers['content-encoding']), 'function': 'http.HttpResponse.parse_content_encoding' }) return 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 process_response(self): """ Parses an HTTP response after an HTTP request is sent """
split_response = self.response.split(self.CRLF) response_line = split_response[0] response_headers = {} response_data = None data_line = None for line_num in range(1, len(split_response[1:])): # CRLF represents the start of data if split_response[line_num] == '': data_line = line_num + 1 break else: # Headers are all split by ':' header = split_response[line_num].split(':', 1) if len(header) != 2: raise errors.TestError( 'Did not receive a response with valid headers', { 'header_rcvd': str(header), 'function': 'http.HttpResponse.process_response' }) response_headers[header[0].lower()] = header[1].lstrip() if 'set-cookie' in response_headers.keys(): try: cookie = Cookie.SimpleCookie() cookie.load(response_headers['set-cookie']) except Cookie.CookieError as err: raise errors.TestError( 'Error processing the cookie content into a SimpleCookie', { 'msg': str(err), 'set_cookie': str(response_headers['set-cookie']), 'function': 'http.HttpResponse.process_response' }) # if the check_for_cookie is invalid then we don't save it if self.check_for_cookie(cookie) is False: raise errors.TestError( 'An invalid cookie was specified', { 'set_cookie': str(response_headers['set-cookie']), 'function': 'http.HttpResponse.process_response' }) else: self.cookiejar.append((cookie, self.dest_addr)) if data_line is not None and data_line < len(split_response): response_data = self.CRLF.join(split_response[data_line:]) # if the output headers say there is encoding if 'content-encoding' in response_headers.keys(): response_data = self.parse_content_encoding( response_headers, response_data) if len(response_line.split(' ', 2)) != 3: raise errors.TestError( 'The HTTP response line returned the wrong args', { 'response_line': str(response_line), 'function': 'http.HttpResponse.process_response' }) try: self.status = int(response_line.split(' ', 2)[1]) except ValueError: raise errors.TestError( 'The status num of the response line isn\'t convertable', { 'msg': 'This may be an HTTP 1.0 \'Simple Req\\Res\', it \ doesn\'t have HTTP headers and FTW will not parse these', 'response_line': str(response_line), 'function': 'http.HttpResponse.process_response' }) self.status_msg = response_line.split(' ', 2)[2] self.version = response_line.split(' ', 2)[0] self.response_line = response_line self.headers = response_headers self.data = 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 send_request(self, http_request): """ Send a request and get response """
self.request_object = http_request self.build_socket() self.build_request() try: self.sock.send(self.request) except socket.error as err: raise errors.TestError( 'We were unable to send the request to the socket', { 'msg': err, 'function': 'http.HttpUA.send_request' }) finally: self.get_response()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_socket(self): """ Generate either an HTTPS or HTTP socket """
try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.settimeout(self.SOCKET_TIMEOUT) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Check if TLS if self.request_object.protocol == 'https': self.sock = ssl.wrap_socket(self.sock, ciphers=self.CIPHERS) self.sock.connect( (self.request_object.dest_addr, self.request_object.port)) except socket.error as msg: raise errors.TestError( 'Failed to connect to server', { 'host': self.request_object.dest_addr, 'port': self.request_object.port, 'proto': self.request_object.protocol, 'message': msg, 'function': 'http.HttpUA.build_socket' })