Performs clustering.

@param ts the input time series.
@param grammarRules the grammar.
@param thresholdLength a parameter.
@param thresholdCom another parameter.
@param fractionTopDist yet another parameter.

@return pruned ruleset.
773055
public static ArrayList<SameLengthMotifs> performPruning(double[] ts, GrammarRules grammarRules,
      double thresholdLength, double thresholdCom, double fractionTopDist) {

    RuleOrganizer ro = new RuleOrganizer();

    ArrayList<SameLengthMotifs> allClassifiedMotifs = ro.classifyMotifs(thresholdLength,
        grammarRules);

    allClassifiedMotifs = ro.removeOverlappingInSimiliar(allClassifiedMotifs, grammarRules, ts,
        thresholdCom);

    ArrayList<SameLengthMotifs> newAllClassifiedMotifs = ro.refinePatternsByClustering(grammarRules,
        ts, allClassifiedMotifs, fractionTopDist);

    return newAllClassifiedMotifs;
  }
1242498
private AbstractRule processFormula(RulesTextProvider textProvider)
    {
    	log.debug("processFormula");
        Formula rule = new Formula();
        int start = textProvider.getPos();
        LoadCommonRuleData(rule,textProvider);
        textProvider.addTOCElement(null, rule.getDescription(), start, textProvider.getPos(), TYPE_FORMULA);
        exactOrError("{",textProvider);
        Expression expression = processAction(textProvider);
        exactOrError("}",textProvider);
        rule.addAction(expression);

        return rule;
    }
511983
function (threshold) {
		var axis = this,
			isLog = axis.isLog;

		var realMin = isLog ? lin2log(axis.min) : axis.min,
			realMax = isLog ? lin2log(axis.max) : axis.max;
		
		if (realMin > threshold || threshold === null) {
			threshold = realMin;
		} else if (realMax < threshold) {
			threshold = realMax;
		}

		return axis.translate(threshold, 0, 1, 0, 1);
	}
445261
public static <C extends Model> void logClusterSizes(Clustering<C> c) {
    if(!LOG.isStatistics()) {
      return;
    }
    final List<Cluster<C>> clusters = c.getAllClusters();
    final int numc = clusters.size();
    LOG.statistics(new StringStatistic(PREFIX + "name", c.getLongName()));
    LOG.statistics(new LongStatistic(PREFIX + "clusters", numc));
    Hierarchy<Cluster<C>> h = c.getClusterHierarchy();
    int cnum = 0;

    for(Cluster<C> clu : clusters) {
      final String p = PREFIX + "cluster-" + cnum + ".";
      if(clu.getName() != null) {
        LOG.statistics(new StringStatistic(p + "name", clu.getName()));
      }
      LOG.statistics(new LongStatistic(p + "size", clu.size()));
      if(clu.isNoise()) {
        LOG.statistics(new StringStatistic(p + "noise", "true"));
      }
      if(h.numChildren(clu) > 0) {
        // TODO: this only works if we have cluster names!
        StringBuilder buf = new StringBuilder();
        for(It<Cluster<C>> it = h.iterChildren(clu); it.valid(); it.advance()) {
          if(buf.length() > 0) {
            buf.append(", ");
          }
          buf.append(it.get().getName());
        }
        LOG.statistics(new StringStatistic(p + "children", buf.toString()));
      }
      // TODO: also log parents?
      ++cnum;
    }
  }
1324212
protected static <M extends Model> int[] findDepth(Clustering<M> c) {
    final Hierarchy<Cluster<M>> hier = c.getClusterHierarchy();
    int[] size = { 0, 0 };
    for(It<Cluster<M>> iter = c.iterToplevelClusters(); iter.valid(); iter.advance()) {
      findDepth(hier, iter.get(), size);
    }
    return size;
  }
504263
public SegmentedSuggestion wordSegmentation(String input, int maxEditDistance, int maxSegmentationWordLength) {
    if (input.isEmpty()) {
      return new SegmentedSuggestion();
    }
    int arraySize = Math.min(maxSegmentationWordLength, input.length());
    SegmentedSuggestion[] compositions = new SegmentedSuggestion[arraySize];
    for (int i = 0; i < arraySize; i++) {
      compositions[i] = new SegmentedSuggestion();
    }

    int circularIndex = -1;

    //outer loop (column): all possible part start positions
    for (int j = 0; j < input.length(); j++) {
      //inner loop (row): all possible part lengths (from start position): part can't be bigger than longest word in dictionary (other than long unknown word)
      int imax = Math.min(input.length() - j, maxSegmentationWordLength);
      for (int i = 1; i <= imax; i++) {
        //get top spelling correction/ed for part
        String part = input.substring(j, j + i);
        int separatorLength = 0;
        int topEd = 0;
        double topProbabilityLog;
        String topResult;

        if (Character.isWhitespace(part.charAt(0))) {
          //remove space for levensthein calculation
          part = part.substring(1);
        } else {
          //add ed+1: space did not exist, had to be inserted
          separatorLength = 1;
        }

        //remove space from part1, add number of removed spaces to topEd
        topEd += part.length();
        //remove space
        part = part.replace(" ", ""); //=System.Text.RegularExpressions.Regex.Replace(part1, @"\s+", "");
        //add number of removed spaces to ed
        topEd -= part.length();

        List<SuggestItem> results = this.lookup(part, SymSpell.Verbosity.Top, maxEditDistance);
        if (results.size() > 0) {
          topResult = results.get(0).term;
          topEd += results.get(0).distance;
          //Naive Bayes Rule
          //we assume the word probabilities of two words to be independent
          //therefore the resulting probability of the word combination is the product of the two word probabilities

          //instead of computing the product of probabilities we are computing the sum of the logarithm of probabilities
          //because the probabilities of words are about 10^-10, the product of many such small numbers could exceed (underflow) the floating number range and become zero
          //log(ab)=log(a)+log(b)
          topProbabilityLog = Math.log10((double) results.get(0).count / (double) N);
        } else {
          topResult = part;
          //default, if word not found
          //otherwise long input text would win as long unknown word (with ed=edmax+1 ), although there there should many spaces inserted
          topEd += part.length();
          topProbabilityLog = Math.log10(10.0 / (N * Math.pow(10.0, part.length())));
        }

        int destinationIndex = ((i + circularIndex) % arraySize);

        //set values in first loop
        if (j == 0) {
          compositions[destinationIndex].segmentedString = part;
          compositions[destinationIndex].correctedString = topResult;
          compositions[destinationIndex].distanceSum = topEd;
          compositions[destinationIndex].probabilityLogSum = topProbabilityLog;
        } else if ((i == maxSegmentationWordLength)
          //replace values if better probabilityLogSum, if same edit distance OR one space difference
          || (((compositions[circularIndex].distanceSum + topEd == compositions[destinationIndex].distanceSum) || (compositions[circularIndex].distanceSum + separatorLength + topEd == compositions[destinationIndex].distanceSum)) && (compositions[destinationIndex].probabilityLogSum < compositions[circularIndex].probabilityLogSum + topProbabilityLog))
          //replace values if smaller edit distance
          || (compositions[circularIndex].distanceSum + separatorLength + topEd < compositions[destinationIndex].distanceSum)) {
          compositions[destinationIndex].segmentedString = compositions[circularIndex].segmentedString + " " + part;
          compositions[destinationIndex].correctedString = compositions[circularIndex].correctedString + " " + topResult;
          compositions[destinationIndex].distanceSum = compositions[circularIndex].distanceSum + topEd;
          compositions[destinationIndex].probabilityLogSum = compositions[circularIndex].probabilityLogSum + topProbabilityLog;
        }
      }
      circularIndex++;
      if (circularIndex >= arraySize) {
        circularIndex = 0;
      }
    }
    return compositions[circularIndex];

  }
847939
private int reduceNondominatedSet(double[][] front, int noPoints, int objective,
                                    double threshold) {
    int n;
    int i;

    n = noPoints;
    for (i = 0; i < n; i++) {
      if (front[i][objective] <= threshold) {
        n--;
        swap(front, i, n);
      }
    }

    return n;
  }
994953
public final void ruleJvmLowerBound() throws RecognitionException {

        		int stackSize = keepStackSize();
        	
        try {
            // InternalXtype.g:271:2: ( ( ( rule__JvmLowerBound__Group__0 ) ) )
            // InternalXtype.g:272:2: ( ( rule__JvmLowerBound__Group__0 ) )
            {
            // InternalXtype.g:272:2: ( ( rule__JvmLowerBound__Group__0 ) )
            // InternalXtype.g:273:3: ( rule__JvmLowerBound__Group__0 )
            {
            if ( state.backtracking==0 ) {
               before(grammarAccess.getJvmLowerBoundAccess().getGroup()); 
            }
            // InternalXtype.g:274:3: ( rule__JvmLowerBound__Group__0 )
            // InternalXtype.g:274:4: rule__JvmLowerBound__Group__0
            {
            pushFollow(FOLLOW_2);
            rule__JvmLowerBound__Group__0();

            state._fsp--;
            if (state.failed) return ;

            }

            if ( state.backtracking==0 ) {
               after(grammarAccess.getJvmLowerBoundAccess().getGroup()); 
            }

            }


            }

        }
        catch (RecognitionException re) {
            reportError(re);
            recover(input,re);
        }
        finally {

            	restoreStackSize(stackSize);

        }
        return ;
    }
123159
public void setRestrictions(List<IRule> rulesNew) throws CDKException {

        Iterator<IRule> itRules = rulesNew.iterator();
        while (itRules.hasNext()) {
            IRule rule = itRules.next();
            if (rule instanceof ElementRule) {
                mfRange = (MolecularFormulaRange) ((Object[]) rule.getParameters())[0];

                //removing the rule
                Iterator<IRule> oldRuleIt = rules.iterator();
                while (oldRuleIt.hasNext()) {
                    IRule oldRule = oldRuleIt.next();
                    if (oldRule instanceof ElementRule) {
                        rules.remove(oldRule);
                        rules.add(rule);
                        break;
                    }
                }
                this.matrix_Base = getMatrix(mfRange.getIsotopeCount());
            } else if (rule instanceof ChargeRule) {
                this.charge = (Double) ((Object[]) rule.getParameters())[0];

                //removing the rule
                Iterator<IRule> oldRuleIt = rules.iterator();
                while (oldRuleIt.hasNext()) {
                    IRule oldRule = oldRuleIt.next();
                    if (oldRule instanceof ChargeRule) {
                        rules.remove(oldRule);
                        rules.add(rule);
                        break;
                    }
                }
            } else if (rule instanceof ToleranceRangeRule) {
                this.tolerance = (Double) ((Object[]) rule.getParameters())[1];
                //removing the rule
                Iterator<IRule> oldRuleIt = rules.iterator();
                while (oldRuleIt.hasNext()) {
                    IRule oldRule = oldRuleIt.next();
                    if (oldRule instanceof ToleranceRangeRule) {
                        rules.remove(oldRule);
                        rules.add(rule);
                        break;
                    }
                }
            } else {
                rules.add(rule);
            }

        }
    }
376546
protected void segmentAfterRule(String sentence, String normalized, List<String> wordList)
    {
        if (!enableRuleBasedSegment)
        {
            segmenter.segment(sentence, normalized, wordList);
            return;
        }
        int start = 0;
        int end = start;
        byte preType = typeTable[normalized.charAt(end)];
        byte curType;
        while (++end < normalized.length())
        {
            curType = typeTable[normalized.charAt(end)];
            if (curType != preType)
            {
                if (preType == CharType.CT_NUM)
                {
                    // 浮点数识别
                    if ("，,．.".indexOf(normalized.charAt(end)) != -1)
                    {
                        if (end + 1 < normalized.length())
                        {
                            if (typeTable[normalized.charAt(end + 1)] == CharType.CT_NUM)
                            {
                                continue;
                            }
                        }
                    }
                    else if ("年月日时分秒".indexOf(normalized.charAt(end)) != -1)
                    {
                        preType = curType; // 交给统计分词
                        continue;
                    }
                }
                pushPiece(sentence, normalized, start, end, preType, wordList);
                start = end;
            }
            preType = curType;
        }
        if (end == normalized.length())
            pushPiece(sentence, normalized, start, end, preType, wordList);
    }
57421
static final int computeMinLgArrLongsFromCount(final int count) {
    final int upperCount = (int) Math.ceil(count / REBUILD_THRESHOLD);
    final int arrLongs = max(ceilingPowerOf2(upperCount), 1 << MIN_LG_ARR_LONGS);
    final int newLgArrLongs = Integer.numberOfTrailingZeros(arrLongs);
    return newLgArrLongs;
  }
6580
public static <T extends Comparable<T>> RangeSet<T> unionRanges(final Iterable<Range<T>> ranges)
  {
    RangeSet<T> rangeSet = null;
    for (Range<T> range : ranges) {
      if (rangeSet == null) {
        rangeSet = TreeRangeSet.create();
      }
      rangeSet.add(range);
    }
    return rangeSet;
  }
382532
public List<Type> subst(List<Type> ts,
                            List<Type> from,
                            List<Type> to) {
        return ts.map(new Subst(from, to));
    }
1013857
private String[] splitIntoPlusMinusPatterns(AmountFormatContext amountFormatContext, String pattern) {
        DecimalFormatSymbols decimalFormatSymbols = amountFormatContext.get(DecimalFormatSymbols.class);
        char patternSeparator = decimalFormatSymbols != null ? decimalFormatSymbols.getPatternSeparator() : SUBPATTERN_BOUNDARY;
        return pattern.split(String.valueOf(patternSeparator));
    }
18388
public final void ruleTerminalToken() throws RecognitionException {

        		int stackSize = keepStackSize();
        	
        try {
            // InternalXtext.g:1183:2: ( ( ( rule__TerminalToken__Group__0 ) ) )
            // InternalXtext.g:1184:2: ( ( rule__TerminalToken__Group__0 ) )
            {
            // InternalXtext.g:1184:2: ( ( rule__TerminalToken__Group__0 ) )
            // InternalXtext.g:1185:3: ( rule__TerminalToken__Group__0 )
            {
             before(grammarAccess.getTerminalTokenAccess().getGroup()); 
            // InternalXtext.g:1186:3: ( rule__TerminalToken__Group__0 )
            // InternalXtext.g:1186:4: rule__TerminalToken__Group__0
            {
            pushFollow(FollowSets000.FOLLOW_2);
            rule__TerminalToken__Group__0();

            state._fsp--;


            }

             after(grammarAccess.getTerminalTokenAccess().getGroup()); 

            }


            }

        }
        catch (RecognitionException re) {
            reportError(re);
            recover(input,re);
        }
        finally {

            	restoreStackSize(stackSize);

        }
        return ;
    }
704761
public void process(StringBuilder buf, NFRuleSet ruleSet) {
        // markers depend on what rule set we are using

        // Commented by johnvu on the if statement since lastRuleSet is never initialized
        //if (ruleSet != lastRuleSet) {
            String name = ruleSet.getName();
            for (int i = 0; i < rulesetNames.length; ++i) {
                if (rulesetNames[i].equals(name)) {
                    format = i;
                    longForm = i == 1 || i == 3;
                    break;
                }
            }
        //}

        if (longForm) {
            for (int i = buf.indexOf("*"); i != -1; i = buf.indexOf("*", i)) {
                buf.delete(i, i+1);
            }
            return;
        }

        final String DIAN = "\u9ede"; // decimal point

        final String[][] markers = {
            { "\u842c", "\u5104", "\u5146", "\u3007" }, // marker chars, last char is the 'zero'
            { "\u4e07", "\u4ebf", "\u5146", "\u3007" },
            { "\u842c", "\u5104", "\u5146", "\u96f6" }
            // need markers for time?
        };

        // remove unwanted lings
        // a '0' (ling) with * might be removed
        // mark off 10,000 'chunks', markers are Z, Y, W (zhao, yii, and wan)
        // already, we avoid two lings in the same chunk -- ling without * wins
        // now, just need  to avoid optional lings in adjacent chunks
        // process right to left

        // decision matrix:
        // state, situation
        //     state         none       opt.          req.
        //     -----         ----       ----          ----
        // none to right     none       opt.          req.  
        // opt. to right     none   clear, none  clear right, req.
        // req. to right     none   clear, none       req.

        // mark chunks with '|' for convenience
        {
            String[] m = markers[format];
            for (int i = 0; i < m.length-1; ++i) {
                int n = buf.indexOf(m[i]);
                if (n != -1) {
                    buf.insert(n+m[i].length(), '|');
                }
            }
        }

        int x = buf.indexOf(DIAN);
        if (x == -1) {
            x = buf.length();
        }
        int s = 0; // 0 = none to right, 1 = opt. to right, 2 = req. to right
        int n = -1; // previous optional ling
        String ling = markers[format][3];
        while (x >= 0) {
            int m = buf.lastIndexOf("|", x);
            int nn = buf.lastIndexOf(ling, x);
            int ns = 0;
            if (nn > m) {
                ns = (nn > 0 && buf.charAt(nn-1) != '*') ? 2 : 1;
            }
            x = m - 1;

            // actually much simpler, but leave this verbose for now so it's easier to follow
            switch (s*3+ns) {
            case 0: /* none, none */
                s = ns; // redundant
                n = -1;
                break;
            case 1: /* none, opt. */
                s = ns;
                n = nn; // remember optional ling to right
                break;
            case 2: /* none, req. */
                s = ns;
                n = -1;
                break;
            case 3: /* opt., none */
                s = ns;
                n = -1;
                break;
            case 4: /* opt., opt. */
                buf.delete(nn-1, nn+ling.length()); // delete current optional ling
                s = 0;
                n = -1;
                break;
            case 5: /* opt., req. */
                buf.delete(n-1, n+ling.length()); // delete previous optional ling
                s = ns;
                n = -1;
                break;
            case 6: /* req., none */
                s = ns;
                n = -1;
                break;
            case 7: /* req., opt. */
                buf.delete(nn-1, nn+ling.length()); // delete current optional ling
                s = 0;
                n = -1;
                break;
            case 8: /* req., req. */
                s = ns;
                n = -1;
                break;
            default:
                throw new IllegalStateException();
            }
        }

        for (int i = buf.length(); --i >= 0;) {
            char c = buf.charAt(i);
            if (c == '*' || c == '|') {
                buf.delete(i, i+1);
            }
        }
    }
251474
def _check_boundaries(self, fragment):
        
        if not isinstance(fragment, SyncMapFragment):
            raise TypeError(u"fragment is not an instance of SyncMapFragment")
        interval = fragment.interval
        if not isinstance(interval, TimeInterval):
            raise TypeError(u"interval is not an instance of TimeInterval")
        if (self.begin is not None) and (interval.begin < self.begin):
            raise ValueError(u"interval.begin is before self.begin")
        if (self.end is not None) and (interval.end > self.end):
            raise ValueError(u"interval.end is after self.end")