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 filter(self): """Generate a filtered query from request parameters. :returns: Filtered SQLALchemy query """
argmap = { filter.label or label: filter.field for label, filter in self.filters.items() } args = self.opts.parser.parse(argmap) query = self.query if self.query is not None else self.opts.query for label, filter in self.filters.items(): 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 _check_min_density(self, min_density): """Validator to ensure proper usage."""
if min_density is None: self._min_density = -np.Inf elif (isinstance(min_density, float) and (0.0 <= min_density < 1.0)): self._min_density = min_density else: raise ValueError('min_density must be float and be >=0.0 and < 1.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 _not_empty(self, view, slice_): """Checks if the density is too low. """
img2d = self._get_axis(self._image, view, slice_) return (np.count_nonzero(img2d) / img2d.size) > self._min_density
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sample_slices_in_dim(self, view, num_slices, non_empty_slices): """Samples the slices in the given dimension according the chosen strategy."""
if self._sampling_method == 'linear': return self._linear_selection(non_empty_slices=non_empty_slices, num_slices=num_slices) elif self._sampling_method == 'percentage': return self._percent_selection(non_empty_slices=non_empty_slices) elif self._sampling_method == 'cal...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _linear_selection(self, non_empty_slices, num_slices): """Selects linearly spaced slices in given"""
num_non_empty = len(non_empty_slices) # # trying to skip 5% slices at the tails (bottom clipping at 0) # skip_count = max(0, np.around(num_non_empty * 0.05).astype('int16')) # # only when possible # if skip_count > 0 and (num_non_empty - 2 * skip_count > num_slices): #...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _percent_selection(self, non_empty_slices): """Chooses slices at a given percentage between the first and last non-empty slice."""
return np.around(self._sampler * len(non_empty_slices) / 100).astype('int64')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _selection_by_callable(self, view, num_slices, non_empty_slices): """Returns all the slices selected by the given callable."""
selected = [sl for sl in non_empty_slices if self._sampler(self._get_axis(self._image, view, sl))] return selected[:num_slices]
<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_slices(self, extended=False): """Generator over all the slices selected, each time returning a cross-section. Parameters extended : bool Flag to return j...
for dim, slice_num in self._slices: yield self._get_axis(self._image, dim, slice_num, extended=extended)
<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_slices_multi(self, image_list, extended=False): """Returns the same cross-section from the multiple images supplied. All images must be of the same shape...
# ensure all the images have the same shape for img in image_list: if img.shape != self._image.shape: raise ValueError('Supplied images are not compatible with this class. ' 'They must have the shape: {}'.format(self._image_shape)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_grid_of_axes(self, bounding_rect=cfg.bounding_rect_default, num_rows=cfg.num_rows_per_view_default, num_cols=cfg.num_cols_grid_default, axis_pad=cfg.axi...
axes_in_grid = list() extents = self._compute_cell_extents_grid(bounding_rect=bounding_rect, num_cols=num_cols, num_rows=num_rows, axis_pad=axis_pad) for cell_ext in extents: ax_cell...
<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_imshow_objects(self): """Turns off all the x and y axes in each Axis"""
# uniform values for initial image can cause weird behaviour with normalization # as imshow.set_data() does not automatically update the normalization!! # using random data is a better choice random_image = np.random.rand(20, 20) self.images = [None] * len(self.flat_grid)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attach(self, image_in, sampler=None, show=True): """Attaches the relevant cross-sections to each axis. Parameters attach_image : ndarray The image to be atta...
if len(image_in.shape) < 3: raise ValueError('Image must be atleast 3D') # allowing the choice of new sampling for different invocations. if sampler is None: temp_sampler = self.sampler else: temp_sampler = sampler slicer = SlicePicker(imag...
<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_visible(self, visibility, grid_index=None): """Sets the visibility property of all axes."""
if grid_index is None: for ax in self.flat_grid: ax.set_visible(visibility) else: if grid_index < 0 or grid_index >= len(self.grids): raise IndexError('Valid indices : 0 to {}'.format(len(self.grids) - 1)) for ax in self.grids[grid_in...
<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(self, annot=None, output_path=None): """Saves the collage to disk as an image. Parameters annot : str text to annotate the figure with a super title out...
if annot is not None: self.fig.suptitle(annot, backgroundcolor='black', color='g') if output_path is not None: output_path = output_path.replace(' ', '_') # TODO improve bbox calculations to include ONLY the axes from collage # and nothing else ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear(self): """Clears all the axes to start fresh."""
for ax in self.flat_grid: for im_h in ax.findobj(AxesImage): im_h.remove()
<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_image(self, image_nD): """Sanity checks on the image data"""
self.input_image = load_image_from_disk(image_nD) if len(self.input_image.shape) < 3: raise ValueError('Input image must be atleast 3D') if np.count_nonzero(self.input_image) == 0: raise ValueError('Input image is completely filled with zeros! ' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_fixed_dim(self, fixed_dim=-1): """Makes note of which dimension needs to be fixed, defaulting to last."""
if fixed_dim in [-1, None, 'last']: fixed_dim = len(self.input_image.shape) - 1 # last dimension if int(fixed_dim)!=fixed_dim or \ fixed_dim > len(self.input_image.shape) or \ fixed_dim < -1: raise ValueError('invalid value for the dimension to be fixe...
<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_carpet(self, rescale_data): """ Constructs the carpet from the input image. Optional rescaling of the data. """
self.carpet = self._unroll_array(self.input_image, self.fixed_dim) if rescale_data: self.carpet = row_wise_rescale(self.carpet)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show(self, clustered=False, ax_carpet=None, label_x_axis='time point', label_y_axis='voxels/ROI'): """ Displays the carpet in the given axis. Parameters clus...
if clustered is True and self._carpet_clustered is False: print('You must run .cluster_rows_in_roi() ' 'before being able to show clustered carpet!') return if ax_carpet is None: self.ax_carpet = plt.gca() else: if not isinstan...
<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(self, output_path=None, title=None): """Saves the current figure with carpet visualization to disk. Parameters output_path : str Path to where the figur...
try: save_figure(self.fig, output_path=output_path, annot=title) except: print('Unable to save the figure to disk! \nException: ') traceback.print_exc()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cluster_rows_in_roi(self, roi_mask=None, num_clusters_per_roi=5, metric='minkowski'): """Clusters the data within all the ROIs specified in a mask. Parameter...
self._set_roi_mask(roi_mask) try: clusters = [self._summarize_in_roi(self.roi_mask == label, num_clusters_per_roi, metric=metric) for label in self.roi_list] self.clustered_carpet = 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 _set_roi_mask(self, roi_mask): """Sets a new ROI mask."""
if isinstance(roi_mask, np.ndarray): # not (roi_mask is None or roi_mask=='auto'): self._verify_shape_compatibility(roi_mask, 'ROI set') self.roi_mask = roi_mask self.roi_list = np.unique(roi_mask.flatten()) np.setdiff1d(self.roi_list, cf...
<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_clusters(self, matrix, num_clusters_per_roi, metric): """clusters a given matrix by into specified number of clusters according to given metric"""
from scipy.cluster.hierarchy import fclusterdata # maxclust needed to ensure t is interpreted as # clusters in heirarchical clustering group_ids = fclusterdata(matrix, metric=metric, t=num_clusters_per_roi, criterion='maxclust') group_set = np.unique(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 _apply_mask(self, roi_mask): """Removes voxels outside the given mask or ROI set."""
# TODO ensure compatible with input image # - must have < N dim and same size in moving dims. rows_to_delete = list() # to allow for additional masks to be applied in the future if isinstance(roi_mask, np.ndarray): # not (roi_mask is None or roi_mask=='auto'): ...
<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_shape_compatibility(self, img, img_type): """Checks mask shape against input image shape."""
if self.input_image.shape[:-1] != img.shape: raise ValueError('Shape of the {} ({}) is not compatible ' 'with input image shape: {} ' ''.format(img_type, img.shape, self.input_image.shape[:-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 verify_email(request, code, redirect_to=None): """Verifies an account activation code a user received by e-mail. Requires Messages Django Contrib. :param Req...
success = False valid_code = EmailConfirmation.is_valid(code) if valid_code: valid_code.activate() success = True if success: messages.success(request, SIGNUP_VERIFY_EMAIL_SUCCESS_TEXT, 'success') else: messages.error(request, SIGNUP_VERIFY_EMAIL_ERROR_TEXT, 'dange...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unpack_fixed8(src): """Get a FIXED8 value."""
dec_part = unpack_ui8(src) int_part = unpack_ui8(src) return int_part + dec_part / 256
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unpack_float16(src): """Read and unpack a 16b float. The structure is: - 1 bit for the sign . 5 bits for the exponent, with an exponent bias of 16 - 10 bits ...
bc = BitConsumer(src) sign = bc.u_get(1) exponent = bc.u_get(5) mantissa = bc.u_get(10) exponent -= 16 mantissa /= 2 ** 10 num = (-1 ** sign) * mantissa * (10 ** exponent) return num
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def u_get(self, quant): """Return a number using the given quantity of unsigned bits."""
if not quant: return bits = [] while quant: if self._count == 0: byte = self.src.read(1) number = struct.unpack("<B", byte)[0] self._bits = bin(number)[2:].zfill(8) self._count = 8 if quant > sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def s_get(self, quant): """Return a number using the given quantity of signed bits."""
if quant < 2: # special case, just return that unsigned value # quant can also be 0 return self.u_get(quant) sign = self.u_get(1) raw_number = self.u_get(quant - 1) if sign == 0: # positive, simplest case number = raw_number ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fb_get(self, quant, fb=16): """Return a fixed bit number quant: number of bits to read fb: number of bits in the integer and decimal part of the output defau...
raw_number = self.s_get(quant) if quant == 1: # special case, just return that unsigned value return raw_number return raw_number / (1 << fb)
<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_freesurfer_cmap(vis_type): """Provides different colormaps for different visualization types."""
if vis_type in ('cortical_volumetric', 'cortical_contour'): LUT = get_freesurfer_cortical_LUT() cmap = ListedColormap(LUT) elif vis_type in ('labels_volumetric', 'labels_contour'): black = np.array([0, 0, 0, 1]) cmap = plt.get_cmap('hsv') # TODO using more than ...
<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_rsa_key(bits=2048, keyfile=None, format='PEM', passphrase=None): """ Generate a new RSA key with the specified key size. :param int bits: bit size of ...
if passphrase and format != 'PEM': raise Exception( "passphrase is only supported for PEM encoded private keys") rsakey = RSA.generate(bits) if passphrase and isinstance(passphrase, collections.Callable): passphrase = passphrase() output = rsakey.exportKey(format=format, pas...
<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_csr(key, dn, csrfilename=None, attributes=None): """ Generates a Certificate Signing Request for a given key. :param Crypto.PublicKey.RSA._RSAobj key:...
certreqInfo = rfc2314.CertificationRequestInfo() certreqInfo.setComponentByName('version', rfc2314.Version(0)) certreqInfo.setComponentByName('subject', _build_dn(dn)) certreqInfo.setComponentByName('subjectPublicKeyInfo', _build_subject_publickey_info(key)) attrp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def respond_for(self, view_function, args, kwargs): """Returns a response for the given view & args."""
request = args[0] form = self.get_requested_form(request) if form.is_valid(): result = self.handle_form_valid(request, form) if result: return result self.update_request(request, form) return view_function(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_request(self, request, form): """Updates Request object with flows forms."""
forms_key = '%s_forms' % self.flow_type # Use ordered forms dict in case _formNode wants to fetch the first defined. flow_dict = OrderedDict() try: flow_dict = request.sitegate[forms_key] except AttributeError: request.sitegate = {} except KeyErr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def login_generic(request, username, password): """Helper method. Generic login with username and password."""
user = authenticate(username=username, password=password) if user is not None and user.is_active: login(request, user) 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 get_arg_or_attr(self, name, default=None): """Returns flow argument, as provided with sitegate decorators or attribute set as a flow class attribute or defau...
if name in self.flow_args: return self.flow_args[name] try: return getattr(self, name) except AttributeError: return default
<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_requested_form(self, request): """Returns an instance of a form requested."""
flow_name = self.get_flow_name() flow_key = '%s_flow' % self.flow_type flow_enabled = self.enabled form_data = None if (flow_enabled and request.method == 'POST' and request.POST.get(flow_key, False) and request.POST[flow_key] == flow_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 init_form(self, form_data, widget_attrs=None, template=None): """Constructs, populates and returns a form."""
form = self.form(data=form_data) form.template = template # Attach flow attribute to have access from flow forms (usually to call get_arg_or_attr()) form.flow = self if widget_attrs is not None: set_form_widgets_attrs(form, widget_attrs) return form
<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_path(scraper): """ Determine the file name for the JSON log. """
return os.path.join(scraper.config.data_path, '%s.jsonlog' % scraper.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 make_logger(scraper): """ Create two log handlers, one to output info-level ouput to the console, the other to store all logging in a JSON file which will la...
logger = logging.getLogger('') logger.setLevel(logging.DEBUG) requests_log = logging.getLogger("requests") requests_log.setLevel(logging.WARNING) json_handler = logging.FileHandler(log_path(scraper)) json_handler.setLevel(logging.DEBUG) json_formatter = jsonlogger.JsonFormatter(make_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 initiate(self, sa): """Initiate an SA. :param sa: the SA to initiate :type sa: dict :return: logs emitted by command, with `errmsg` given on failure :rtype: ...
response = self.handler.streamed_request("initiate", "control-log", sa) return self._result(*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 terminate(self, sa): """Terminate an SA. :param sa: the SA to terminate :type sa: dict :return: logs emitted by command, with `errmsg` given on failure :rtyp...
response = self.handler.streamed_request("terminate", "control-log", sa) return self._result(*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 list_sas(self, filters=None): """Retrieve active IKE_SAs and associated CHILD_SAs. :param filters: retrieve only matching IKE_SAs (optional) :type filters: d...
_, sa_list = self.handler.streamed_request("list-sas", "list-sa", filters) return sa_list
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_policies(self, filters=None): """Retrieve installed trap, drop and bypass policies. :param filters: retrieve only matching policies (optional) :type fil...
_, policy_list = self.handler.streamed_request("list-policies", "list-policy", filters) return policy_list
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_conns(self, filters=None): """Retrieve loaded connections. :param filters: retrieve only matching configuration names (optional) :type filters: dict :re...
_, connection_list = self.handler.streamed_request("list-conns", "list-conn", filters) return connection_list
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_certs(self, filters=None): """Retrieve loaded certificates. :param filters: retrieve only matching certificates (optional) :type filters: dict :return: ...
_, cert_list = self.handler.streamed_request("list-certs", "list-cert", filters) return cert_list
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _result(self, command_response, log=None): """Create a CommandResult for a request response. :param command_response: command request response :type command_...
if command_response["success"] == "yes": return CommandResult(True, None, log) else: return CommandResult(False, command_response["errmsg"], log)
<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, command, message=None): """Send command request with an optional message. :param command: command to send :type command: str :param message: me...
if message is not None: message = Message.serialize(message) packet = Packet.request(command, message) response = self._communicate(packet) if response.response_type != Packet.CMD_RESPONSE: raise SessionException( "Unexpected response type {type}...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def streamed_request(self, command, event_stream_type, message=None): """Send command request and collect and return all emitted events. :param command: command ...
result = [] if message is not None: message = Message.serialize(message) # subscribe to event stream packet = Packet.register_event(event_stream_type) response = self._communicate(packet) if response.response_type != Packet.EVENT_CONFIRM: raise...
<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(self): """Get next packet from transport. :return: parsed packet in a tuple with message type and payload :rtype: :py:class:`collections.namedtuple` ""...
raw_response = self.transport.receive() response = Packet.parse(raw_response) # FIXME if response.response_type == Packet.EVENT and response.event_type == "log": # queue up any debug log messages, and get next self.log_events.append(response) # do so...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _diff_image(slice1, slice2, abs_value=True, cmap='gray', **kwargs): """Computes the difference image"""
diff = slice1 - slice2 if abs_value: diff = np.abs(diff) return diff, cmap
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def diff_colormap(): "Custom colormap to map low values to black or another color." # bottom = plt.cm.copper(np.linspace(0., 1, 6)) black = np.atleast_2d([0., 0., 0., 1.]) bottom = np.repeat(black, 6, axis=0) middle = plt.cm.copper(np.linspace(0, 1, 250)) # remain = plt.cm.Reds(np.linspace(0, 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 check_bounding_rect(rect_pos): """Ensure the rect spec is valid."""
if not isinstance(rect_pos, Iterable): raise ValueError('rectangle spect must be a tuple of floats ' 'specifying (left, right, width, height)') left, bottom, width, height = rect_pos for val, name in zip((left, bottom, width, height), ('left', 'bo...
<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_num_slices(num_slices, img_shape=None, num_dims=3): """Ensures requested number of slices is valid. Atleast 1 and atmost the image size, if available "...
if not isinstance(num_slices, Iterable) or len(num_slices) == 1: num_slices = np.repeat(num_slices, num_dims) if img_shape is not None: if len(num_slices) != len(img_shape): raise ValueError('The number of dimensions requested is different from image.' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_int(num, num_descr='number', min_value=0, max_value=np.Inf): """Validation and typecasting."""
if not np.isfinite(num) or num < min_value or num > max_value: raise ValueError('{}={} is not finite or ' 'is not >= {} or ' 'is not < {}'.format(num_descr, num, min_value, max_value)) return int(num)
<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_image(img_spec, bkground_thresh, ensure_num_dim=3): """Image reader, with additional checks on size. Can optionally remove stray values close to zero (s...
img = load_image_from_disk(img_spec) if not np.issubdtype(img.dtype, np.floating): img = img.astype('float32') if ensure_num_dim == 3: img = check_image_is_3d(img) elif ensure_num_dim == 4: img = check_image_is_4d(img) return threshold_image(img, bkground_thresh)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_image_from_disk(img_spec): """Vanilla image loader."""
if isinstance(img_spec, str): if pexists(realpath(img_spec)): hdr = nib.load(img_spec) # trying to stick to an orientation hdr = nib.as_closest_canonical(hdr) img = hdr.get_data() else: raise IOError('Given path to image does not exist!')...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def threshold_image(img, bkground_thresh, bkground_value=0.0): """ Thresholds a given image at a value or percentile. Replacement value can be specified too. Par...
if bkground_thresh is None: return img if isinstance(bkground_thresh, str): try: thresh_perc = float(bkground_thresh.replace('%', '')) except: raise ValueError( 'percentile specified could not be parsed correctly ' ' - must be 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 row_wise_rescale(matrix): """ Row-wise rescale of a given matrix. For fMRI data (num_voxels x num_time_points), this would translate to voxel-wise normalizat...
if matrix.shape[0] <= matrix.shape[1]: raise ValueError('Number of voxels is less than the number of time points!! ' 'Are you sure data is reshaped correctly?') min_ = matrix.min(axis=1) range_ = matrix.ptp(axis=1) # ptp : peak to peak, max-min min_tile = np.tile(min_, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crop_to_extents(img1, img2, padding): """Crop the images to ensure both fit within the bounding box"""
beg_coords1, end_coords1 = crop_coords(img1, padding) beg_coords2, end_coords2 = crop_coords(img2, padding) beg_coords = np.fmin(beg_coords1, beg_coords2) end_coords = np.fmax(end_coords1, end_coords2) img1 = crop_3dimage(img1, beg_coords, end_coords) img2 = crop_3dimage(img2, beg_coords, en...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def crop_image(img, padding=5): "Crops an image or slice to its extents" if padding < 1: return img beg_coords, end_coords = crop_coords(img, padding) if len(img.shape) == 3: img = crop_3dimage(img, beg_coords, end_coords) elif len(img.shape) == 2: img = crop_2dimage(img, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crop_coords(img, padding): """Find coordinates describing extent of non-zero portion of image, padded"""
coords = np.nonzero(img) empty_axis_exists = np.any([len(arr) == 0 for arr in coords]) if empty_axis_exists: end_coords = img.shape beg_coords = np.zeros((1, img.ndim)).astype(int).flatten() else: min_coords = np.array([arr.min() for arr in coords]) max_coords = np.arra...
<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_sampler(sampler, image, image_shape, view_set, num_slices): """verifies the sampler requested is valid."""
if isinstance(sampler, str): sampler = sampler.lower() if sampler not in ['linear', ]: raise ValueError('Sampling strategy: {} not implemented.'.format(sampler)) out_sampler = sampler out_sampling_method = 'linear' elif isinstance(sampler, Iterable): if any(...
<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_username_max_len(): """Returns username maximum length as supported by Django. :rtype: int """
fields = [field for field in USER._meta.fields if field.name == 'username'] try: length = fields[0].max_length except IndexError: length = 30 return length
<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_env(self, config): """ Read environment variables based on the settings defined in the defaults. These are expected to be upper-case versions of the act...
for option, value in config.items(): env_name = 'SCRAPEKIT_%s' % option.upper() value = os.environ.get(env_name, value) config[option] = value return 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 _spawn(self): """ Initialize the queue and the threads. """
self.queue = Queue(maxsize=self.num_threads * 10) for i in range(self.num_threads): t = Thread(target=self._consume) t.daemon = True t.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _consume(self): """ Main loop for each thread, handles picking a task off the queue, processing it and notifying the queue that it is done. """
while True: try: task, args, kwargs = self.queue.get(True) task(*args, **kwargs) finally: self.queue.task_done()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put(self, task, args, kwargs): """ Add a new item to the queue. An item is a task and the arguments needed to call it. Do not call this directly, use Task.qu...
if self.num_threads == 0: return task(*args, **kwargs) if self.queue is None: self._spawn() self.queue.put((task, args, kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, *args, **kwargs): """ Queue a first item to execute, then wait for the queue to be empty before returning. This should be the default way of starti...
if self._source is not None: return self._source.run(*args, **kwargs) else: self.queue(*args, **kwargs) return self.wait()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chain(self, other_task): """ Add a chain listener to the execution of this task. Whenever an item has been processed by the task, the registered listener tas...
other_task._source = self self._listeners.append(ChainListener(other_task)) return other_task
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pipe(self, other_task): """ Add a pipe listener to the execution of this task. The output of this task is required to be an iterable. Each item in the iterab...
other_task._source = self self._listeners.append(PipeListener(other_task)) return other_task
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def client_auth(self): """Generate an XML element with client auth data populated."""
if not self._client_auth: self._client_auth = E.Element('merchantAuthentication') E.SubElement(self._client_auth, 'name').text = self.config.login_id E.SubElement(self._client_auth, 'transactionKey').text = self.config.transaction_key return self._client_auth
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _base_request(self, method): """Factory method for generating the base XML requests."""
request = E.Element(method) request.set('xmlns', 'AnetApi/xml/v1/schema/AnetApiSchema.xsd') request.append(self.client_auth) return request
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_call(self, call): """Make a call to the Authorize.net server with the XML."""
try: request = urllib2.Request(self.config.environment, E.tostring(call)) request.add_header('Content-Type', 'text/xml') response = urllib2.urlopen(request).read() response = E.fromstring(response) response_json = parse_response(response) 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 tag_builder(parser, token, cls, flow_type): """Helper function handling flow form tags."""
tokens = token.split_contents() tokens_num = len(tokens) if tokens_num == 1 or (tokens_num == 3 and tokens[1] == 'for'): flow_name = None if tokens_num == 3: flow_name = tokens[2] return cls(flow_name) else: raise template.TemplateSyntaxError( '"...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sitegate_view(*args_dec, **kwargs_dec): """Decorator to mark views used both for signup & sign in."""
if len(args_dec): # simple decoration w/o parameters return signup_view(signin_view(redirect_signedin(*args_dec, **kwargs_dec))) signin = signin_view(**kwargs_dec) signup = signup_view(**kwargs_dec) return lambda *args, **kwargs: signup(signin(redirect_signedin(*args, **kwargs)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_ulid_timestamp(ulid): """ Get the time from an ULID as an UNIX timestamp. :param ulid: An ULID (either as UUID, base32 ULID or binary) :return: UNIX time...
ts_bytes = ulid_to_binary(ulid)[:6] ts_bytes = b'\0\0' + ts_bytes assert len(ts_bytes) == 8 return (struct.unpack(b'!Q', ts_bytes)[0] / 1000.)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_binary_ulid(timestamp=None, monotonic=False): """ Generate the bytes for an ULID. :param timestamp: An optional timestamp override. If `None`, the c...
global _last_entropy, _last_timestamp if timestamp is None: timestamp = time.time() elif isinstance(timestamp, datetime.datetime): timestamp = calendar.timegm(timestamp.utctimetuple()) ts = int(timestamp * 1000.0) ts_bytes = _to_binary( (ts >> shift) & 0xFF for shift in (40...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_ulid_as_uuid(timestamp=None, monotonic=False): """ Generate an ULID, but expressed as an UUID. :param timestamp: An optional timestamp override. If ...
return uuid.UUID(bytes=generate_binary_ulid(timestamp, monotonic=monotonic))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ulid_to_binary(ulid): """ Convert an ULID to its binary representation. :param ulid: An ULID (either as UUID, base32 ULID or binary) :return: Bytestring of l...
if isinstance(ulid, uuid.UUID): return ulid.bytes if isinstance(ulid, (text_type, bytes)) and len(ulid) == 26: return decode_ulid_base32(ulid) if isinstance(ulid, (bytes, bytearray)) and len(ulid) == 16: return ulid raise InvalidULID('can not convert ulid %r to binary' % ulid)
<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_session(scraper): """ Instantiate a session with the desired configuration parameters, including the cache policy. """
cache_path = os.path.join(scraper.config.data_path, 'cache') cache_policy = scraper.config.cache_policy cache_policy = cache_policy.lower().strip() session = ScraperSession() session.scraper = scraper session.cache_policy = cache_policy adapter = CacheControlAdapter( FileCache(cach...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json(self, **kwargs): """ Create JSON object out of the response. """
try: return super(ScraperResponse, self).json(**kwargs) except ValueError as ve: raise ParseException(ve)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collapse_whitespace(text): """ Collapse all consecutive whitespace, newlines and tabs in a string into single whitespaces, and strip the outer whitespace. Th...
if text is None: return None if hasattr(text, 'xpath'): text = text.xpath('string()') text = re.sub('\s+', ' ', text) return text.strip()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_regex(self): """Sets up the patterns and compiled regex objects for parsing types."""
#Regex for matching the entire body of the type and getting top-level modifiers. self._RX_TYPE = r"\n\s*type(?P<modifiers>,\s+(public|private))?(\s*::)?\s+(?P<name>[A-Za-z0-9_]+)" + \ r"(?P<contents>.+?)end\s*type(\s+(?P=name))?" self.RE_TYPE = re.compile(self._RX_TYPE, ...
<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_line(self, statement, element, mode): """As part of real-time update, parses the statement and adjusts the attributes of the specified CustomType insta...
if element.incomplete: #We need to check for the end_token so we can close up the incomplete #status for the instance. if element.end_token in statement: element.incomplete = False return #This method deals with updating the *body* of...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _rt_members_add(self, element, statement): """Finds all the member declarations in 'statement' and adds the corresponding instances to element.members."""
members = self.vparser.parse(statement, None) for member in members: single = members[member] single.parent = element element.members[member] = single
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _rt_members_delete(self, element, statement): """Finds all the member declarations in 'statement' and removes the corresponding instances from element.member...
removals = self.vparser.parse(statement, None) for member in removals: if member in element.members: del element.members[member]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(self, module): """Extracts all the types from the specified module body."""
matches = self.RE_TYPE.finditer(module.contents) result = {} for match in matches: name = match.group("name") modifiers = match.group("modifiers") if modifiers is not None: cleanmods = re.split("[\s,]+", modifiers.strip()) else: ...
<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_type(self, name, modifiers, contents, module, match): """Processes a regex match of a type's contents."""
#First, we need to see if the types children are private. if self.RE_PRIV.search(contents): modifiers.append("private contents") #Next, we need to parse out all the members of the type and their docstrings members = self.vparser.parse(contents, None) #Now w...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_docs(self, t, module): """Updates the documentation for the specified type using the module predocs."""
#We need to look in the parent module docstrings for this types decorating tags. key = "{}.{}".format(module.name, t.name) if key in module.predocs: t.docstring = self.docparser.to_doc(module.predocs[key][0], t.name) t.docstart, t.docend = (module.predocs[key][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 _process_execs(self, contents, modulename, atype, mode="insert"): """Extracts all the executable methods that belong to the type."""
#We only want to look at text after the contains statement match = self.RE_CONTAINS.search(contents) #It is possible for the type to not have any executables if match is not None: exectext = match.group("remainder") self._process_execs_contents(exectext, modulen...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def login(self): """Logs into MAL and sets cookies appropriately. :rtype: :class:`.Session` :return: The current session. """
# POSTS a login to mal. mal_headers = { 'Host': 'myanimelist.net', } mal_payload = { 'username': self.username, 'password': self.password, 'cookie': 1, 'sublogin': 'Login' } self.session.headers.update(mal_headers) r = self.session.post(u'http://myanimelist.net...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def increase_indent(func): """Decorator for makin """
def wrapper(*args, **kwargs): global _debug_indent _debug_indent += 1 result = func(*args, **kwargs) _debug_indent -= 1 return result 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 dbg(message, *args): """ Looks at the stack, to see if a debug message should be printed. """
if debug_function and enable_notice: frm = inspect.stack()[1] mod = inspect.getmodule(frm[0]) if not (mod.__name__ in ignored_modules): i = ' ' * _debug_indent debug_function(NOTICE, i + 'dbg: ' + message % 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 print_to_stdout(level, str_out): """ The default debug function """
if level == NOTICE: col = Fore.GREEN elif level == WARNING: col = Fore.RED else: col = Fore.YELLOW if not is_py3: str_out = str_out.encode(encoding, 'replace') print((col + str_out + Fore.RESET))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def count_dimensions(entry): """Counts the number of dimensions from a nested list of dimension assignments that may include function calls. """
result = 0 for e in entry: if isinstance(e, str): sliced = e.strip(",").split(",") result += 0 if len(sliced) == 1 and sliced[0] == "" else len(sliced) 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 parse(self, string, parent): """Parses all the value code elements from the specified string."""
result = {} for member in self.RE_MEMBERS.finditer(string): mems = self._process_member(member, parent, string) #The regex match could contain multiple members that were defined #on the same line in the code file. for onemem in mems: resul...
<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_member(self, member, parent, string): """Extracts all the member info from the regex match; returns a ValueElements."""
#The modifiers regex is very greedy so we have some cleaning up to do #to extract the mods. modifiers = member.group("modifiers") dimension = None if modifiers is not None: #Unfortunately, the dimension can also be specified as a modifier and #th...