code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
obj = _make_object("DropShadowFilter") obj.DropShadowColor = self._get_struct_rgba() obj.BlurX = unpack_fixed16(self._src) obj.BlurY = unpack_fixed16(self._src) obj.Angle = unpack_fixed16(self._src) obj.Distance = unpack_fixed16(self._src) obj.Strength = ...
def _get_struct_dropshadowfilter(self)
Get the values for the DROPSHADOWFILTER record.
3.550055
3.393088
1.046261
obj = _make_object("BlurFilter") obj.BlurX = unpack_fixed16(self._src) obj.BlurY = unpack_fixed16(self._src) bc = BitConsumer(self._src) obj.Passes = bc.u_get(5) obj.Reserved = bc.u_get(3) return obj
def _get_struct_blurfilter(self)
Get the values for the BLURFILTER record.
6.367433
5.963087
1.067808
obj = _make_object("GlowFilter") obj.GlowColor = self._get_struct_rgba() obj.BlurX = unpack_fixed16(self._src) obj.BlurY = unpack_fixed16(self._src) obj.Strength = unpack_fixed8(self._src) bc = BitConsumer(self._src) obj.InnerGlow = bc.u_get(1) ob...
def _get_struct_glowfilter(self)
Get the values for the GLOWFILTER record.
4.449553
4.183927
1.063487
obj = _make_object("BevelFilter") obj.ShadowColor = self._get_struct_rgba() obj.HighlightColor = self._get_struct_rgba() obj.BlurX = unpack_fixed16(self._src) obj.BlurY = unpack_fixed16(self._src) obj.Angle = unpack_fixed16(self._src) obj.Distance = unpac...
def _get_struct_bevelfilter(self)
Get the values for the BEVELFILTER record.
3.303535
3.230625
1.022568
obj = _make_object("ConvolutionFilter") obj.MatrixX = unpack_ui8(self._src) obj.MatrixY = unpack_ui8(self._src) obj.Divisor = unpack_float(self._src) obj.Bias = unpack_float(self._src) _quant = obj.MatrixX * obj.MatrixY obj.Matrix = [unpack_float(self._s...
def _get_struct_convolutionfilter(self)
Get the values for the CONVOLUTIONFILTER record.
5.0454
4.705093
1.072327
obj = _make_object("ColorMatrixFilter") obj.Matrix = [unpack_float(self._src) for _ in range(20)] return obj
def _get_struct_colormatrixfilter(self)
Get the values for the COLORMATRIXFILTER record.
11.440284
10.269629
1.113992
obj = _make_object("GradientBevelFilter") obj.NumColors = num_colors = unpack_ui8(self._src) obj.GradientColors = [self._get_struct_rgba() for _ in range(num_colors)] obj.GradientRatio = [unpack_ui8(self._src) for _ in r...
def _get_struct_gradientbevelfilter(self)
Get the values for the GRADIENTBEVELFILTER record.
3.400179
3.324314
1.022821
obj = _make_object("ActionConstantPool") obj.Count = count = unpack_ui16(self._src) obj.ConstantPool = pool = [] for _ in range(count): pool.append(self._get_struct_string()) yield obj
def _handle_actionconstantpool(self, _)
Handle the ActionConstantPool action.
7.265615
6.383004
1.138275
obj = _make_object("ActionGetURL") obj.UrlString = self._get_struct_string() obj.TargetString = self._get_struct_string() yield obj
def _handle_actiongeturl(self, _)
Handle the ActionGetURL action.
8.069493
6.877461
1.173324
init_pos = self._src.tell() while self._src.tell() < init_pos + length: obj = _make_object("ActionPush") obj.Type = unpack_ui8(self._src) # name and how to read each type push_types = { 0: ("String", self._get_struct_string), ...
def _handle_actionpush(self, length)
Handle the ActionPush action.
3.005217
2.943106
1.021104
obj = _make_object("ActionDefineFunction") obj.FunctionName = self._get_struct_string() obj.NumParams = unpack_ui16(self._src) for i in range(1, obj.NumParams + 1): setattr(obj, "param" + str(i), self._get_struct_string()) obj.CodeSize = unpack_ui16(self._src...
def _handle_actiondefinefunction(self, _)
Handle the ActionDefineFunction action.
4.264582
4.011863
1.062993
obj = _make_object("ActionIf") obj.BranchOffset = unpack_si16(self._src) yield obj
def _handle_actionif(self, _)
Handle the ActionIf action.
22.696009
16.380323
1.385565
obj = _make_object("ActionDefineFunction2") obj.FunctionName = self._get_struct_string() obj.NumParams = unpack_ui16(self._src) obj.RegisterCount = unpack_ui8(self._src) bc = BitConsumer(self._src) obj.PreloadParentFlag = bc.u_get(1) obj.PreloadRootFlag =...
def _handle_actiondefinefunction2(self, _)
Handle the ActionDefineFunction2 action.
2.812622
2.777394
1.012684
items_unk = collections.Counter() items_ok = collections.Counter() def _go_deep(obj): if type(obj).__name__ in ('UnknownObject', 'UnknownAction'): # blatantly unknown items_unk[obj.name] += 1 elif obj.name in ('Define...
def coverage(self)
Calculate the coverage of a file.
3.896266
3.883445
1.003302
img_one, img_two = _preprocess_images(img_spec1, img_spec2, rescale_method=rescale_method, bkground_thresh=background_threshold, padding=paddi...
def checkerboard(img_spec1=None, img_spec2=None, patch_size=10, view_set=(0, 1, 2), num_slices=(10,), num_rows=2, rescale_method='global', background_threshold=0.05, annot=None, ...
Checkerboard mixer. Parameters ---------- img_spec1 : str or nibabel image-like object MR image (or path to one) to be visualized img_spec2 : str or nibabel image-like object MR image (or path to one) to be visualized patch_size : int or list or (int, int) or None size of ...
3.170233
3.227016
0.982404
if alpha_channels is None: alpha_channels = [1, 1] if not len(alpha_channels) == 2: # not sure if we should make them sum to 1: or not np.isclose(sum(alpha_channels), 1.0) raise ValueError('Alpha must be two elements') mixer_params = dict(alpha_channels=alpha_channels, ...
def color_mix(img_spec1=None, img_spec2=None, alpha_channels=None, color_space='rgb', view_set=(0, 1, 2), num_slices=(10,), num_rows=2, rescale_method='global', background_threshold=0.05, annot=...
Color mixer, where each image is represented with a different color (default: red and green) in color channels. Parameters ---------- img_spec1 : str or nibabel image-like object MR image (or path to one) to be visualized img_spec2 : str or nibabel image-like object MR image (or path t...
3.184273
3.192447
0.99744
if not isinstance(abs_value, bool): abs_value = bool(abs_value) mixer_params = dict(abs_value=abs_value, cmap=cmap, overlay_image=overlay_image, overlay_alpha=overlay_alpha) fig = _compare(img_spec1, im...
def voxelwise_diff(img_spec1=None, img_spec2=None, abs_value=True, cmap='gray', overlay_image=False, overlay_alpha=0.8, num_rows=2, num_cols=6, rescale_method='global',...
Voxel-wise difference map. Parameters ---------- img_spec1 : str or nibabel image-like object MR image (or path to one) to be visualized img_spec2 : str or nibabel image-like object MR image (or path to one) to be visualized abs_value : bool Flag indicating whether to take...
2.185444
2.471066
0.884413
num_rows, num_cols, padding = check_params(num_rows, num_cols, padding) img1, img2 = check_images(img_spec1, img_spec2, bkground_thresh=bkground_thresh) img1, img2 = crop_to_extents(img1, img2, padding) num_slices_per_view = num_rows * num_cols slices = pick_slices(img2, num_slices_per_view)...
def _compare(img_spec1, img_spec2, num_rows=2, num_cols=6, mixer='checker_board', rescale_method='global', annot=None, padding=5, bkground_thresh=0.05, output_path=None, figsize=None, ...
Produces checkerboard comparison plot of two 3D images. Parameters ---------- img_spec1 : str or nibabel image-like object MR image (or path to one) to be visualized img_spec2 : str or nibabel image-like object MR image (or path to one) to be visualized num_rows : int numb...
3.230286
3.307066
0.976783
"Produces a collage of various slices from different orientations in the given 3D image" num_rows, num_cols, padding = check_params(num_rows, num_cols, padding) img = read_image(img_spec, bkground_thresh=bkground_thresh) img = crop_image(img, padding) img, (min_value, max_value) = check_rescaling...
def collage(img_spec, num_rows=2, num_cols=6, rescale_method='global', cmap='gray', annot=None, padding=5, bkground_thresh=None, output_path=None, figsize=None, **kwargs)
Produces a collage of various slices from different orientations in the given 3D image
3.015049
2.785036
1.082589
"Produces a collage of various slices from different orientations in the given 3D image" num_rows, num_cols, padding = check_params(num_rows, num_cols, padding) mri = read_image(mri_spec, bkground_thresh=bkground_thresh) seg = read_image(aseg_spec, bkground_thresh=0) mri, seg = crop_to_seg_extents...
def aseg_on_mri(mri_spec, aseg_spec, alpha_mri=1.0, alpha_seg=1.0, num_rows=2, num_cols=6, rescale_method='global', aseg_cmap='freesurfer', sub_cortical=False, annot=None, ...
Produces a collage of various slices from different orientations in the given 3D image
2.52161
2.37221
1.062979
mixer_name = mixer_name.lower() if mixer_name in ['color_mix', 'rgb']: mixed = _mix_color(slice1, slice2, **kwargs) cmap = None # data is already RGB-ed elif mixer_name in ['checkerboard', 'checker', 'cb', 'checker_board']: checkers = _get_checkers(slice1.shape, **kwargs) ...
def _generic_mixer(slice1, slice2, mixer_name, **kwargs)
Generic mixer to process two slices with appropriate mixer and return the composite to be displayed.
3.221086
3.176831
1.01393
# estimating intensity ranges if rescale_method is None: # this section is to help user to avoid all intensity rescaling altogther! # TODO bug does not work yet, as pyplot does not offer any easy way to control it rescale_images = False min_value = None max_value = ...
def check_rescaling(img1, img2, rescale_method)
Estimates the intensity range to clip the visualizations to
4.837869
4.773938
1.013392
img1 = read_image(img_spec1, bkground_thresh) img2 = read_image(img_spec2, bkground_thresh) if img1.shape != img2.shape: raise ValueError('size mismatch! First image: {} Second image: {}\n' 'Two images to be compared must be of the same size in all dimensions.'.format...
def check_images(img_spec1, img_spec2, bkground_thresh=0.05)
Reads the two images and assers identical shape.
3.223197
2.932705
1.099052
if patch_size is not None: patch_size = check_patch_size(patch_size) else: # 7 patches in each axis, min voxels/patch = 3 # TODO make 7 a user settable parameter patch_size = np.round(np.array(slice_shape) / 7).astype('int16') patch_size = np.maximum(patch_size, np....
def _get_checkers(slice_shape, patch_size)
Creates checkerboard of a given tile size, filling a given slice.
2.892743
2.761734
1.047437
if slice1.shape != slice2.shape: raise ValueError('size mismatch between cropped slices and checkers!!!') alpha_channels = np.array(alpha_channels) if len(alpha_channels) != 2: raise ValueError('Alphas must be two value tuples.') slice1, slice2 = scale_images_0to1(slice1, slice2)...
def _mix_color(slice1, slice2, alpha_channels, color_space)
Mixing them as red and green channels
3.458969
3.432313
1.007766
checkers = _get_checkers(slice1.shape, checker_size) if slice1.shape != slice2.shape or slice2.shape != checkers.shape: raise ValueError('size mismatch between cropped slices and checkers!!!') mixed = slice1.copy() mixed[checkers > 0] = slice2[checkers > 0] return mixed
def _checker_mixer(slice1, slice2, checker_size=None)
Mixes the two slices in alternating areas specified by checkers
3.581471
3.45103
1.037798
rough_string = E.tostring(elem, 'utf-8') reparsed = minidom.parseString(rough_string) return reparsed.toprettyxml(indent=' ').strip()
def prettify(elem)
Return a pretty-printed XML string for the Element.
2.270677
2.220987
1.022373
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(): ...
def filter(self)
Generate a filtered query from request parameters. :returns: Filtered SQLALchemy query
3.69547
3.776349
0.978583
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')
def _check_min_density(self, min_density)
Validator to ensure proper usage.
2.856425
2.584455
1.105233
self._slices = list() self._slices_by_dim = list() for view, ns_in_view in zip(self.view_set, self.num_slices): # discarding completely empty or almost empty slices. dim_size = self._image_shape[view] non_empty_slices = np.array([sl for sl in range(d...
def _pick_slices(self)
Picks the slices to display in each dimension/view, skipping any empty slices (without any data at all).
5.358663
4.952737
1.08196
img2d = self._get_axis(self._image, view, slice_) return (np.count_nonzero(img2d) / img2d.size) > self._min_density
def _not_empty(self, view, slice_)
Checks if the density is too low.
6.92416
4.905054
1.411638
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...
def _sample_slices_in_dim(self, view, num_slices, non_empty_slices)
Samples the slices in the given dimension according the chosen strategy.
2.814445
2.75745
1.020669
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): ...
def _linear_selection(self, non_empty_slices, num_slices)
Selects linearly spaced slices in given
3.399859
3.417488
0.994842
return np.around(self._sampler * len(non_empty_slices) / 100).astype('int64')
def _percent_selection(self, non_empty_slices)
Chooses slices at a given percentage between the first and last non-empty slice.
7.40077
6.122874
1.208709
selected = [sl for sl in non_empty_slices if self._sampler(self._get_axis(self._image, view, sl))] return selected[:num_slices]
def _selection_by_callable(self, view, num_slices, non_empty_slices)
Returns all the slices selected by the given callable.
9.420613
8.340143
1.129551
slice_list = [slice(None)] * array.ndim slice_list[axis] = slice_num slice_data = array[tuple(slice_list)] if transpose: # for proper orientation slice_data = slice_data.T if not extended: # return just the slice data return slice_d...
def _get_axis(self, array, axis, slice_num, extended=False, transpose=True)
Returns a fixed axis
3.868703
4.039451
0.95773
for dim, slice_num in self._slices: yield self._get_axis(self._image, dim, slice_num, extended=extended)
def get_slices(self, extended=False)
Generator over all the slices selected, each time returning a cross-section. Parameters ---------- extended : bool Flag to return just slice data (default, extended=False), or return a tuple of axis, slice_num, slice_data (extended=True) Returns ---...
7.666343
6.105648
1.255615
# 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)) ...
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 as the original image defining this object. Parameters ---------- image_list : Iterable containing atleast 2 images extended : bool Flag to return ju...
6.324035
5.557815
1.137863
import imageio gif_data = [img for img in self.get_slices()] # using img.astype(np.uint32) is leaving noticable artefacts, # depending on imageio inner conversion, which is rescaling okay # TODO deal with differing sizes of slices, padding with zeros or white?? ...
def save_as_gif(self, gif_path, duration=0.25)
Package the selected slices into a single GIF for easy sharing and display (on web etc). You must install imageio module separately to use this feature. Parameters ---------- gif_path : str Output path for the GIF image duration : float Duration of disp...
10.74995
9.737229
1.104005
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: ...
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.axis_pad_default, commn_an...
Creates a grid of axes bounded within a given rectangle.
2.424831
2.402773
1.00918
left, bottom, width, height = bounding_rect height_padding = axis_pad * (num_rows + 1) width_padding = axis_pad * (num_cols + 1) cell_height = float((height - height_padding) / num_rows) cell_width = float((width - width_padding) / num_cols) cell_height_padded ...
def _compute_cell_extents_grid(bounding_rect=(0.03, 0.03, 0.97, 0.97), num_rows=2, num_cols=6, axis_pad=0.01)
Produces array of num_rows*num_cols elements each containing the rectangular extents of the corresponding cell the grid, whose position is within bounding_rect.
1.769558
1.806029
0.979806
# 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.fl...
def _create_imshow_objects(self)
Turns off all the x and y axes in each Axis
8.381713
8.355556
1.00313
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 = SlicePic...
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 attached to the collage, once it is created. Must be atleast 3d. sampler : str or list or callable selection strategy: to identify the ty...
4.373295
4.115654
1.0626
if not callable(func): raise TypeError('func must be callable!') if not isinstance(image_list, (tuple, list)) and isinstance(image_list, np.ndarray): image_list = [image_list, ] if len(image_list) > 1: shape1 = image_list[0].shape for i...
def transform_and_attach(self, image_list, func, show=True)
Displays the transformed (combined) version of the cross-sections from each image, (same slice and dimension). So if you input n>=1 images, n slices are obtained from each image, which are passed to the func (callable) provided, and the result will be displayed in the corresponding c...
3.419921
3.319566
1.030231
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...
def _set_visible(self, visibility, grid_index=None)
Sets the visibility property of all axes.
2.546418
2.38221
1.068931
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 ...
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 output_path : str path to save the figure to. Note: any spaces in the filename will be replace with ``_``
6.878587
5.730844
1.200275
for ax in self.flat_grid: for im_h in ax.findobj(AxesImage): im_h.remove()
def clear(self)
Clears all the axes to start fresh.
15.363915
11.562133
1.328813
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! ' ...
def _check_image(self, image_nD)
Sanity checks on the image data
3.610367
3.417105
1.056557
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...
def _add_fixed_dim(self, fixed_dim=-1)
Makes note of which dimension needs to be fixed, defaulting to last.
3.05627
2.966096
1.030402
self.carpet = self._unroll_array(self.input_image, self.fixed_dim) if rescale_data: self.carpet = row_wise_rescale(self.carpet)
def _make_carpet(self, rescale_data)
Constructs the carpet from the input image. Optional rescaling of the data.
6.585736
5.336521
1.234088
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 ...
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 ---------- clustered : bool, optional Flag to indicate whether to show the clustered/reduced carpet or the original. You must run .cluster_rows_in_roi() before trying to show clustered carpet. ax_carpet : Axis, ...
3.353748
3.038645
1.103699
try: save_figure(self.fig, output_path=output_path, annot=title) except: print('Unable to save the figure to disk! \nException: ') traceback.print_exc()
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 figure needs to be saved to. title : str text to overlay and annotate the visualization (done via plt.suptitle())
5.134237
4.986245
1.02968
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_ca...
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. Parameters ---------- roi_mask : ndarray or None volumetric mask defining the list of ROIs, with a label for each voxel. This must be the same size in all dimensions except the fixed_dim i.e. if you ...
4.470093
3.851955
1.160474
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_...
def _set_roi_mask(self, roi_mask)
Sets a new ROI mask.
6.272032
6.13706
1.021993
this_label = self.carpet[label_mask.flatten(), :] if num_clusters_per_roi == 1: out_matrix = self._summary_func(this_label, axis=0) else: out_matrix = self._make_clusters(this_label, num_clusters_per_roi, metric) return out_matrix
def _summarize_in_roi(self, label_mask, num_clusters_per_roi=1, metric='minkowski')
returns a single row summarizing (typically via mean) all rows in an ROI.
3.859392
3.629329
1.06339
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....
def _make_clusters(self, matrix, num_clusters_per_roi, metric)
clusters a given matrix by into specified number of clusters according to given metric
5.370697
5.431864
0.988739
# 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=='...
def _apply_mask(self, roi_mask)
Removes voxels outside the given mask or ROI set.
9.63054
9.361091
1.028784
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]))
def _verify_shape_compatibility(self, img, img_type)
Checks mask shape against input image shape.
3.627201
3.160997
1.147486
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, 'd...
def verify_email(request, code, redirect_to=None)
Verifies an account activation code a user received by e-mail. Requires Messages Django Contrib. :param Requset request: :param str code: :param str redirect_to: :return:
3.014704
3.206788
0.940101
dec_part = unpack_ui8(src) int_part = unpack_ui8(src) return int_part + dec_part / 256
def unpack_fixed8(src)
Get a FIXED8 value.
4.891555
4.52274
1.081547
dec_part = unpack_ui16(src) int_part = unpack_ui16(src) return int_part + dec_part / 65536
def unpack_fixed16(src)
Get a FIXED16 value (called plainly FIXED in the spec).
4.264451
3.848661
1.108035
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
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 for the mantissa
3.95922
3.731256
1.061096
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 qua...
def u_get(self, quant)
Return a number using the given quantity of unsigned bits.
3.230694
3.083073
1.047881
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_...
def s_get(self, quant)
Return a number using the given quantity of signed bits.
4.728409
4.16248
1.135959
raw_number = self.s_get(quant) if quant == 1: # special case, just return that unsigned value return raw_number return raw_number / (1 << fb)
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 default is 16, resulting in a 16.16 fixed bit
8.894978
8.731035
1.018777
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 t...
def get_freesurfer_cmap(vis_type)
Provides different colormaps for different visualization types.
3.900304
3.868376
1.008254
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,...
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 the key modulus :param str keyfile: file the key should be written to :param str format: format for the key file, either PEM or DER :param str passphrase: pass phrase for encrypting the k...
2.968685
3.151285
0.942056
certreqInfo = rfc2314.CertificationRequestInfo() certreqInfo.setComponentByName('version', rfc2314.Version(0)) certreqInfo.setComponentByName('subject', _build_dn(dn)) certreqInfo.setComponentByName('subjectPublicKeyInfo', _build_subject_publickey_info(key)) a...
def create_csr(key, dn, csrfilename=None, attributes=None)
Generates a Certificate Signing Request for a given key. :param Crypto.PublicKey.RSA._RSAobj key: a key :param dn: a distinguished name as dictionary or string with key=value pairs separated by slashes like ``/CN=test.example.org/C=DE/O=Test organisation/`` :param str csrf...
2.298883
2.418878
0.950392
if template_name is None: # Build default template path. template_name = self.default_form_template if '.html' not in template_name: # Shortcut, e.g.: . template_name = '%s%s.html' % ('sitegate/%s/', template_name) if '%s' in template_name: # Fill i...
def get_template_name(self, template_name)
Returns template path, either from a shortcut built-in template name (`form_as_p`) or a template path (`my_sitegate/my_tpl.html`). Note that template path can include one `%s` placeholder. In that case it will be replaced with flow type (`signin` or `signup`).
5.351123
3.93208
1.360889
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)
def respond_for(self, view_function, args, kwargs)
Returns a response for the given view & args.
3.338072
3.314631
1.007072
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 = {} excep...
def update_request(self, request, form)
Updates Request object with flows forms.
7.264137
6.565252
1.106452
user = authenticate(username=username, password=password) if user is not None and user.is_active: login(request, user) return True return False
def login_generic(request, username, password)
Helper method. Generic login with username and password.
1.905098
1.967834
0.968119
if name in self.flow_args: return self.flow_args[name] try: return getattr(self, name) except AttributeError: return default
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 default.
2.812559
2.217399
1.268405
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...
def get_requested_form(self, request)
Returns an instance of a form requested.
3.617396
3.600286
1.004753
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
def init_form(self, form_data, widget_attrs=None, template=None)
Constructs, populates and returns a form.
8.247804
7.873253
1.047573
return os.path.join(scraper.config.data_path, '%s.jsonlog' % scraper.name)
def log_path(scraper)
Determine the file name for the JSON log.
4.621962
3.613034
1.279247
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_...
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 later be used to generate reports.
2.18801
2.173721
1.006574
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.connect((self.host, self.port)) payload = {"command": command} if arg is not None: # Parameter must be converted to basestring (no int) payload.update({'parame...
def command(self, command, arg=None)
Initialize a socket connection, send a command (a json encoded dict) and receive the response (and decode it).
3.079292
3.021339
1.019181
response = self.handler.streamed_request("initiate", "control-log", sa) return self._result(*response)
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: :py:class:`vici.session.CommandResult`
26.612782
29.314402
0.90784
response = self.handler.streamed_request("terminate", "control-log", sa) return self._result(*response)
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 :rtype: :py:class:`vici.session.CommandResult`
29.661238
35.032028
0.846689
_, sa_list = self.handler.streamed_request("list-sas", "list-sa", filters) return sa_list
def list_sas(self, filters=None)
Retrieve active IKE_SAs and associated CHILD_SAs. :param filters: retrieve only matching IKE_SAs (optional) :type filters: dict :return: list of active IKE_SAs and associated CHILD_SAs :rtype: list
16.592228
15.955673
1.039895
_, policy_list = self.handler.streamed_request("list-policies", "list-policy", filters) return policy_list
def list_policies(self, filters=None)
Retrieve installed trap, drop and bypass policies. :param filters: retrieve only matching policies (optional) :type filters: dict :return: list of installed trap, drop and bypass policies :rtype: list
13.233706
13.929547
0.950046
_, connection_list = self.handler.streamed_request("list-conns", "list-conn", filters) return connection_list
def list_conns(self, filters=None)
Retrieve loaded connections. :param filters: retrieve only matching configuration names (optional) :type filters: dict :return: list of connections :rtype: list
13.701419
15.103847
0.907148
_, cert_list = self.handler.streamed_request("list-certs", "list-cert", filters) return cert_list
def list_certs(self, filters=None)
Retrieve loaded certificates. :param filters: retrieve only matching certificates (optional) :type filters: dict :return: list of installed trap, drop and bypass policies :rtype: list
11.91636
14.013159
0.850369
if command_response["success"] == "yes": return CommandResult(True, None, log) else: return CommandResult(False, command_response["errmsg"], log)
def _result(self, command_response, log=None)
Create a CommandResult for a request response. :param command_response: command request response :type command_response: dict :param log: list of log messages (optional) :type log: list :return: a CommandResult containing any given log messages :rtype: :py:class:`vici.se...
3.737703
3.330276
1.12234
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 typ...
def request(self, command, message=None)
Send command request with an optional message. :param command: command to send :type command: str :param message: message (optional) :type message: str :return: command result :rtype: dict
3.592266
3.838576
0.935833
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: ...
def streamed_request(self, command, event_stream_type, message=None)
Send command request and collect and return all emitted events. :param command: command to send :type command: str :param event_stream_type: event type emitted on command execution :type event_stream_type: str :param message: message (optional) :type message: str ...
2.277263
2.362957
0.963735
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) ...
def _read(self)
Get next packet from transport. :return: parsed packet in a tuple with message type and payload :rtype: :py:class:`collections.namedtuple`
9.142473
8.516114
1.07355
paging = self._deserialize(ListRecurringSchema().bind(), params) return self.api._make_call(self._list_request(paging))
def list(self, params={})
Required Parameters: * searchType (str) - cardExpiringThisMonth - subscriptionActive - subscriptionInactive - subscriptionExpiringThisMonth Optional Parameters: * sorting * orderBy (string) - id - name ...
22.606129
24.37941
0.927263
diff = slice1 - slice2 if abs_value: diff = np.abs(diff) return diff, cmap
def _diff_image(slice1, slice2, abs_value=True, cmap='gray', **kwargs)
Computes the difference image
3.063803
3.085737
0.992892
"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, 240)) colors =...
def diff_colormap()
Custom colormap to map low values to black or another color.
3.71942
2.952062
1.25994
slice_list = [slice(None)] * array.ndim slice_list[axis] = slice_num slice_data = array[tuple(slice_list)].T # transpose for proper orientation return slice_data
def get_axis(array, axis, slice_num)
Returns a fixed axis
3.637272
3.979715
0.913953
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',...
def check_bounding_rect(rect_pos)
Ensure the rect spec is valid.
3.161098
2.945421
1.073225
if not isinstance(view_set, Iterable): view_set = tuple([view_set, ]) if len(view_set) > max_views: raise ValueError('Can only have {} views'.format(max_views)) return [check_int(view, 'view', min_value=0, max_value=max_views - 1) for view in view_set]
def check_views(view_set, max_views=3)
Ensures valid view/dimensions are selected.
2.850312
2.64796
1.076418
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.' ...
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
3.365317
3.259549
1.032449
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)
def check_int(num, num_descr='number', min_value=0, max_value=np.Inf)
Validation and typecasting.
2.927222
2.821899
1.037323
patch_size = np.array(patch_size) if patch_size.size == 1: patch_size = np.repeat(patch_size, 2).astype('int16') return patch_size
def check_patch_size(patch_size)
Validation and typcasting
2.433919
2.323743
1.047413
num_rows = check_int(num_rows, 'num_rows', min_value=1) num_cols = check_int(num_cols, 'num_cols', min_value=1) padding = check_int(padding, 'padding', min_value=0) return num_rows, num_cols, padding
def check_params(num_rows, num_cols, padding)
Validation and typcasting
1.627903
1.661356
0.979864
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)
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 (smaller than 5 %ile).
2.184351
2.350104
0.92947
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 exis...
def load_image_from_disk(img_spec)
Vanilla image loader.
5.131747
5.05121
1.015944