Return the bottom most (Y) point, first staff line +
lyrics line + tablature + ...
507180
protected double getBottomY() {
		//TODO add space for lyrics, low notes...
		double ret = get1stLineY();
		if (m_tablature != null) {
			ret += getTemplate().getAttributeSize(ScoreAttribute.TABLATURE_SPACING);
			ret += m_tablature.getHeight();
		}
		return ret;
	}
2724
def lbrt(self):
        """"""
        return self._left, self._bottom, self._right, self._top
921012
def find_side(ls, side):
    
    minx, miny, maxx, maxy = ls.bounds
    points = {'left': [(minx, miny), (minx, maxy)],
              'right': [(maxx, miny), (maxx, maxy)],
              'bottom': [(minx, miny), (maxx, miny)],
              'top': [(minx, maxy), (maxx, maxy)],}
    return sgeom.LineString(points[side])
115810
def begin_track(tuning, padding=2):
    """"""
    # find longest shorthand tuning base
    names = [x.to_shorthand() for x in tuning.tuning]
    basesize = len(max(names)) + 3

    # Build result
    res = []
    for x in names:
        r = ' %s' % x
        spaces = basesize - len(r)
        r += ' ' * spaces + '||' + '-' * padding
        res.append(r)
    return res
152704
def read_query_notes(query_str, first_line=False):
    
    lines = query_str.split("\n")
    started = False
    parts = []
    for line in lines:
        line = line.strip()
        if line.startswith("#"):
            parts.append(line)
            started = True
            if first_line:
                break
        if started and line and not line.startswith("#"):
            break
    return "\n".join(parts)
1139946
def get_current_line(self):
        """"""
        cursor = self.textCursor()
        cursor.select(QTextCursor.BlockUnderCursor)
        return to_text_string(cursor.selectedText())
977595
def get_range_string(self):
    """"""
    return self.left.chr+":"+str(self.left.end)+'/'+self.right.chr+":"+str(self.right.start)
1320855
def _get_column_ends(self):
        '''
        '''
        ends = collections.Counter()
        for line in self.text.splitlines():
            for matchobj in re.finditer('\s{2,}', line.lstrip()):
                ends[matchobj.end()] += 1
        return ends
398285
function getLeftmost(start) {
        var p = start, leftmost = start;
        do {
            if (p.x < leftmost.x)
                leftmost = p;
            p = p.next;
        } while (p !== start);
        return leftmost;
    }
599393
def _get_selectable(self):
        '''
        
        '''
        # Save some typing
        cursong = self.loop[self.song][0]
        
        if self.dif_song and len(cursong) > 1:
            # Position is relative to the intro of the track,
            # so we we will get the both the intro and body.
            s = cursong[0] + cursong[1]
        else:
            # Position is relative to the body of the track, so just get that.
            s = cursong[-1]
        # Return what we found
        return s
1303406
function positionToOffset(str, desiredLine, desiredCol) {
    if (desiredLine === 1) {
        return desiredCol - 1;
    }
    let line = 1;
    let lastNewLineOffset = -1;
    do {
        if (desiredLine === line) {
            return lastNewLineOffset + 1 + desiredCol - 1;
        }
        lastNewLineOffset = str.indexOf('\n', lastNewLineOffset + 1);
        line++;
    } while (lastNewLineOffset >= 0);
    return -1;
}
1020663
def box(text):
    
    """
    lines = text.split('\n')

    width = max(len(l) for l in lines)
    top_bar = (TOP_LEFT_CORNER + HORIZONTAL_BAR * (2 + width) +
               TOP_RIGHT_CORNER)
    bottom_bar = (BOTTOM_LEFT_CORNER + HORIZONTAL_BAR * (2 + width) +
                  BOTTOM_RIGHT_CORNER)

    lines = [LINES_FORMAT_STR.format(line=line, width=width) for line in lines]

    return top_bar + '\n' + '\n'.join(lines) + '\n' + bottom_bar
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;
	}
1306473
def get_curr_lines(self):
        
        start = max(0, self._coord.line - 5)
        end = min(len(self._template_lines), self._coord.line + 4)

        lines = [(x, self._template_lines[x]) for x in six.moves.range(start, end, 1)]
        return self._coord.line, lines
897569
def boardToString(self, margins=None):
        
        if margins is None:
            margins = {}

        b = self.board
        rg = range(b.size())
        left = ' '*margins.get('left', 0)
        s = '\n'.join(
            [left + ' '.join([self.getCellStr(x, y) for x in rg]) for y in rg])
        return s
488660
def pretty(self,verbose=0):
        """"""
        # split prompt lines and add blanks in later lines to align them
        plines = self.prompt.split('\n')
        for i in range(len(plines)-1): plines[i+1] = 32*' ' + plines[i+1]
        plines = '\n'.join(plines)
        namelen = min(len(self.name), 12)
        pvalue = self.get(prompt=0,lpar=1)
        alwaysquoted = ['s', 'f', '*gcur', '*imcur', '*ukey', 'pset']
        if self.type in alwaysquoted and self.value is not None: pvalue = '"' + pvalue + '"'
        if self.mode == "h":
            s = "%13s = %-15s %s" % ("("+self.name[:namelen],
                                    pvalue+")", plines)
        else:
            s = "%13s = %-15s %s" % (self.name[:namelen],
                                    pvalue, plines)
        if not verbose: return s

        if self.choice is not None:
            s = s + "\n" + 32*" " + "|"
            nline = 33
            for i in range(len(self.choice)):
                sch = str(self.choice[i]) + "|"
                s = s + sch
                nline = nline + len(sch) + 1
                if nline > 80:
                    s = s + "\n" + 32*" " + "|"
                    nline = 33
        elif self.min not in [None, INDEF] or self.max not in [None, INDEF]:
            s = s + "\n" + 32*" "
            if self.min not in [None, INDEF]:
                s = s + str(self.min) + " <= "
            s = s + self.name
            if self.max not in [None, INDEF]:
                s = s + " <= " + str(self.max)
        return s
1343898
def to_bb(YY, y="deprecated"):
    """"""
    cols,rows = np.nonzero(YY)
    if len(cols)==0: return np.zeros(4, dtype=np.float32)
    top_row = np.min(rows)
    left_col = np.min(cols)
    bottom_row = np.max(rows)
    right_col = np.max(cols)
    return np.array([left_col, top_row, right_col, bottom_row], dtype=np.float32)