Compute the final score by sampling the 5 regions.  Four regions are sampled around the center
region.  Out of those four only the two with the smallest score are used.
347014
protected void computeScoreFive( int top[] , int middle[] , int bottom[] , int score[] , int width ) {

		// disparity as the outer loop to maximize common elements in inner loops, reducing redundant calculations
		for( int d = minDisparity; d < maxDisparity; d++ ) {

			// take in account the different in image border between the sub-regions and the effective region
			int indexSrc = (d-minDisparity)*width + (d-minDisparity) + radiusX;
			int indexDst = (d-minDisparity)*width + (d-minDisparity);
			int end = indexSrc + (width-d-4*radiusX);
			while( indexSrc < end ) {
				int s = 0;

				// sample four outer regions at the corners around the center region
				int val0 = top[indexSrc-radiusX];
				int val1 = top[indexSrc+radiusX];
				int val2 = bottom[indexSrc-radiusX];
				int val3 = bottom[indexSrc+radiusX];

				// select the two best scores from outer for regions
				if( val1 < val0 ) {
					int temp = val0;
					val0 = val1;
					val1 = temp;
				}

				if( val3 < val2 ) {
					int temp = val2;
					val2 = val3;
					val3 = temp;
				}

				if( val3 < val0 ) {
					s += val2;
					s += val3;
				} else if( val2 < val1 ) {
					s += val2;
					s += val0;
				} else {
					s += val0;
					s += val1;
				}

				score[indexDst++] = s + middle[indexSrc++];
			}
		}
	}
846129
def finalize(self):
        

        # Set the title
        self.set_title((
            "Silhouette Plot of {} Clustering for {} Samples in {} Centers"
        ).format(
            self.name, self.n_samples_, self.n_clusters_
        ))

        # Set the X and Y limits
        # The silhouette coefficient can range from -1, 1;
        # but here we scale the plot according to our visualizations

        # l_xlim and u_xlim are lower and upper limits of the x-axis,
        # set according to our calculated maximum and minimum silhouette score along with necessary padding
        l_xlim = max(-1, min(-0.1, round(min(self.silhouette_samples_) - 0.1, 1)))
        u_xlim = min(1, round(max(self.silhouette_samples_) + 0.1, 1))
        self.ax.set_xlim([l_xlim, u_xlim])

        # The (n_clusters_+1)*10 is for inserting blank space between
        # silhouette plots of individual clusters, to demarcate them clearly.
        self.ax.set_ylim([0, self.n_samples_ + (self.n_clusters_ + 1) * 10])

        # Set the x and y labels
        self.ax.set_xlabel("silhouette coefficient values")
        self.ax.set_ylabel("cluster label")

        # Set the ticks on the axis object.
        self.ax.set_yticks([])  # Clear the yaxis labels / ticks
        self.ax.xaxis.set_major_locator(ticker.MultipleLocator(0.1))
316548
def compute_rewards(self, scores):
        
        # get the k + 1 best scores in descending order
        best_scores = sorted(scores, reverse=True)[:self.k + 1]
        velocities = [best_scores[i] - best_scores[i + 1]
                      for i in range(len(best_scores) - 1)]

        # pad the list out with zeros to maintain the length of the list
        zeros = (len(scores) - self.k) * [0]
        return velocities + zeros
773564
def get_samples_with_constraints(self, init_points_count):
        
        samples = np.empty((0, self.space.dimensionality))

        while samples.shape[0] < init_points_count:
            domain_samples = self.get_samples_without_constraints(init_points_count)
            valid_indices = (self.space.indicator_constraints(domain_samples) == 1).flatten()
            if sum(valid_indices) > 0:
                valid_samples = domain_samples[valid_indices,:]
                samples = np.vstack((samples,valid_samples))

        return samples[0:init_points_count,:]
593626
def _make_sampling_sequence(n):
    # type: (int) -> List[int]
    
    seq = list(range(5))
    i = 50
    while len(seq) < n:
        seq.append(i)
        i += 50
    return seq
693074
private boolean initializeScore(List<Point2D_I32> contour , boolean loops ) {
		// Score each side
		Element<Corner> e = list.getHead();
		Element<Corner> end = loops ? null : list.getTail();
		while( e != end ) {
			if (convex && !isSideConvex(contour, e))
				return false;

			Element<Corner> n = e.next;

			double error;
			if( n == null ) {
				error = computeSideError(contour,e.object.index, list.getHead().object.index);
			} else {
				error = computeSideError(contour,e.object.index, n.object.index);
			}
			e.object.sideError = error;
			e = n;
		}

		// Compute what would happen if a side was split
		e = list.getHead();
		while( e != end ) {
			computePotentialSplitScore(contour,e,list.size() < minSides);
			e = e.next;
		}

		return true;
	}
207601
public static void marginals(final Hypergraph graph, final Hyperpotential w, final Algebra s,
            final Scores scores) {
        final int n = graph.getNodes().size();
        final double[] alpha = scores.alpha;
        final double[] beta = scores.beta;
        final double[] marginal = new double[n];
        int root = graph.getRoot().getId();
        
        // p(i) = \alpha_i * \beta_i / \beta_{root}
        for (Hypernode iNode : graph.getNodes()) {
            int i = iNode.getId();
            marginal[i] = s.divide(s.times(alpha[i], beta[i]), beta[root]); 
        }
        
        scores.marginal = marginal;
    }
169496
def fill_sampling(slice_list, N):
    
    A = [len(s.inliers) for s in slice_list]
    N_max = np.sum(A)
    if N > N_max:
        raise ValueError("Tried to draw {:d} samples from a pool of only {:d} items".format(N, N_max))
    
    samples_from = np.zeros((len(A),), dtype='int') # Number of samples to draw from each group

    remaining = N
    while remaining > 0:
        remaining_groups = np.flatnonzero(samples_from - np.array(A))
        
        if remaining < len(remaining_groups):
            np.random.shuffle(remaining_groups)
            for g in remaining_groups[:remaining]:
                samples_from[g] += 1
        else:
            # Give each group the allowed number of samples. Constrain to their max size.
            to_each = max(1, int(remaining / len(remaining_groups)))
            samples_from = np.min(np.vstack((samples_from + to_each, A)), axis=0)
        
        # Update remaining count
        remaining = int(N - np.sum(samples_from))
    if not remaining == 0:
        raise ValueError("Still {:d} samples left! This is an error in the selection.")

    # Construct index list of selected samples
    samples = []
    for s, a, n in zip(slice_list, A, samples_from):
        if a == n:
            samples.append(np.array(s.inliers)) # all
        elif a == 0:
            samples.append(np.arange([]))
        else:
            chosen = np.random.choice(s.inliers, n, replace=False)
            samples.append(np.array(chosen))
    return samples
1161865
def sample( s )
      @sum += s
      @sumsq += s * s
      if @num == 0
        @min = @max = s
      else
        @min = s if @min > s
        @max = s if @max < s
      end
      @num += 1
      @last = s
    end
893205
def _analysis_block_stats(regions, samples):
    
    prev = None
    between_sizes = []
    region_sizes = []
    for region in regions:
        if prev and prev.chrom == region.chrom:
            between_sizes.append(region.start - prev.end)
        region_sizes.append(region.end - region.start)
        prev = region
    def descriptive_stats(xs):
        if len(xs) < 2:
            return xs
        parts = ["min: %s" % min(xs),
                 "5%%: %s" % numpy.percentile(xs, 5),
                 "25%%: %s" % numpy.percentile(xs, 25),
                 "median: %s" % numpy.percentile(xs, 50),
                 "75%%: %s" % numpy.percentile(xs, 75),
                 "95%%: %s" % numpy.percentile(xs, 95),
                 "99%%: %s" % numpy.percentile(xs, 99),
                 "max: %s" % max(xs)]
        return "\n".join(["  " + x for x in parts])
    logger.info("Identified %s parallel analysis blocks\n" % len(region_sizes) +
                "Block sizes:\n%s\n" % descriptive_stats(region_sizes) +
                "Between block sizes:\n%s\n" % descriptive_stats(between_sizes))
    if len(region_sizes) == 0:
        raise ValueError("No callable regions found in: %s" %
                         (", ".join([dd.get_sample_name(x) for x in samples])))
620045
protected double computeScore( int leftX , int rightX , int centerY ) {

		double center = computeScoreRect(leftX,rightX,centerY);
		four[0] =  computeScoreRect(leftX-radiusX,rightX-radiusX,centerY-radiusY);
		four[1] =  computeScoreRect(leftX+radiusX,rightX+radiusX,centerY-radiusY);
		four[2] =  computeScoreRect(leftX-radiusX,rightX-radiusX,centerY+radiusY);
		four[3] =  computeScoreRect(leftX+radiusX,rightX+radiusX,centerY+radiusY);

		Arrays.sort(four);

		return four[0] + four[1] + center;
	}
341406
public final void sample()
  {
    long sum = _sum.getAndSet(0);
    int count = _count.getAndSet(0);

    if (count != 0)
      _value =sum / (double) count;
    else
      _value = 0;
  }
733026
private void compute() {
		getBase().setLocation(getTemplate().getAttributeSize(ScoreAttribute.MARGIN_LEFT),
				getTemplate().getAttributeSize(ScoreAttribute.MARGIN_TOP));
		cursor = (Point2D) getBase().clone();
		
		double componentWidth = 0, componentHeight = 0;
		
		//System.out.println("Passage #"+(++DEBUG));
		
		//if (m_isOutdated || (m_tuneBeforeTransposition == null))
		//	m_tuneBeforeTransposition = (Tune) m_tune.clone();
		m_isOutdated = false;
		m_music = null;
		m_tune = Tune.transpose(m_tuneBeforeTransposition,
				getTransposition());

		getEngraver().adaptToTune(m_tune, getMetrics());

		m_scoreElements.clear();
        m_scoreNoteGroups.clear();
        m_staffLines.removeAllElements();
		m_beginningNotesLinkElements.clear();
		
		currentKey = null;
		previousKey = null;
		currentClef = null;

		// clear headings, eg. titles, subtitles, composer, etc.
		m_headerAndFooterTexts.clear();
		
		byte[] headerFields = getTemplate().getHeaderFields();
        for (byte headerField : headerFields) {
            computeTextFieldToJText(headerField);
        }
		/*if (isShowTitles())*/ {
			//calculate Y position
			Iterator itHeaders = m_headerAndFooterTexts.iterator();
			double y = cursor.getY();
			double yLeft = y, yCenter = y, yRight = y;
			while (itHeaders.hasNext()) {
				JText oneText = (JText) itHeaders.next();
				//only headers
				if (oneText.getVerticalPosition()
						!= VerticalPosition.TOP)
					continue;
				byte align = oneText.getHorizontalPosition();
				//double textWidth = oneText.getWidth();
				if (align == HorizontalPosition.CENTER)
					y = Math.max(yLeft, Math.max(yCenter, yRight));
				else if (align == HorizontalPosition.RIGHT)
					y = Math.max(yRight, yCenter);
				else //LEFT || LEFT_TAB
					y = Math.max(yLeft, yCenter);
				y += oneText.getHeight();
				//now it's aligned on left, we'll recalculate
				//X later (see renderTitles)
				//for centered and right texts
				cursor.setLocation(getBase().getX(), y);
				if (align == HorizontalPosition.CENTER)
					yCenter = y;
				else if (align == HorizontalPosition.RIGHT)
					yRight = y;
				else //LEFT || LEFT_TAB
					yLeft = y;
				oneText.setBase(cursor);
			}
			//move the cursor at the max Y of the headers
			double headerHeight = Math.max(yLeft, Math.max(yCenter, yRight));
			cursor.setLocation(getBase().getX(), headerHeight);
		}

		//if tune has part, tune.getMusic() will return
		//duplicate parts when repeated
		//e.g. structure ABBA, P:A one line, P:B one line
		//getMusic() returns 4 lines
		//it's ok for audio rendition, but for graphical
		//we just need one occurence of each part.
		//m_tune.getVoice("1").setTablature(Tablature.BOUZOUKI_GREEK_TRICHORDO);
		m_music = m_tune.getMusicForGraphicalRendition();
		
		ArrayList lessThanQuarter = new ArrayList();
		//int durationInGroup = 0;
		//int maxDurationInGroup = Note.QUARTER;
		//int durationInCurrentMeasure = 0;
		Tuplet tupletContainer = null;
		// int staffLineNb = 0;
		//init attributes that are for iterating through the score of the tune.
		currentKey = m_tune.getKey();
		if (currentKey != null) {
			try {
				previousKey = (KeySignature) currentKey.clone();
			} catch (CloneNotSupportedException never) {
				never.printStackTrace();
			}
		}
		else
			previousKey = null;
        TimeSignature previousTime = null;
		currentTime = null;
		currentStaffLineInitialized = false;
		currentStaffLine = null;
		m_currentTablature = null;
        for (Object o : m_music.getVoices()) {
            Voice voice = (Voice) o;
            m_currentVoice = voice.getVoiceName();
            m_currentTablature = voice.getTablature();
            //m_currentTablature = Tablature.GUITAR;
            if (m_currentTablature != null) {
                m_currentTablature.computeFingerings(voice);
            }
            int size = 0;
            for (m_index = 0, size = voice.size(); m_index < size; m_index++) {
                MusicElement s = (MusicElement) voice.elementAt(m_index);
                //System.out.println(s.toString() + " " + s.getReference().toString());
                // ==== Notes>quarter, rests, notes without slur,tuplet ====
                if (
                        (
                                !(s instanceof Note || s instanceof MultiNote)
                                        || (s instanceof Note && ((Note) s).isRest())
                                        //if we were in a tuplet and the current note isn't part of tuplet anymore or part of another tuplet
                                        || (s instanceof NoteAbstract && tupletContainer != null && (!tupletContainer.equals(((NoteAbstract) s).getTuplet())))
                                        //if we weren't in a tuplet and the new note is part of a tuplet.
                                        || (s instanceof NoteAbstract && tupletContainer == null && ((NoteAbstract) s).isPartOfTuplet())
                                        || (s instanceof Note && ((Note) s).getStrictDuration() >= Note.QUARTER)
                                        || (s instanceof MultiNote && (!((MultiNote) s).hasUniqueStrictDuration() ||
                                        ((MultiNote) s).getLongestNote().getStrictDuration() >= Note.QUARTER)))

                                && lessThanQuarter.size() != 0) {
                    //this is is the end of the group, append the current group content to the score.
                    appendToScore(lessThanQuarter);
                    lessThanQuarter.clear();
                }
                // ==== Key signature ====
                if (s instanceof KeySignature) {
                    currentKey = (KeySignature) s;
                    currentClef = currentKey.getClef();
                    //TODO if end of staffline, add the key signture at right
                    //here or in initStaffLine?
                    if (currentStaffLineInitialized && !currentKey.equals(previousKey)) {
                        appendToScore(new JKeySignature(currentKey, previousKey, cursor, getMetrics()));
                        try {
                            previousKey = (KeySignature) currentKey.clone();
                        } catch (CloneNotSupportedException never) {
                            never.printStackTrace();
                        }
                    }
                } else
                    // ==== Time signature ====
                    if (s instanceof TimeSignature) {
                        if (currentTime != null) {
                            try {
                                previousTime = (TimeSignature) currentTime.clone();
                            } catch (CloneNotSupportedException never) {
                                never.printStackTrace();
                            }
                        }
                        currentTime = (TimeSignature) s;
                        //if (previousTime != null)
                        if (currentStaffLineInitialized && !currentTime.equals(previousTime))
                            appendToScore(new JTimeSignature(currentTime, cursor, getMetrics()));
                    } else
                        // ==== MultiNote ====
                        if (s instanceof MultiNote) {
                            NoteAbstract note = (NoteAbstract) s;
                            if (note.isBeginingSlur())
                                m_beginningNotesLinkElements.addElement(note);
                            tupletContainer = ((MultiNote) s).getTuplet();
                            Note[] tiesStart = ((MultiNote) s).getNotesBeginningTie();
                            if (tiesStart != null)
                                for (Note aTiesStart : tiesStart) {
                                    m_beginningNotesLinkElements.addElement(aTiesStart);
                                }
                            //checks if the shortest durations of the multi note is less than a quarter note.
                            // if yes, this multi note will be put into a group.
                            if (((MultiNote) s).getStrictDurations()[0] < Note.QUARTER)
                                lessThanQuarter.add(s);
                            else {
                                appendToScore(new JChord((MultiNote) s, currentClef, getMetrics(), cursor));
                            }

                            //durationInCurrentMeasure+=((MultiNote)s).getLongestNote().getDuration();
                        } //end MultiNote
                        else
                            // ==== Note ====
                            if (s instanceof Note) {
                                Note note = (Note) s;

                                if (note.isBeginingSlur() || note.isBeginningTie())
                                    m_beginningNotesLinkElements.addElement(note);
                                short strictDur = note.getStrictDuration();
                                tupletContainer = note.getTuplet();
                                // checks if this note should be part of a group.
                                if (strictDur < Note.QUARTER && !note.isRest()) {
                                    //durationInGroup+=(note).getDuration();
                                    //System.out.println("duration in group " + durationInGroup);
                                    lessThanQuarter.add(note);
                    /*if (durationInGroup>=maxDurationInGroup) {
						appendToScore(lessThanQuarter);
						lessThanQuarter.clear();
						durationInGroup = 0;
					}*/
                                } else {
                                    JNote noteR = new JNote(note, currentClef, cursor, getMetrics());
                                    //if (note.getHeight()>=Note.c)
                                    //	noteR.setStemUp(false);
                                    appendToScore(noteR);
                                }
                                //durationInCurrentMeasure+=note.getDuration();
                            } //end Note
                            else
                                // ==== RepeatBarLine ===
                                if (s instanceof RepeatBarLine) {
                                    appendToScore(new JRepeatBar((RepeatBarLine) s, cursor, getMetrics()));
                                    //durationInCurrentMeasure=0;
                                } else
                                    // ==== BarLine ====
                                    if (s instanceof BarLine) {
                                        appendToScore(new JBar((BarLine) s, cursor, getMetrics()));
                                        //durationInCurrentMeasure=0;
                                    } else
                                        // ==== EndOfStaffLine ====
                                        if (s instanceof EndOfStaffLine) {
                                            // staffLineNb++;
                                            currentStaffLineInitialized = false;
                                        } else
                                            // ==== NotesSeparator ====
                                            if (s instanceof NotesSeparator) {
                                                appendToScore(lessThanQuarter);
                                                lessThanQuarter.clear();
                                            } else
                                                // ==== Spacer ====
                                                if (s instanceof Spacer) {
                                                    appendToScore(lessThanQuarter);
                                                    lessThanQuarter.clear();
                                                    appendToScore(new JSpacer(getMetrics(), cursor, (Spacer) s));
                                                } else
                                                    // ==== Words ====
                                                    if (s instanceof Words) {
                                                        appendLyrics(new JWords(getMetrics(), (Words) s));
                                                    } else
                                                        // ==== Part label ====
                                                        if (s instanceof PartLabel) {
                                                            appendToScore(new JPartLabel(getMetrics(), cursor, (PartLabel) s));
                                                        } else
                                                            // ==== Tempo ====
                                                            if ((s instanceof Tempo)/* && (s != m_tune.getGeneralTempo())*/) {
                                                                appendToScore(new JTempo(getMetrics(), cursor, (Tempo) s));
                                                            } else
                                                                // ==== MeasureRepeat ====
                                                                if (s instanceof MeasureRepeat) {
                                                                    appendToScore(new JMeasureRepeat(getMetrics(), cursor, (MeasureRepeat) s));
                                                                }
            }//end each element in voice
        }//end each voice in music

		if (lessThanQuarter.size()!=0) {
			appendToScore(lessThanQuarter);
			lessThanQuarter.clear();
			//durationInGroup = 0;
		}

		if (isJustified())
			justify();

		cursor.setLocation(cursor.getX(),
			(currentStaffLine!=null
					?currentStaffLine.getBottomY()
					:cursor.getY())
				+getMetrics().getStaffCharBounds().getHeight());

		/*if (isShowFootNotes())*/ {
			byte[] footerFields = getTemplate().getFooterFields();
            for (byte footerField : footerFields) {
                computeTextFieldToJText(footerField);
            }
			Iterator it = m_headerAndFooterTexts.iterator();
			double height = 0;
			while (it.hasNext()) {
				JText jtext = (JText) it.next();
				if (jtext.getVerticalPosition() != VerticalPosition.BOTTOM)
					continue;
				height = jtext.getHeight();//*1.2;
				cursor.setLocation(cursor.getX(), cursor.getY()+height);
				jtext.setBase(cursor);
			}
			//a little more space for bottom baseline letters (like p, q...)
			cursor.setLocation(cursor.getX(), cursor.getY()+1);
		}

		if (m_staffLines != null) {
			double maxWidth = 0;
			for (int i=0; i<m_staffLines.size();i++) {
				JStaffLine currentStaffLine = (JStaffLine)m_staffLines.elementAt(i);
				maxWidth = Math.max(maxWidth, currentStaffLine.getWidth());
			}
			componentWidth = maxWidth + 1;
		} else {
			if (cursor.getX()>componentWidth)
				componentWidth = (int)cursor.getX() + 1;
		}
		
		//if header/footer texts are too long, extend component width
        for (Object m_headerAndFooterText : m_headerAndFooterTexts) {
            JText jt = (JText) m_headerAndFooterText;
            componentWidth = Math.max(componentWidth, jt.getWidth());
        }
		componentWidth += getTemplate().getAttributeSize(
				ScoreAttribute.MARGIN_RIGHT);
		componentHeight = (int)cursor.getY();
		componentHeight += getTemplate().getAttributeSize(
				ScoreAttribute.MARGIN_BOTTOM);

		m_width = componentWidth;
		m_height = componentHeight;
	}
1134830
private int sample(Queue<OutboundFrame> q) {
        packets.addAll(q);

        if (packets.size() < threshold) {
            return -1;
        }

        int sampleCount = min(samples, packets.size());
        int actualSampleCount = 0;
        for (int k = 0; k < sampleCount; k++) {
            OutboundFrame packet = packets.get(random.nextInt(packets.size()));
            String key = toKey(packet);

            if (key != null) {
                actualSampleCount++;
                occurrenceMap.add(key, 1);
            }
        }

        return actualSampleCount;
    }
145611
private boolean rule5(double sample) {
        if (!hasMean()) {
            return false;
        }

        if (rule5LastThree.size() == 3) {
            switch (rule5LastThree.removeLast()) {
                case ">":
                    --rule5Above;
                    break;
                case "<":
                    --rule5Below;
                    break;
            }
        }
        if (Math.abs(sample - mean.getResult()) > twoDeviations) {
            if (sample > mean.getResult()) {
                ++rule5Above;
                rule5LastThree.push(">");
            } else {
                ++rule5Below;
                rule5LastThree.push("<");
            }
        } else {
            rule5LastThree.push("");
        }

        return rule5Above >= 2 || rule5Below >= 2;
    }
699025
private void computeFirstRow(GrayS16 left, GrayS16 right ) {
		// compute horizontal scores for first row block
		for( int row = 0; row < regionHeight; row++ ) {

			int scores[] = horizontalScore[row];

			UtilDisparityScore.computeScoreRow(left, right, row, scores,
					minDisparity,maxDisparity,regionWidth,elementScore);
		}

		// compute score for the top possible row
		for( int i = 0; i < lengthHorizontal; i++ ) {
			int sum = 0;
			for( int row = 0; row < regionHeight; row++ ) {
				sum += horizontalScore[row][i];
			}
			verticalScore[i] = sum;
		}

		// compute disparity
		computeDisparity.process(radiusY, verticalScore);
	}
202881
private static double scoreToPvalue(double score, int n) {
        double T= score/Math.sqrt((1-score*score)/(n-2));
        return ContinuousDistributions.studentsCdf(T, n-2);
    }