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 ...
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...
<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_...
# 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.ami...
<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 ...
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]]) 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 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 indi...
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 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 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 star...
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_fl...
<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. Th...
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] = Fa...
<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...
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. Paramet...
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.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 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 i...
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: ...
<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 struc...
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 stru...
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 im...
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 inse...
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.rav...
<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...
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).ast...
<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. Paramet...
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: face...
<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...
# ------------------------------------------------------------------------- # 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: ali...
<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 :pa...
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...
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 ...
<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 patte...
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) ...
<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 :p...
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...
@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, **...
<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() ...
<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. ...
<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): """R...
with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency, thread_name_prefix='T') as executor: try: results = [] pending_futures = set() done_futures = set() finished_futures = [] progress_t...
<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 p...
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(): ...
<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 t...
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: ...
<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, EObj...
<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...
<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...
# 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': respons...
<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 ...
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"] ...
<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:...
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, Fals...
# 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 #...
<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 ...
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 # ot...
<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 cmdl...
<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 su...
<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_argu...
<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: ...
<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: ...
<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_p...
<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()) ...
<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_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 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.assignme...
<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 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 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 ce...
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 = '' lo...
<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 authe...
<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 OAuthExce...
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_desc...
<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 a...
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 = dis...
<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...
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: rai...
<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 Non...
<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() exce...
<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 ...
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): ...
<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 interpretabl...
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) ...
<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 pro...
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...
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: ...
<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.expl...
<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: jso...
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 ...
<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 sco...
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": disp...
<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...
<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) ...
<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` ...
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)...
<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 ...
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 rece...
<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: dic...
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...
<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 answe...
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) ...
<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._verif...
<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.n...
<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 eva...
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 submissi...
<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 -...
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 = sk...
<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[...
<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 aga...
# 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 g...
<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 obje...
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: su...
<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 val...
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(re...
<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[...
<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', { ...
<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': sel...