Best Python code snippet using fMBT_python
test_pitch.py
Source:test_pitch.py  
1# -*- coding: utf-8 -*-2# ------------------------------------------------------------------------------3# Name:         test.test_pitch.py4# Purpose:      music21 tests for pitches5#6# Authors:      Michael Scott Asato Cuthbert7#               Christopher Ariza8#9# Copyright:    Copyright © 2008-2022 Michael Scott Asato Cuthbert and the music21 Project10# License:      BSD, see license.txt11# ------------------------------------------------------------------------------12import copy13import sys14import types15import unittest16from music21 import common17from music21 import converter18from music21 import corpus19from music21 import key20from music21 import note21from music21 import pitch22from music21 import scale23from music21 import stream24from music21.musicxml import m21ToXml25from music21.pitch import Pitch, Accidental26class Test(unittest.TestCase):27    def testCopyAndDeepcopy(self):28        '''29        Test copying all objects defined in this module30        '''31        for part in sys.modules[self.__module__].__dict__:32            match = False33            for skip in ['_', '__', 'Test', 'Exception']:34                if part.startswith(skip) or part.endswith(skip):35                    match = True36            if match:37                continue38            name = getattr(sys.modules[self.__module__], part)39            # noinspection PyTypeChecker40            if callable(name) and not isinstance(name, types.FunctionType):41                try:  # see if obj can be made w/ args42                    obj = name()43                except TypeError:44                    continue45                copy.copy(obj)46                copy.deepcopy(obj)47        p1 = Pitch('C#3')48        p2 = copy.deepcopy(p1)49        self.assertIsNot(p1, p2)50        self.assertIsNot(p1.accidental, p2.accidental)51    def testRepr(self):52        p = pitch.Pitch('B#3')53        self.assertEqual(repr(p), '<music21.pitch.Pitch B#3>')54    def testOctave(self):55        b = Pitch('B#3')56        self.assertEqual(b.octave, 3)57    def testAccidentalImport(self):58        '''Test that we are getting the properly set accidentals59        '''60        s = corpus.parse('bwv438.xml')61        tenorMeasures = s.parts[2].getElementsByClass(stream.Measure)62        pAltered = tenorMeasures[0].pitches[1]63        self.assertEqual(pAltered.accidental.name, 'flat')64        self.assertEqual(pAltered.accidental.displayType, 'normal')65        # in key signature, so should not be shown66        self.assertFalse(pAltered.accidental.displayStatus)67        altoM6 = s.parts[1].measure(6)68        pAltered = altoM6.pitches[2]69        self.assertEqual(pAltered.accidental.name, 'sharp')70        self.assertTrue(pAltered.accidental.displayStatus)71    def testUpdateAccidentalDisplaySimple(self):72        '''Test updating accidental display.73        '''74        past = [Pitch('A#3'), Pitch('C#'), Pitch('C')]75        a = Pitch('c')76        a.accidental = Accidental('natural')77        a.accidental.displayStatus = True78        self.assertEqual(a.name, 'C')79        self.assertTrue(a.accidental.displayStatus)80        a.updateAccidentalDisplay(pitchPast=past, overrideStatus=True)81        self.assertFalse(a.accidental.displayStatus)82        b = copy.deepcopy(a)83        self.assertFalse(b.accidental.displayStatus)84        self.assertEqual(b.accidental.name, 'natural')85    def testUpdateAccidentalDisplaySeries(self):86        '''Test updating accidental display.87        '''88        def proc(_pList, past):89            for p in _pList:90                p.updateAccidentalDisplay(pitchPast=past)91                past.append(p)92        def compare(past, _result):93            # environLocal.printDebug(['accidental compare'])94            for i in range(len(_result)):95                p = past[i]96                if p.accidental is None:97                    pName = None98                    pDisplayStatus = None99                else:100                    pName = p.accidental.name101                    pDisplayStatus = p.accidental.displayStatus102                targetName = _result[i][0]103                targetDisplayStatus = _result[i][1]104                self.assertEqual(pName, targetName,105                                 f'name error for {i}: {pName} instead of desired {targetName}')106                self.assertEqual(107                    pDisplayStatus,108                    targetDisplayStatus,109                    f'{i}: {p} display: {pDisplayStatus}, target {targetDisplayStatus}'110                )111        # alternating, in a sequence, same pitch space112        pList = [Pitch('a#3'), Pitch('a3'), Pitch('a#3'),113                 Pitch('a3'), Pitch('a#3')]114        result = [('sharp', True), ('natural', True), ('sharp', True),115                  ('natural', True), ('sharp', True)]116        proc(pList, [])117        compare(pList, result)118        # alternating, in a sequence, different pitch space119        pList = [Pitch('a#2'), Pitch('a6'), Pitch('a#1'),120                 Pitch('a5'), Pitch('a#3')]121        result = [('sharp', True), ('natural', True), ('sharp', True),122                  ('natural', True), ('sharp', True)]123        proc(pList, [])124        compare(pList, result)125        # alternating, after gaps126        pList = [Pitch('a-2'), Pitch('g3'), Pitch('a5'),127                 Pitch('a#5'), Pitch('g-3'), Pitch('a3')]128        result = [('flat', True), (None, None), ('natural', True),129                  ('sharp', True), ('flat', True), ('natural', True)]130        proc(pList, [])131        compare(pList, result)132        # repeats of the same: show at different registers133        pList = [Pitch('a-2'), Pitch('a-2'), Pitch('a-5'),134                 Pitch('a#5'), Pitch('a#3'), Pitch('a3'), Pitch('a2')]135        result = [('flat', True), ('flat', False), ('flat', True),136                  ('sharp', True), ('sharp', True), ('natural', True), ('natural', True)]137        proc(pList, [])138        compare(pList, result)139        # the always- 'unless-repeated' setting140        # first, with no modification, repeated accidentals are not shown141        pList = [Pitch('a-2'), Pitch('a#3'), Pitch('a#5')]142        result = [('flat', True), ('sharp', True), ('sharp', True)]143        proc(pList, [])144        compare(pList, result)145        # second, with status set to always146        pList = [Pitch('a-2'), Pitch('a#3'), Pitch('a#3')]147        pList[2].accidental.displayType = 'always'148        result = [('flat', True), ('sharp', True), ('sharp', True)]149        proc(pList, [])150        compare(pList, result)151        # status set to always152        pList = [Pitch('a2'), Pitch('a3'), Pitch('a5')]153        pList[2].accidental = Accidental('natural')154        pList[2].accidental.displayType = 'always'155        result = [(None, None), (None, None), ('natural', True)]156        proc(pList, [])157        compare(pList, result)158        # first use after other pitches in different register159        # note: this will force the display of the accidental160        pList = [Pitch('a-2'), Pitch('g3'), Pitch('a-5')]161        result = [('flat', True), (None, None), ('flat', True)]162        proc(pList, [])163        compare(pList, result)164        # first use after other pitches in different register165        # note: this will force the display of the accidental166        pList = [Pitch('a-2'), Pitch('g3'), Pitch('a-2')]167        # pairs of accidental, displayStatus168        result = [('flat', True), (None, None), ('flat', True)]169        proc(pList, [])170        compare(pList, result)171        # accidentals, first usage, not first pitch172        pList = [Pitch('a2'), Pitch('g#3'), Pitch('d-2')]173        result = [(None, None), ('sharp', True), ('flat', True)]174        proc(pList, [])175        compare(pList, result)176    def testUpdateAccidentalDisplaySeriesKeySignature(self):177        '''Test updating accidental display against a KeySignature178        '''179        def proc(_pList, past, alteredPitches):180            for p in _pList:181                p.updateAccidentalDisplay(pitchPast=past, alteredPitches=alteredPitches)182                past.append(p)183        def compare(past, _result):184            # environLocal.printDebug(['accidental compare'])185            for i in range(len(_result)):186                p = past[i]187                if p.accidental is None:188                    pName = None189                    pDisplayStatus = None190                else:191                    pName = p.accidental.name192                    pDisplayStatus = p.accidental.displayStatus193                targetName = _result[i][0]194                targetDisplayStatus = _result[i][1]195                # environLocal.printDebug(['accidental test:', p, pName,196                #         pDisplayStatus, 'target:', targetName, targetDisplayStatus])197                self.assertEqual(pName, targetName)198                self.assertEqual(199                    pDisplayStatus,200                    targetDisplayStatus,201                    f'{i}: {p} display: {pDisplayStatus}, target {targetDisplayStatus}'202                )203        # chromatic alteration of key204        pList = [Pitch('f#3'), Pitch('f#2'), Pitch('f3'),205                 Pitch('f#3'), Pitch('f#3'), Pitch('g3'), Pitch('f#3')]206        result = [('sharp', False), ('sharp', False), ('natural', True),207                  ('sharp', True), ('sharp', False), (None, None), ('sharp', False)]208        ks = key.KeySignature(1)  # f3209        proc(pList, [], ks.alteredPitches)210        compare(pList, result)211        # non initial scale tones212        pList = [Pitch('a3'), Pitch('b2'), Pitch('c#3'),213                 Pitch('f#3'), Pitch('g#3'), Pitch('f#3'), Pitch('a4')]214        result = [(None, None), (None, None), ('sharp', False),215                  ('sharp', False), ('sharp', False), ('sharp', False), (None, None)]216        ks = key.KeySignature(3)217        proc(pList, [], ks.alteredPitches)218        compare(pList, result)219        # non-initial scale tones with chromatic alteration220        pList = [Pitch('a3'), Pitch('c#3'), Pitch('g#3'),221                 Pitch('g3'), Pitch('c#4'), Pitch('g#4')]222        result = [(None, None), ('sharp', False), ('sharp', False),223                  ('natural', True), ('sharp', False), ('sharp', True)]224        ks = key.KeySignature(3)225        proc(pList, [], ks.alteredPitches)226        compare(pList, result)227        # non-initial scale tones with chromatic alteration228        pList = [Pitch('a3'), Pitch('c#3'), Pitch('g#3'),229                 Pitch('g3'), Pitch('c#4'), Pitch('g#4')]230        result = [(None, None), ('sharp', False), ('sharp', False),231                  ('natural', True), ('sharp', False), ('sharp', True)]232        ks = key.KeySignature(3)233        proc(pList, [], ks.alteredPitches)234        compare(pList, result)235        # initial scale tones with chromatic alteration, repeated tones236        pList = [Pitch('f#3'), Pitch('f3'), Pitch('f#3'),237                 Pitch('g3'), Pitch('f#4'), Pitch('f#4')]238        result = [('sharp', False), ('natural', True), ('sharp', True),239                   (None, None), ('sharp', True), ('sharp', False)]240        # no 4 is a dicey affair; could go either way241        ks = key.KeySignature(1)242        proc(pList, [], ks.alteredPitches)243        compare(pList, result)244        # initial scale tones with chromatic alteration, repeated tones245        pList = [Pitch('d3'), Pitch('e3'), Pitch('f#3'),246                 Pitch('g3'), Pitch('f4'), Pitch('g#4'),247                 Pitch('c#3'), Pitch('f#4'), Pitch('c#4')]248        result = [(None, None), (None, None), ('sharp', False),249                  (None, None), ('natural', True), ('sharp', True),250                  ('sharp', False), ('sharp', True), ('sharp', False)]251        ks = key.KeySignature(2)252        proc(pList, [], ks.alteredPitches)253        compare(pList, result)254        # altered tones outside of key255        pList = [Pitch('b3'), Pitch('a3'), Pitch('e3'),256                 Pitch('b-3'), Pitch('a-3'), Pitch('e-3'),257                 Pitch('b-3'), Pitch('a-3'), Pitch('e-3'),258                 Pitch('b-3'), Pitch('a-3'), Pitch('e-3')]259        result = [260            ('natural', True), ('natural', True), ('natural', True),261            ('flat', True), ('flat', True), ('flat', True),262            ('flat', False), ('flat', False), ('flat', False),263            ('flat', False), ('flat', False), ('flat', False),264        ]265        ks = key.KeySignature(-3)  # b-, e-, a-266        proc(pList, [], ks.alteredPitches)267        compare(pList, result)268        # naturals against the key signature are required for each and every use269        pList = [Pitch('b3'), Pitch('a3'), Pitch('e3'),270                 Pitch('b4'), Pitch('a-3'), Pitch('e-3'),271                 Pitch('b3'), Pitch('a3'), Pitch('e3')]272        result = [('natural', True), ('natural', True), ('natural', True),273                  ('natural', True), ('flat', True), ('flat', True),274                  ('natural', True), ('natural', True), ('natural', True)]275        ks = key.KeySignature(-3)  # b-, e-, a-276        proc(pList, [], ks.alteredPitches)277        compare(pList, result)278    def testUpdateAccidentalDisplayOctaves(self):279        '''280        test if octave display is working281        '''282        def proc1(_pList, _past):283            for p in _pList:284                p.updateAccidentalDisplay(pitchPast=_past, cautionaryPitchClass=True,285                                          cautionaryNotImmediateRepeat=False)286                _past.append(p)287        def proc2(_pList, _past):288            for p in _pList:289                p.updateAccidentalDisplay(pitchPast=_past, cautionaryPitchClass=False,290                                          cautionaryNotImmediateRepeat=False)291                _past.append(p)292        def compare(_past, _result):293            # environLocal.printDebug(['accidental compare'])294            for i in range(len(_result)):295                p = _past[i]296                if p.accidental is None:297                    pName = None298                    pDisplayStatus = None299                else:300                    pName = p.accidental.name301                    pDisplayStatus = p.accidental.displayStatus302                targetName = _result[i][0]303                targetDisplayStatus = _result[i][1]304                self.assertEqual(pName, targetName)305                self.assertEqual(306                    pDisplayStatus,307                    targetDisplayStatus,308                    f'{i}: {p} display: {pDisplayStatus}, target {targetDisplayStatus}'309                )310        pList = [Pitch('c#3'), Pitch('c#4'), Pitch('c#3'),311                 Pitch('c#4')]312        result = [('sharp', True), ('sharp', True), ('sharp', False),313                  ('sharp', False)]314        proc1(pList, [])315        compare(pList, result)316        pList = [Pitch('c#3'), Pitch('c#4'), Pitch('c#3'),317                 Pitch('c#4')]318        proc2(pList, [])319        compare(pList, result)320        a4 = Pitch('a4')321        past = [Pitch('a#3'), Pitch('c#'), Pitch('c')]322        # will not add a natural because match is pitchSpace323        a4.updateAccidentalDisplay(pitchPast=past, cautionaryPitchClass=False)324        self.assertEqual(a4.accidental, None)325    def testAccidentalsCautionary(self):326        '''327        a nasty test provided by Jose Cabal-Ugaz about octave leaps,328        cautionaryNotImmediateRepeat=False329        and key signature conflicts.330        '''331        bm = converter.parse("tinynotation: 4/4 fn1 fn1 e-8 e'-8 fn4 en4 e'n4").flatten()332        bm.insert(0, key.KeySignature(1))333        bm.makeNotation(inPlace=True, cautionaryNotImmediateRepeat=False)334        notes = bm[note.Note]335        self.assertEqual(notes[0].pitch.accidental.name, 'natural')     # Fn336        self.assertEqual(notes[0].pitch.accidental.displayStatus, True)337        self.assertEqual(notes[1].pitch.accidental.name, 'natural')     # Fn338        self.assertEqual(notes[1].pitch.accidental.displayStatus, True)339        self.assertEqual(notes[2].pitch.accidental.name, 'flat')        # E-4340        self.assertEqual(notes[2].pitch.accidental.displayStatus, True)341        self.assertEqual(notes[3].pitch.accidental.name, 'flat')        # E-5342        self.assertEqual(notes[3].pitch.accidental.displayStatus, True)343        self.assertEqual(notes[4].pitch.accidental.name, 'natural')     # En4344        self.assertEqual(notes[4].pitch.accidental.displayStatus, True)345        self.assertEqual(notes[5].pitch.accidental.name, 'natural')     # En4346        self.assertEqual(notes[5].pitch.accidental.displayStatus, True)347        self.assertIsNotNone(notes[6].pitch.accidental)  # En5348        self.assertEqual(notes[6].pitch.accidental.name, 'natural')349        self.assertEqual(notes[6].pitch.accidental.displayStatus, True)350    def testOverrideDisplayStatus(self):351        n = note.Note('Cn')352        n.pitch.accidental.displayStatus = True353        k = key.Key('C')354        n.pitch.updateAccidentalDisplay(overrideStatus=True, alteredPitches=k.alteredPitches)355        self.assertIs(n.pitch.accidental.displayStatus, False)356    def testImplicitToExplicitNatural(self):357        p = converter.parse('tinyNotation: 2/4 f4 fn4')358        last_note = p.recurse().notes.last()359        p.makeAccidentals(inPlace=True)360        self.assertIs(last_note.pitch.accidental.displayStatus, False)361        last_note.pitch.accidental.displayStatus = None362        p['Measure'].first().insert(0, key.Key('C-'))363        p.makeAccidentals(inPlace=True)364        self.assertIs(last_note.pitch.accidental.displayStatus, False)365    def testIfAbsolutelyNecessary(self):366        '''367        Beginning of test cases for if-absolutely-necessary.368        '''369        p = converter.parse('tinyNotation: 2/4 f#2 f2')370        last_note = p.recurse().notes.last()371        last_note.pitch.accidental = Accidental('natural')372        last_note.pitch.accidental.displayType = 'if-absolutely-necessary'373        p.makeAccidentals(inPlace=True)374        self.assertIs(last_note.pitch.accidental.displayStatus, False)375        p[stream.Measure].first().insert(0, key.KeySignature(-7))  # F-flat!376        p.makeAccidentals(inPlace=True, overrideStatus=True)377        self.assertIs(last_note.pitch.accidental.displayStatus, True)378        p[key.KeySignature].first().sharps = -5  # No effect on us.379        p.makeAccidentals(inPlace=True, overrideStatus=True)380        self.assertIs(last_note.pitch.accidental.displayStatus, False)381        p = converter.parse('tinyNotation: 2/4 F#4 f4')382        last_note = p.recurse().notes.last()383        last_note.pitch.accidental = Accidental('natural')384        last_note.pitch.accidental.displayType = 'if-absolutely-necessary'385        p.makeAccidentals(inPlace=True)386        self.assertIs(last_note.pitch.accidental.displayStatus, False)387        # F# in different octaves -- need one.388        last_note.pitch.accidental.set('sharp')389        p.makeAccidentals(inPlace=True, overrideStatus=True)390        self.assertIs(last_note.pitch.accidental.displayStatus, True)391    def testNaturalOutsideAlteredPitches(self):392        p = converter.parse('tinyNotation: 2/4 f4 dn4')393        p.makeAccidentals(inPlace=True)394        last_note = p[note.Note].last()395        self.assertIs(last_note.pitch.accidental.displayStatus, False)396        # Rerun test with C-flat major397        last_note.pitch.accidental.displayStatus = None398        p['Measure'].first().insert(0, key.Key('C-'))399        p.makeAccidentals(inPlace=True)400        self.assertIs(last_note.pitch.accidental.displayStatus, True)401    def testInterveningNoteBetweenIdenticalChromaticPitches(self):402        p = converter.parse('tinyNotation: f#4 e f#')403        p.measure(1).insert(0, key.Key('G'))404        p.recurse().notes.last().pitch.accidental.displayStatus = False405        p.makeAccidentals(inPlace=True, overrideStatus=True)406        self.assertIs(p.measure(1).notes.first().pitch.accidental.displayStatus, False)407        self.assertIs(p.measure(1).notes.last().pitch.accidental.displayStatus, False)408    def testPitchEquality(self):409        '''410        Test updating accidental display.411        '''412        data = [413            ('a', 'b', False), ('a', 'a', True), ('a#', 'a', False),414            ('a#', 'b-', False), ('a#', 'a-', False), ('a##', 'a#', False),415            ('a#4', 'a#4', True), ('a-3', 'a-4', False), ('a#3', 'a#4', False),416        ]417        for x, y, match in data:418            p1 = Pitch(x)419            p2 = Pitch(y)420            self.assertEqual(p1 == p2, match)421        # specific case of changing octave422        p1 = Pitch('a#')423        p2 = Pitch('a#')424        self.assertEqual(p1, p2)425        p1.octave = 4426        p2.octave = 3427        self.assertNotEqual(p1, p2)428        p1.octave = 4429        p2.octave = 4430        self.assertEqual(p1, p2)431    def testLowNotes(self):432        dPitch = Pitch('D2')433        lowC = dPitch.transpose('M-23')434        self.assertEqual(lowC.name, 'C')435        self.assertEqual(lowC.octave, -1)436    def testQuarterToneA(self):437        p1 = Pitch('D#~')438        # environLocal.printDebug([p1, p1.accidental])439        self.assertEqual(str(p1), 'D#~')440        # test generation of raw musicxml output441        xmlOut = m21ToXml.GeneralObjectExporter().parse(p1).decode('utf-8')442        match = '<step>D</step><alter>1.5</alter><octave>4</octave>'443        xmlOut = xmlOut.replace(' ', '')444        xmlOut = xmlOut.replace('\n', '')445        self.assertNotEqual(xmlOut.find(match), -1)446        s = stream.Stream()447        for pStr in ['A~', 'A#~', 'A`', 'A-`']:448            p = Pitch(pStr)449            self.assertEqual(str(p), pStr)450            n = note.Note()451            n.pitch = p452            s.append(n)453        self.assertEqual(len(s), 4)454        match = [e.pitch.ps for e in s]455        self.assertEqual(match, [69.5, 70.5, 68.5, 67.5])456        s = stream.Stream()457        alterList = [None, 0.5, 1.5, -1.5, -0.5,458                     'half-sharp', 'one-and-a-half-sharp', 'half-flat', 'one-and-a-half-flat',459                     '~']460        sc = scale.MajorScale('c4')461        for x in range(1, 10):462            n = note.Note(sc.pitchFromDegree(x % sc.getDegreeMaxUnique()))463            n.quarterLength = 0.5464            n.pitch.accidental = Accidental(alterList[x])465            s.append(n)466        match = [str(n.pitch) for n in s.notes]467        self.assertEqual(match,468                         ['C~4', 'D#~4', 'E-`4', 'F`4', 'G~4', 'A#~4', 'B`4', 'C-`4', 'D~4'])469        match = [e.pitch.ps for e in s]470        self.assertEqual(match, [60.5, 63.5, 62.5, 64.5, 67.5, 70.5, 70.5, 58.5, 62.5])471    def testMicrotoneA(self):472        p = pitch.Pitch('a4')473        p.microtone = 25474        self.assertEqual(str(p), 'A4(+25c)')475        self.assertEqual(p.ps, 69.25)476        p.microtone = '-10'477        self.assertEqual(str(p), 'A4(-10c)')478        self.assertEqual(p.ps, 68.90)479        self.assertEqual(p.pitchClass, 9)480        p = p.transpose(12)481        self.assertEqual(str(p), 'A5(-10c)')482        self.assertEqual(p.ps, 80.90)483    def testMicrotoneB(self):484        self.assertEqual(str(pitch.Pitch('c4').getHarmonic(1)), 'C4')485        p = pitch.Pitch('c4')486        p.microtone = 20487        self.assertEqual(str(p), 'C4(+20c)')488        self.assertEqual(str(p.getHarmonic(1)), 'C4(+20c)')489        self.assertEqual(str(pitch.Pitch('c4').getHarmonic(2)), 'C5')490        self.assertEqual(str(pitch.Pitch('c4').getHarmonic(3)), 'G5(+2c)')491        self.assertEqual(str(pitch.Pitch('c4').getHarmonic(4)), 'C6')492        self.assertEqual(str(pitch.Pitch('c4').getHarmonic(5)), 'E6(-14c)')493        self.assertEqual(str(pitch.Pitch('c4').getHarmonic(6)), 'G6(+2c)')494        self.assertEqual(str(pitch.Pitch('c4').getHarmonic(7)), 'A~6(+19c)')495        self.assertEqual(pitch.Pitch('g4').harmonicString('c3'), '3rdH(-2c)/C3')496        self.assertEqual(str(pitch.Pitch('c4').getHarmonic(1)), 'C4')497        self.assertEqual(str(pitch.Pitch('c3').getHarmonic(2)), 'C4')498        self.assertEqual(str(pitch.Pitch('c2').getHarmonic(2)), 'C3')499        self.assertEqual(pitch.Pitch('c4').harmonicString('c3'), '2ndH/C3')500        f = pitch.Pitch('c3')501        f.microtone = -10502        self.assertEqual(str(f.getHarmonic(2)), 'C4(-10c)')503        p = pitch.Pitch('c4')504        f = pitch.Pitch('c3')505        f.microtone = -20506        # the third harmonic of c3 -20 is closer than the507        self.assertEqual(p.harmonicString(f), '2ndH(+20c)/C3(-20c)')508        f.microtone = +20509        self.assertEqual(p.harmonicString(f), '2ndH(-20c)/C3(+20c)')510        p1 = pitch.Pitch('c1')511        self.assertEqual(str(p1.getHarmonic(13)), 'G#~4(-9c)')512        p2 = pitch.Pitch('a1')513        self.assertEqual(str(p2.getHarmonic(13)), 'F~5(-9c)')514        self.assertEqual(str(p1.transpose('M6')), 'A1')515        # not sure if this is correct:516        # self.assertEqual(str(p1.getHarmonic(13).transpose('M6')), 'E##5(-9c)')517    def testMicrotoneC(self):518        match = []519        p = pitch.Pitch('C4')520        p.microtone = 5521        for i in range(11):522            match.append(str(p))523            p.microtone = p.microtone.cents - 1524        self.assertEqual(str(match),525                         "['C4(+5c)', 'C4(+4c)', 'C4(+3c)', 'C4(+2c)', 'C4(+1c)', "526                         + "'C4', 'C4(-1c)', 'C4(-2c)', 'C4(-3c)', 'C4(-4c)', 'C4(-5c)']")527    def testMicrotoneD(self):528        # the microtonal scale used by padberg529        f = [440, 458 + 1 / 3, 476 + 2 / 3, 495, 513 + 1 / 3,530             531 + 2 / 3, 550, 568 + 1 / 3,531             586 + 2 / 3, 605, 623 + 1 / 3, 641 + 2 / 3,532             660, 678 + 1 / 3, 696 + 2 / 3, 715,533             733 + 1 / 3, 751 + 2 / 3, 770, 788 + 1 / 3,534             806 + 2 / 3, 825, 843 + 1 / 3, 861 + 2 / 3]535        self.assertEqual(len(f), 24)536        pList = []537        for fq in f:538            p = pitch.Pitch()539            p.frequency = fq540            pList.append(str(p))541        self.assertTrue(542            common.whitespaceEqual(543                str(pList),544                '''545                ['A4', 'A~4(+21c)', 'B`4(-11c)', 'B4(+4c)', 'B~4(+17c)', 'C~5(-22c)',546                 'C#5(-14c)', 'C#~5(-7c)', 'D5(-2c)', 'D~5(+1c)', 'E-5(+3c)', 'E`5(+3c)',547                 'E5(+2c)', 'E~5(-1c)', 'F5(-4c)', 'F~5(-9c)', 'F#5(-16c)', 'F#~5(-23c)',548                 'F#~5(+19c)', 'G5(+10c)', 'G~5(-1c)', 'G#5(-12c)', 'G#~5(-24c)', 'G#~5(+14c)']''',549            ),550            str(pList)551        )552if __name__ == '__main__':553    import music21...instance_status.py
Source:instance_status.py  
1from __future__ import unicode_literals2from django.utils.translation import ugettext_lazy as _3DEFAULT_KEY = 'default'4class DisplayStatus(object):5    """Instance status used by Fleio for display purposes."""6    RUNNING = 'Running'7    STOPPED = 'Stopped'8    PAUSED = 'Paused'9    SUSPENDED = 'Suspended'10    ERROR = 'Error'11    REBOOT = 'Reboot'12    HARD_REBOOT = 'Hard Reboot'13    PASSWORD = 'Password'14    REBUILD = 'Rebuild'15    MIGRATING = 'Migrating'16    RESIZE = 'Resize'17    STOPPING = 'Stopping'18    BUILDING = 'Building'19    STARTING = 'Starting'20    VERIFY_RESIZE = 'Verify Resize'21    REVERT_RESIZE = 'Revert Resize'22    RESCUE = 'Rescue'23    RESCUED = 'Rescued'24    BOOTING_FROM_ISO = 'Booting from ISO'25    BOOTED_FROM_ISO = 'Booted from ISO'26    DELETED = 'Deleted'27    SOFT_DELETE = 'Soft Delete'28    SHELVED = 'Shelved'29    SHELVED_OFFLOADED = 'Shelved Offloaded'30    UNKNOWN = 'Unknown'31class InstanceStatus(object):32    """Instance status mirrored from OpenStack."""33    ACTIVE = 'active'  # VM is running34    BUILDING = 'building'  # VM only exists in DB35    PAUSED = 'paused'36    SUSPENDED = 'suspended'  # VM is suspended to disk.37    STOPPED = 'stopped'  # VM is powered off, the disk image is still there.38    RESCUED = 'rescued'  # A rescue image is running with the original VM image attached.39    BOOTED_FROM_ISO = 'booted_from_iso'40    RESIZED = 'resized'  # a VM with the new size is active. The user is expected41    # to manually confirm or revert.42    SOFT_DELETED = 'soft-delete'  # VM is marked as deleted but the disk images are43    # still available to restore.44    DELETED = 'deleted'  # VM is permanently deleted.45    ERROR = 'error'46    SHELVED = 'shelved'  # VM is powered off, resources still on hypervisor47    SHELVED_OFFLOADED = 'shelved_offloaded'  # VM and associated resources are48    # not on hypervisor49    ALLOW_SOFT_REBOOT = [ACTIVE]  # states we can soft reboot from50    ALLOW_HARD_REBOOT = ALLOW_SOFT_REBOOT + [STOPPED, PAUSED, SUSPENDED, ERROR]51    status_map = {52        ACTIVE: _('Active'),53        BUILDING: _('Building'),54        PAUSED: _('Paused'),55        SUSPENDED: _('Suspended'),56        STOPPED: _('Stopped'),57        RESCUED: _('Rescued'),58        RESIZED: _('Resized'),59        BOOTED_FROM_ISO: _('Booted from ISO'),60        SOFT_DELETED: _('Soft delete'),61        DELETED: _('Deleted'),62        ERROR: _('Error'),63        SHELVED: _('Shelved'),64        SHELVED_OFFLOADED: _('Shelved offloaded')65    }66class InstanceTask(object):67    """Instance task state mirrored from OpenStack."""68    # possible task states during create()69    SCHEDULING = 'scheduling'70    BLOCK_DEVICE_MAPPING = 'block_device_mapping'71    NETWORKING = 'networking'72    SPAWNING = 'spawning'73    # possible task states during snapshot()74    IMAGE_SNAPSHOT = 'image_snapshot'75    IMAGE_SNAPSHOT_PENDING = 'image_snapshot_pending'76    IMAGE_PENDING_UPLOAD = 'image_pending_upload'77    IMAGE_UPLOADING = 'image_uploading'78    # possible task states during backup()79    IMAGE_BACKUP = 'image_backup'80    # possible task states during set_admin_password()81    UPDATING_PASSWORD = 'updating_password'82    # possible task states during resize()83    RESIZE_PREP = 'resize_prep'84    RESIZE_MIGRATING = 'resize_migrating'85    RESIZE_MIGRATED = 'resize_migrated'86    RESIZE_FINISH = 'resize_finish'87    # possible task states during revert_resize()88    RESIZE_REVERTING = 'resize_reverting'89    # possible task states during confirm_resize()90    RESIZE_CONFIRMING = 'resize_confirming'91    # possible task states during reboot()92    REBOOTING = 'rebooting'93    REBOOT_PENDING = 'reboot_pending'94    REBOOT_STARTED = 'reboot_started'95    REBOOTING_HARD = 'rebooting_hard'96    REBOOT_PENDING_HARD = 'reboot_pending_hard'97    REBOOT_STARTED_HARD = 'reboot_started_hard'98    # possible task states during pause()99    PAUSING = 'pausing'100    # possible task states during unpause()101    UNPAUSING = 'unpausing'102    # possible task states during suspend()103    SUSPENDING = 'suspending'104    # possible task states during resume()105    RESUMING = 'resuming'106    # possible task states during power_off()107    POWERING_OFF = 'powering-off'108    # possible task states during power_on()109    POWERING_ON = 'powering-on'110    # possible task states during rescue()111    RESCUING = 'rescuing'112    # possible task states during boot from ISO113    BOOTING_FROM_ISO = 'booting_from_iso'114    # possible task states during unrescue()115    UNRESCUING = 'unrescuing'116    # possible task states during unmount ISO117    UNMOUNTING_AND_REBOOTING = 'unmounting_ISO_and_rebooting'118    # possible task states during rebuild()119    REBUILDING = 'rebuilding'120    REBUILD_BLOCK_DEVICE_MAPPING = "rebuild_block_device_mapping"121    REBUILD_SPAWNING = 'rebuild_spawning'122    # possible task states during live_migrate()123    MIGRATING = "migrating"124    # possible task states during delete()125    DELETING = 'deleting'126    # possible task states during soft_delete()127    SOFT_DELETING = 'soft-deleting'128    # possible task states during restore()129    RESTORING = 'restoring'130    # possible task states during shelve()131    SHELVING = 'shelving'132    SHELVING_IMAGE_PENDING_UPLOAD = 'shelving_image_pending_upload'133    SHELVING_IMAGE_UPLOADING = 'shelving_image_uploading'134    # possible task states during shelve_offload()135    SHELVING_OFFLOADING = 'shelving_offloading'136    # possible task states during unshelve()137    UNSHELVING = 'unshelving'138    task_state_filtering_opts_map = {139        SCHEDULING: _('Scheduling'),140        BLOCK_DEVICE_MAPPING: _('Block device mapping'),141        NETWORKING: _('Networking'),142        SPAWNING: _('Spawning'),143        IMAGE_SNAPSHOT: _('Image snapshot'),144        IMAGE_SNAPSHOT_PENDING: _('Image snapshot pending'),145        IMAGE_PENDING_UPLOAD: _('Image pending upload'),146        IMAGE_UPLOADING: _('Image uploading'),147        IMAGE_BACKUP: _('Image backup'),148        UPDATING_PASSWORD: _('Updating password'),149        RESIZE_PREP: _('Resize prep'),150        RESIZE_MIGRATING: _('Resize migrating'),151        RESIZE_MIGRATED: _('Resize migrated'),152        RESIZE_FINISH: _('Resize finish'),153        RESIZE_REVERTING: _('Resize reverting'),154        RESIZE_CONFIRMING: _('Resize confirming'),155        REBOOTING: _('Rebooting'),156        REBOOT_PENDING: _('Reboot pending'),157        REBOOT_STARTED: _('Reboot started'),158        REBOOTING_HARD: _('Rebooting hard'),159        REBOOT_PENDING_HARD: _('Reboot pending hard'),160        REBOOT_STARTED_HARD: _('Reboot started hard'),161        PAUSING: _('Pausing'),162        UNPAUSING: _('Unpausing'),163        SUSPENDING: _('Suspending'),164        RESUMING: _('Resuming'),165        POWERING_OFF: _('Powering off'),166        POWERING_ON: _('Powering on'),167        RESCUING: _('Rescuing'),168        BOOTING_FROM_ISO: _('Booting from ISO'),169        UNRESCUING: _('Unrescuing'),170        UNMOUNTING_AND_REBOOTING: _('Unmounting IOS and rebooting'),171        REBUILDING: _('Rebuilding'),172        REBUILD_BLOCK_DEVICE_MAPPING: _('Rebuild block device mapping'),173        REBUILD_SPAWNING: _('Rebuild spawning'),174        MIGRATING: _('Migrating'),175        DELETING: _('Deleting'),176        SOFT_DELETING: _('Soft deleting'),177        RESTORING: _('Restoring'),178        SHELVING: _('Shelving'),179        SHELVING_IMAGE_PENDING_UPLOAD: _('Shelving image pending upload'),180        SHELVING_IMAGE_UPLOADING: _('Shelving image uploading'),181        SHELVING_OFFLOADING: _('Shelving offloading'),182        UNSHELVING: _('Unshelving'),183    }184INSTANCE_STATE_MAP = {185    InstanceStatus.ACTIVE: {186        DEFAULT_KEY: DisplayStatus.RUNNING,187        InstanceTask.REBOOTING: DisplayStatus.REBOOT,188        InstanceTask.REBOOT_PENDING: DisplayStatus.REBOOT,189        InstanceTask.REBOOT_STARTED: DisplayStatus.REBOOT,190        InstanceTask.REBOOTING_HARD: DisplayStatus.HARD_REBOOT,191        InstanceTask.REBOOT_STARTED_HARD: DisplayStatus.HARD_REBOOT,192        InstanceTask.UPDATING_PASSWORD: DisplayStatus.PASSWORD,193        InstanceTask.REBUILDING: DisplayStatus.REBUILD,194        InstanceTask.REBUILD_BLOCK_DEVICE_MAPPING: DisplayStatus.REBUILD,195        InstanceTask.REBUILD_SPAWNING: DisplayStatus.REBUILD,196        InstanceTask.MIGRATING: DisplayStatus.MIGRATING,197        InstanceTask.RESIZE_PREP: DisplayStatus.RESIZE,198        InstanceTask.RESIZE_MIGRATING: DisplayStatus.RESIZE,199        InstanceTask.RESIZE_MIGRATED: DisplayStatus.RESIZE,200        InstanceTask.RESIZE_FINISH: DisplayStatus.RESIZE,201        InstanceTask.POWERING_OFF: DisplayStatus.STOPPING,202        InstanceTask.RESCUING: DisplayStatus.RESCUE,203        InstanceTask.BOOTING_FROM_ISO: DisplayStatus.BOOTING_FROM_ISO,204    },205    InstanceStatus.BUILDING: {DEFAULT_KEY: DisplayStatus.BUILDING},206    InstanceStatus.STOPPED: {DEFAULT_KEY: DisplayStatus.STOPPED,207                             InstanceTask.RESIZE_PREP: DisplayStatus.RESIZE,208                             InstanceTask.RESIZE_MIGRATING: DisplayStatus.RESIZE,209                             InstanceTask.RESIZE_MIGRATED: DisplayStatus.RESIZE,210                             InstanceTask.RESIZE_FINISH: DisplayStatus.RESIZE,211                             InstanceTask.POWERING_ON: DisplayStatus.STARTING212                             },213    InstanceStatus.RESIZED: {DEFAULT_KEY: DisplayStatus.VERIFY_RESIZE,214                             InstanceTask.RESIZE_REVERTING: DisplayStatus.REVERT_RESIZE215                             },216    InstanceStatus.PAUSED: {DEFAULT_KEY: DisplayStatus.PAUSED},217    InstanceStatus.SUSPENDED: {DEFAULT_KEY: DisplayStatus.SUSPENDED},218    InstanceStatus.RESCUED: {DEFAULT_KEY: DisplayStatus.RESCUED},219    InstanceStatus.BOOTED_FROM_ISO: {DEFAULT_KEY: DisplayStatus.BOOTED_FROM_ISO},220    InstanceStatus.ERROR: {DEFAULT_KEY: DisplayStatus.ERROR},221    InstanceStatus.DELETED: {DEFAULT_KEY: DisplayStatus.DELETED},222    InstanceStatus.SOFT_DELETED: {DEFAULT_KEY: DisplayStatus.SOFT_DELETE},223    InstanceStatus.SHELVED: {DEFAULT_KEY: DisplayStatus.SHELVED},224    InstanceStatus.SHELVED_OFFLOADED: {DEFAULT_KEY: DisplayStatus.SHELVED_OFFLOADED},225    'unknown': {DEFAULT_KEY: DisplayStatus.UNKNOWN}226}227class InstancePowerState(object):228    NO_STATE = 0229    RUNNING = 1230    BLOCKED = 2231    PAUSED = 3232    SHUTDOWN = 4233    SHUTOFF = 5234    CRASHED = 6235    SUSPENDED = 7236    FAILED = 8...PyPiBotter.py
Source:PyPiBotter.py  
1#!/usr/bin/env python32#3# Author:   pibotter@gmx.de4# Version:  0.0.15# Date:     1st Aug. 20166#7from flask import Flask8import sys9import logging10from logging.handlers import RotatingFileHandler11from OuterWorld import DistanceSensor as Distance12from OuterWorld import MotorController as Motor13# to change the display implementation you only need to change the import here.14from OuterWorld import Nokia5110 as Display15#from OuterWorld import DummyDisplay as Display16app = Flask(__name__)17fwSensor = Distance.UsDistanceSensor()18bwSensor = Distance.UsDistanceSensor()19driver = Motor.MotorController()20display = Display.Display()21@app.route('/')22def index():23    return app.send_static_file('templates/index.html')24@app.route('/distance/forward')25def getForwardSensor():26    fwAvgDistance = fwSensor.getAverageForwardsReading()27    fwDistance = fwSensor.getForwardsReading()28    displayStatus = display.displayText(0,0,'fw dist: ' + str(fwAvgDistance))29    app.logger.debug('fw distance avg last 10 seconds: ' + str(fwAvgDistance) + ' / now: ' + str(fwDistance))30    return 'fw distance avg last 10 seconds: ' + str(fwAvgDistance) + ' / now: ' + str(fwDistance)31@app.route('/distance/backward')32def getBackwardSensor():33    bwAvgDistance = bwSensor.getAverageBackwardsReading()34    bwDistance = bwSensor.getBackwardsReading()35    displayStatus = display.displayText(0,2,'bw dist: ' + str(bwAvgDistance))36    app.logger.debug('fw distance avg last 10 seconds: ' + str(bwAvgDistance) + ' / now: ' + str(bwDistance))37    return 'fw distance avg last 10 seconds: ' + str(bwAvgDistance) + ' / now: ' + str(bwDistance)38@app.route('/drive/stopall')39def stopMotors():40    motorStatus = driver.stopMotors()41    displayStatus = display.displayText(0,0,motorStatus)42    app.logger.debug('display status: ' + displayStatus + ' / motor status: ' + motorStatus)43    return motorStatus44@app.route('/drive/stop/a')45def stopMotorA():46    motorStatus = driver.stopMotorA()47    displayStatus = display.displayText(0,0,motorStatus)48    app.logger.debug('display status: ' + displayStatus + ' / motor status: ' + motorStatus)49    return motorStatus50@app.route('/drive/stop/b')51def stopMotorB():52    motorStatus = driver.stopMotorB()53    displayStatus = display.displayText(0,0,motorStatus)54    app.logger.debug('display status: ' + displayStatus + ' / motor status: ' + motorStatus)55    return motorStatus56@app.route('/drive/forwards')57def driveForwards():58    motorStatus = driver.driveForwards()59    displayStatus = display.displayText(0,0,motorStatus)60    app.logger.debug('display status: ' + displayStatus + ' / motor status: ' + motorStatus)61    return motorStatus62@app.route('/drive/backwards')63def driveBackwards():64    motorStatus = driver.driveBackwards()65    displayStatus = display.displayText(0,0,motorStatus)66    app.logger.debug('display status: ' + displayStatus + ' / motor status: ' + motorStatus)67    return motorStatus68@app.route('/drive/left')69def turnLeft():70    motorStatus = driver.turnLeft()71    displayStatus = display.displayText(0,0,motorStatus)72    app.logger.debug('display status: ' + displayStatus + ' / motor status: ' + motorStatus)73    return motorStatus74@app.route('/drive/right')75def turnRight():76    motorStatus = driver.turnRight()77    displayStatus = display.displayText(0,0,motorStatus)78    app.logger.debug('display status: ' + displayStatus + ' / motor status: ' + motorStatus)79    return motorStatus80def main():81    handler = RotatingFileHandler('/var/tmp/PyPiBotter.log', maxBytes=10000, backupCount=1)82    handler.setLevel(logging.DEBUG)83    app.logger.addHandler(handler)84    appDebug=False85    if (len(sys.argv) > 1):86        if (sys.argv[1] == '--server'):87            pass88        elif (sys.argv[1] == '--debug'):89            appDebug = True90        else:91            print('running all in console mode - please use --server to start a background server')92    else:93        print('running all in console mode and with debugging on - please use --server to start a background server')94        appDebug = True95    app.run(host='0.0.0.0', debug=appDebug)96    app.logger.info('Try the forwards and backwards sensors at /distance/forward and /distance/backward')97if __name__ == '__main__':...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
