Selects a mask by minimizing the appearance of certain patterns. This is inspired by
what was described in the reference manual. I had a hard time understanding some
of the specifics so I improvised.
326951
static QrCodeMaskPattern selectMask( QrCode qr ) {
		int N = qr.getNumberOfModules();
		int totalBytes = QrCode.VERSION_INFO[qr.version].codewords;
		List<Point2D_I32> locations = QrCode.LOCATION_BITS[qr.version];

		QrCodeMaskPattern bestMask = null;
		double bestScore = Double.MAX_VALUE;

		PackedBits8 bits = new PackedBits8();
		bits.size = totalBytes * 8;
		bits.data = qr.rawbits;

		if (bits.size > locations.size())
			throw new RuntimeException("BUG in code");

		// Bit value of 0 = white. 1 = black
		QrCodeCodeWordLocations matrix = new QrCodeCodeWordLocations(qr.version);
		for (QrCodeMaskPattern mask : QrCodeMaskPattern.values()) {
			double score = scoreMask(N, locations, bits, matrix, mask);
			if (score < bestScore) {
				bestScore = score;
				bestMask = mask;
			}
		}
		return bestMask;
	}
595952
def _makemasks(self, index=None, level=0):
        
        if index is None:
            index = self.index

        try:
            dims = len(array(index).shape)
            if dims == 1:
                index = array(index, ndmin=2).T
        except:
            raise TypeError('A multi-index must be convertible to a numpy ndarray')

        try:
            index = index[:, level]
        except:
            raise ValueError("Levels must be indices into individual elements of the index")

        lenIdx = index.shape[0]
        nlevels = index.shape[1]

        combs = product(*[unique(index.T[i, :]) for i in range(nlevels)])
        combs = array([l for l in combs])

        masks = array([[array_equal(index[i], c) for i in range(lenIdx)] for c in combs])

        return zip(*[(masks[x], combs[x]) for x in range(len(masks)) if masks[x].any()])
847310
def mask_reduce(mask):
    
    mask = mask.copy()
    for i in range(len(mask.shape)):
        a = mask.copy()
        j = list(range(len(mask.shape)))
        j.remove(i)
        j = tuple(j)
        a = a.max(axis=j, keepdims=True)
        idx = [slice(None)] * len(mask.shape)
        a = a.flatten()
        idx[i] = [k for k in range(len(a)) if a[k]]
        mask = mask[tuple(idx)]
    return mask
410707
def selection(x_bounds,
              x_types,
              clusteringmodel_gmm_good,
              clusteringmodel_gmm_bad,
              minimize_starting_points,
              minimize_constraints_fun=None):
    '''
    
    '''
    results = lib_acquisition_function.next_hyperparameter_lowest_mu(\
                    _ratio_scores, [clusteringmodel_gmm_good, clusteringmodel_gmm_bad],\
                    x_bounds, x_types, minimize_starting_points, \
                    minimize_constraints_fun=minimize_constraints_fun)

    return results
114218
def set_on_mask(self, mask):
        """"""
        set_cmd = self._create_set_property_msg('_on_mask', 0x02, mask)
        self._send_method(set_cmd, self._property_set)
144393
def keep_mask(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state):
    

    X_train, X_test = to_array(X_train, X_test)

    # how many features to mask
    assert X_train.shape[1] == X_test.shape[1]

    # keep nkeep top features for each test explanation
    X_test_tmp = X_test.copy()
    yp_masked_test = np.zeros(y_test.shape)
    tie_breaking_noise = const_rand(X_train.shape[1], random_state) * 1e-6
    mean_vals = X_train.mean(0)
    for i in range(len(y_test)):
        if nkeep[i] < X_test.shape[1]:
            ordering = np.argsort(-attr_test[i,:] + tie_breaking_noise)
            X_test_tmp[i,ordering[nkeep[i]:]] = mean_vals[ordering[nkeep[i]:]]

    yp_masked_test = trained_model.predict(X_test_tmp)

    return metric(y_test, yp_masked_test)
498479
def create_mask(
        fnii,
        fimout = '',
        outpath = '',
        fill = 1,
        dtype_fill = np.uint8,
        
        thrsh = 0.,
        fwhm = 0.,):

    ''' '''
    

    #> output path
    if outpath=='' and fimout!='':
        opth = os.path.dirname(fimout)
        if opth=='':
            opth = os.path.dirname(fnii)
            fimout = os.path.join(opth, fimout)

    elif outpath=='':
        opth = os.path.dirname(fnii)

    else:
        opth = outpath

    #> output file name if not given
    if fimout=='':
        fniis = os.path.split(fnii)
        fimout = os.path.join(opth, fniis[1].split('.nii')[0]+'_mask.nii.gz')

    niidct = imio.getnii(fnii, output='all')
    im = niidct['im']
    hdr = niidct['hdr']

    if im.ndim>3:
        raise ValueError('The masking function only accepts 3-D images.')

    #> generate output image
    if thrsh>0.:
        smoim = ndi.filters.gaussian_filter(
                    im,
                    imio.fwhm2sig(fwhm, voxsize=abs(hdr['pixdim'][1])), 
                    mode='mirror')
        thrsh = thrsh*smoim.max()
        immsk = np.int8(smoim>thrsh)
        immsk = imfill(immsk)

        #> output image
        imo = fill * immsk.astype(dtype_fill)

    else:

        imo = fill * np.ones(im.shape, dtype = dtype_fill)

    #> save output image
    imio.array2nii( 
                imo,
                niidct['affine'],
                fimout,
                trnsp = (niidct['transpose'].index(0),
                         niidct['transpose'].index(1),
                         niidct['transpose'].index(2)),
                flip = niidct['flip'])

    return {'fim':fimout, 'im':imo}
133184
def mask(self):
        '''
        

        '''

        return np.array(list(set(np.concatenate([self.outmask, self.badmask,
                        self.transitmask, self.nanmask]))), dtype=int)
896748
function mask( obj ){
	if ( Object.create ){
		var T = function Masked(){};

		T.prototype = obj;

		return new T();
	}else{
		return Object.create( obj );
	}
}
1315261
def maskname(self) -> Optional[str]:
        """"""
        mask = self._data['geometry']['mask']
        if os.path.abspath(mask):
            mask = os.path.split(mask)[-1]
        return mask
831198
def one_mask(self):
        """"""
        accum = 0
        for i in range(self.data.itemsize):
            accum += (0xAA << (i << 3))
        return accum
1146636
function _createMaskRect() {
  const element = document.createElementNS(svgNS, 'rect');

  _setAttributes(element, {
    fill: '#FFFFFF',
    height: '100%',
    id: elementIds.modalOverlayMaskRect,
    width: '100%',
    x: '0',
    y: '0'
  });

  return element;
}
1233932
def draw_mask(im, mask, alpha=0.5, color=None):
    
    if color is None:
        color = PALETTE_RGB[np.random.choice(len(PALETTE_RGB))][::-1]
    im = np.where(np.repeat((mask > 0)[:, :, None], 3, axis=2),
                  im * (1 - alpha) + color * alpha, im)
    im = im.astype('uint8')
    return im
143750
def vector_mask(self):
        
        if not hasattr(self, '_vector_mask'):
            self._vector_mask = None
            blocks = self.tagged_blocks
            for key in ('VECTOR_MASK_SETTING1', 'VECTOR_MASK_SETTING2'):
                if key in blocks:
                    self._vector_mask = VectorMask(blocks.get_data(key))
        return self._vector_mask
599975
def _apply_mask(self, roi_mask):
        """"""

        # 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'):
            self._set_roi_mask(roi_mask)

            rows_roi = np.where(self.roi_mask.flatten() == cfg.background_value)

            # TODO below would cause differences in size/shape across mask and carpet!
            self.carpet = np.delete(self.carpet, rows_roi, axis=0)

        else:
            self.roi_mask = np.ones(self.carpet.shape)
238115
def minimize_matrix(self):
        
        if self._algo == EwaldMinimizer.ALGO_FAST or \
                        self._algo == EwaldMinimizer.ALGO_BEST_FIRST:
            return self._recurse(self._matrix, self._m_list,
                                 set(range(len(self._matrix))))
984621
def _conform_mask(in_mask, in_reference):
    """"""
    from pathlib import Path
    import nibabel as nb
    from nipype.utils.filemanip import fname_presuffix

    ref = nb.load(in_reference)
    nii = nb.load(in_mask)
    hdr = nii.header.copy()
    hdr.set_data_dtype('int16')
    hdr.set_slope_inter(1, 0)

    qform, qcode = ref.header.get_qform(coded=True)
    if qcode is not None:
        hdr.set_qform(qform, int(qcode))

    sform, scode = ref.header.get_sform(coded=True)
    if scode is not None:
        hdr.set_sform(sform, int(scode))

    if '_maths' in in_mask:  # Cut the name at first _maths occurrence
        ext = ''.join(Path(in_mask).suffixes)
        basename = Path(in_mask).name
        in_mask = basename.split('_maths')[0] + ext

    out_file = fname_presuffix(in_mask, suffix='_mask',
                               newpath=str(Path()))
    nii.__class__(nii.get_data().astype('int16'), ref.affine,
                  hdr).to_filename(out_file)
    return out_file