An implementation of factorial using motif pattern matching.
355315
public long factMatching(long n) {
    return match(n)
        .when(caseLong(0)).get(() -> 1L)
        .when(caseLong(any())).get(i -> i * factMatching(i - 1))
        .getMatch();
  }
1280621
public static CharSequence matchesPattern(final CharSequence input, final String pattern, final String message) {
        return INSTANCE.matchesPattern(input, pattern, message);
    }
271972
def _summary_matching_gos(prt, pattern, matching_gos, all_gos):
        """"""
        msg = 'Found {N} GO(s) out of {M} matching pattern("{P}")\n'
        num_gos = len(matching_gos)
        num_all = len(all_gos)
        prt.write(msg.format(N=num_gos, M=num_all, P=pattern))
1321646
def _init_compile_patterns(optional_attrs):
        """"""
        attr2cmp = {}
        if optional_attrs is None:
            return attr2cmp
        # "peptidase inhibitor complex" EXACT [GOC:bf, GOC:pr]
        # "blood vessel formation from pre-existing blood vessels" EXACT systematic_synonym []
        # "mitochondrial inheritance" EXACT []
        # "tricarboxylate transport protein" RELATED [] {comment="WIkipedia:Mitochondrial_carrier"}
        if 'synonym' in optional_attrs:
            attr2cmp['synonym'] = re.compile(r'"(\S.*\S)" ([A-Z]+) (.*)\[(.*)\](.*)$')
            attr2cmp['synonym nt'] = cx.namedtuple("synonym", "text scope typename dbxrefs")
        # Wikipedia:Zygotene
        # Reactome:REACT_27267 "DHAP from Ery4P and PEP, Mycobacterium tuberculosis"
        if 'xref' in optional_attrs:
            attr2cmp['xref'] = re.compile(r'^(\S+:\s*\S+)\b(.*)$')
        return attr2cmp
73708
function(symbol, factors) {
                if(symbol.group !== PL) return symbol; //only PL need apply
                var d = core.Utils.arrayMin(keys(symbol.symbols));
                var retval = new Symbol(0);
                var q = _.parse(symbol.value+'^'+d);
                symbol.each(function(x) {
                    x = _.divide(x, q.clone());
                    retval = _.add(retval, x);
                });
                factors.add(q);
                return retval;
            }
1168069
public boolean matchMidClauses(char[] chars, int start, int length) 
  {
    return pattern.matchMiddle(chars, start, start+length);

  }
50909
def match_sequence(self, tokens, item):
        """"""
        tail = None
        if len(tokens) == 2:
            series_type, matches = tokens
        else:
            series_type, matches, tail = tokens
        self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Sequence)")
        if tail is None:
            self.add_check("_coconut.len(" + item + ") == " + str(len(matches)))
        else:
            self.add_check("_coconut.len(" + item + ") >= " + str(len(matches)))
            if tail != wildcard:
                if len(matches) > 0:
                    splice = "[" + str(len(matches)) + ":]"
                else:
                    splice = ""
                self.assign_to_series(tail, series_type, item + splice)
        self.match_all_in(matches, item)
1168107
private static boolean matchesPatternList(final String str, final List<Pattern> patterns) {
        if (patterns != null) {
            for (final Pattern pattern : patterns) {
                if (pattern.matcher(str).matches()) {
                    return true;
                }
            }
        }
        return false;
    }
422610
function(symbol, factors) {  
                if(symbol.group === FN) { 
                    if(symbol.fname === 'sqrt') {
                        var factors2 = new Factors(),
                            arg = __.Factor.common(symbol.args[0].clone(), factors2);
                        arg = __.Factor.coeffFactor(arg, factors2);
                        symbol = _.symfunction('sqrt', [arg]);
                        factors2.each(function(x) {
                            symbol = _.multiply(symbol, _.parse(core.Utils.format('sqrt({0})', x)));
                        });
                    }
                    else
                        factors.add(symbol);
                }
                else { 
                    //symbol = __.Factor.common(symbol, factors);
                    symbol = __.Factor.mSqfrFactor(symbol, factors);
                    
                    var vars = variables(symbol),
                        symbols = symbol.collectSymbols().map(function(x) {
                            return Symbol.unwrapSQRT(x);
                        }),
                        sorted = {},
                        maxes = {},
                        l = vars.length, n = symbols.length;
                    //take all the variables in the symbol and organize by variable name
                    //e.g. a^2+a^2+b*a -> {a: {a^3, a^2, b*a}, b: {b*a}}
                    
                    for(var i=0; i<l; i++) {
                        var v = vars[i];
                        sorted[v] = new Symbol(0);
                        for(var j=0; j<n; j++) {
                            var s = symbols[j];
                            if(s.contains(v)) {
                                var p = s.value === v ? s.power.toDecimal() : s.symbols[v].power.toDecimal();
                                if(!maxes[v] || p < maxes[v]) maxes[v] = p;
                                sorted[v] = _.add(sorted[v], s.clone());
                            }
                        }
                    }
                    
                    for(var x in sorted) {
                        var r = _.parse(x+'^'+maxes[x]); 
                        var div = _.divide(sorted[x], r);
                        var new_factor = _.expand(div); 
                        
                        if(new_factor.equals(1))
                            break; //why divide by one. Just move 
                        var divided = __.div(symbol.clone(), new_factor); 
                        if(divided[0].equals(0)) { 
                            //cant factor anymore
                            break;
                        }
                        
                        var neg_numeric_factor = isInt(new_factor) && new_factor.lessThan(0);
                        
                        if(divided[1].equals(0) && !neg_numeric_factor) { //we found at least one factor
                            //factors.add(new_factor);
                            var d = __.div(symbol.clone(), divided[0].clone());
                            var r = d[0];
                            symbol = d[1];
                            //we don't want to just flip the sign. If the remainder is -1 then we accomplished nothing
                            //and we just return the symbol;
                            //If r equals zero then there's nothing left to do so we're done
                            if(r.equals(-1))
                                return symbol;

                            var factor = divided[0]; 
                            if(symbol.equals(factor)) {
                                var rem = __.Factor.reduce(factor, factors);
                                
                                if(!symbol.equals(rem)) 
                                    return __.Factor.mfactor(rem, factors);
                            }
                            else {
                                factors.add(factor); 
                                //if the remainder of the symbol is zero then we're done. TODO: Rethink this logic a bit.
                                if(symbol.equals(0))
                                    return r;
                            }
                            
                            if(r.isConstant('all')) { 
                                factors.add(r);
                                return r;
                            }
                            
                            return __.Factor.mfactor(r, factors);
                        }
                    }
                    
                }
                
                //difference of squares factorization
                symbol = __.Factor.sqdiff(symbol, factors);
                //factors by fishing for zeroes
                symbol = __.Factor.zeroes(symbol, factors);
                
                return symbol;
            }
980034
@Reference(authors = "D. Pelleg, A. Moore", //
      title = "X-means: Extending K-means with Efficient Estimation on the Number of Clusters", //
      booktitle = "Proc. 17th Int. Conf. on Machine Learning (ICML 2000)", //
      url = "http://www.pelleg.org/shared/hp/download/xmeans.ps", //
      bibkey = "DBLP:conf/icml/PellegM00")
  public static <V extends NumberVector> double logLikelihood(Relation<V> relation, Clustering<? extends MeanModel> clustering, NumberVectorDistanceFunction<? super V> distanceFunction) {
    List<? extends Cluster<? extends MeanModel>> clusters = clustering.getAllClusters();
    // number of clusters
    final int m = clusters.size();

    // number of objects in the clustering
    int n = 0;
    // cluster sizes
    int[] n_i = new int[m];
    // total variance
    double d = 0.;
    // variances
    double[] d_i = new double[m];

    // Iterate over clusters:
    Iterator<? extends Cluster<? extends MeanModel>> it = clusters.iterator();
    for(int i = 0; it.hasNext(); ++i) {
      Cluster<? extends MeanModel> cluster = it.next();
      n += n_i[i] = cluster.size();
      d += d_i[i] = varianceOfCluster(cluster, distanceFunction, relation);
    }

    // No remaining variance, if every point is on its own:
    if(n <= m) {
      return Double.NEGATIVE_INFINITY;
    }

    // Total variance (corrected for bias)
    final double logv = FastMath.log(d / (n - m));

    final int dim = RelationUtil.dimensionality(relation);
    // log likelihood of this clustering
    double logLikelihood = 0.;

    // Aggregate
    for(int i = 0; i < m; i++) {
      logLikelihood += n_i[i] * FastMath.log(n_i[i]) // Post. entropy Rn log Rn
          - n_i[i] * .5 * MathUtil.LOGTWOPI // Rn/2 log2pi
          - n_i[i] * dim * .5 * logv // Rn M/2 log sigma^2
          - (d_i[i] - m) * .5; // (Rn-K)/2
    }
    logLikelihood -= n * FastMath.log(n); // Prior entropy, sum_i Rn log R
    return logLikelihood;
  }
932527
def generate_association_rules(patterns, confidence_threshold):
    
    rules = {}
    for itemset in patterns.keys():
        upper_support = patterns[itemset]

        for i in range(1, len(itemset)):
            for antecedent in itertools.combinations(itemset, i):
                antecedent = tuple(sorted(antecedent))
                consequent = tuple(sorted(set(itemset) - set(antecedent)))

                if antecedent in patterns:
                    lower_support = patterns[antecedent]
                    confidence = float(upper_support) / lower_support

                    if confidence >= confidence_threshold:
                        rules[antecedent] = (consequent, confidence)

    return rules
757194
static void detectAdjacentAndPositionPatterns(int N, QrCodeCodeWordLocations matrix, FoundFeatures features) {

		for (int foo = 0; foo < 2; foo++) {
			for (int row = 0; row < N; row++) {
				int index = row * N;
				for (int col = 1; col < N; col++, index++) {
					if (matrix.data[index] == matrix.data[index + 1])
						features.adjacent++;
				}
				index = row * N;
				for (int col = 6; col < N; col++, index++) {
					if (matrix.data[index] && !matrix.data[index + 1] &&
							matrix.data[index + 2] && matrix.data[index + 3] && matrix.data[index + 4] &&
							!matrix.data[index + 5] && matrix.data[index + 6])
						features.position++;
				}
			}
			CommonOps_BDRM.transposeSquare(matrix);
		}

		// subtract out false positives by the mask applied to position patterns, timing, mode
		features.adjacent -= 8*9 + 2*9*8 + (N-18)*2;
	}
758301
def partial_ratio(s1, s2):
    """""""
    s1, s2 = utils.make_type_consistent(s1, s2)

    if len(s1) <= len(s2):
        shorter = s1
        longer = s2
    else:
        shorter = s2
        longer = s1

    m = SequenceMatcher(None, shorter, longer)
    blocks = m.get_matching_blocks()

    # each block represents a sequence of matching characters in a string
    # of the form (idx_1, idx_2, len)
    # the best partial match will block align with at least one of those blocks
    #   e.g. shorter = "abcd", longer = XXXbcdeEEE
    #   block = (1,3,3)
    #   best score === ratio("abcd", "Xbcd")
    scores = []
    for block in blocks:
        long_start = block[1] - block[0] if (block[1] - block[0]) > 0 else 0
        long_end = long_start + len(shorter)
        long_substr = longer[long_start:long_end]

        m2 = SequenceMatcher(None, shorter, long_substr)
        r = m2.ratio()
        if r > .995:
            return 100
        else:
            scores.append(r)

    return utils.intr(100 * max(scores))
856399
private static String combinatorialPatternMaker(String[] str, int str_size, int c) {
        String comb_pattern = "";
        int curr_comb = 1;
        for (int i = 0; i < str_size; i++) {
            if ((c & curr_comb) != 0) {
                comb_pattern += str[i] + "\\s";
            } else {
                comb_pattern += "[\\w]+\\s";
            }
            curr_comb = curr_comb << 1;
        }
        //System.err.println(comb_pattern);
        return comb_pattern;
    }
535542
def fasta_motif_scan( fasta_fname, input_tuples, regex_ready=False, allow_overlaps=True, file_buffer=False, molecule='dna' ):
	
	
	###################
	# validity checks #
	###################
	if not isinstance( fasta_fname, six.string_types ):
		raise TypeError( "In fasta_motif_scan, fasta_fname must be a string!" )
	elif not isinstance( molecule, six.string_types ):
		raise TypeError( "In fasta_motif_scan, molecule must be a string!" )
	elif isinstance( input_tuples, six.string_types ) or not isinstance( input_tuples, tuple ):
		raise( TypeError( "In fasta_motif_scan, input_tuples should be a tuple!" ) )
	elif not type( regex_ready ) is bool:
		raise( TypeError( "In fasta_motif_scan, regex_ready should be a bool!" ) )
	elif not type( file_buffer ) is bool:
		raise( TypeError( "In fasta_motif_scan, file_buffer should be a bool!" ) )
		
	#######################################
	# deal with temporary files if needed #
	#######################################
	if file_buffer == True:
		TMPFILE = tempfile.NamedTemporaryFile( delete = False )
		return_name = TMPFILE.name
	
	#########################
	# setup some local vars #
	#########################
	motif_seq, contig, start, end, strand = input_tuples
	
	if regex_ready == False:
		if strand == '+':
			regex_compiled = regex.compile( make_degenerate_regex( motif_seq ) )
		elif strand == '-':
			regex_compiled = regex.compile( make_degenerate_regex( rev_comp( motif_seq, molecule ) ) )
	else:
		if strand == '+':
			regex_compiled = regex.compile( motif_seq )
		elif strand == '-':
			regex_compiled = regex.compile( rev_comp( motif_seq, molecule ) )
	
	#######
	# run #
	#######
	site_count = 0
	
	if file_buffer == True:
		site_list = None
	else:
		site_list = []
	
	with pyfaidx.Fasta( fasta_fname, as_raw=True ) as FAIDX:
		sequence = str( FAIDX[contig][start:end] ).upper()
		
		for m in regex_compiled.finditer( sequence, overlapped=allow_overlaps ):
			# self, motif, contig, positionStart, strand, regexMatch, molecule='dna'
			tmp = SequenceMotif( motif_seq, contig, start, strand, m, molecule )
			
			site_count += 1
			
			if file_buffer == True:
				TMPFILE.write( "%s\n" % ( tmp ) )
			else:
				site_list.append( tmp )
	
	if file_buffer == True:
		return( input_tuples, None, return_name, site_count )
	else:
		return ( input_tuples, site_list, None, site_count )
703853
@Benchmark
  public void fizzBuzzPatternMatching() {
    IntStream.range(0, 101).forEach(
        n -> System.out.println(
            match(Tuple2.of(n % 3, n % 5))
                .when(tuple2(eq(0), eq(0))).get(() -> "FizzBuzz")
                .when(tuple2(eq(0), any())).get(y -> "Fizz")
                .when(tuple2(any(), eq(0))).get(x -> "Buzz")
                .orElse(String.valueOf(n))
                .getMatch()
        )
    );
  }
245288
private void checkPatternMatching(Map<String, PatternCacheControl> patterns, String specificPattern, String generalPattern) {
        if (PatternMatcherUtils.caseInsensitiveMatch(specificPattern, generalPattern)) {
            PatternCacheControl specificPatternDirective = patterns.get(specificPattern);
            PatternCacheControl generalPatternDirective = patterns.get(generalPattern);
            generalPatternDirective.incrementMatchingPatternCount();
            ConflictResolverUtils.resolveConflicts(specificPatternDirective, generalPatternDirective);
        }
    }