コード例 #1
0
ファイル: database.py プロジェクト: bjvanderweij/expressivity
def selectM21Score():
    composers = ['bach', 'beethoven', 'ciconia', 'coltrane', 'handel', 'haydn', 'josquin',\
        'luca', 'monteverdi', 'mozart', 'pachelbel', 'schoenberg', 'schubert', 'schumann']
    path = -1
    while(path == -1):
        comp = util.menu('Choose a composer', composers)
        path = util.menu('Choose a work', m21.corpus.getComposer(composers[comp]), cancel=True)
    return m21.corpus.parse(m21.corpus.getComposer(composers[comp])[path])
コード例 #2
0
def wait_for_power_and_battery(args):
    global VERDICT, OUTPUT
    if wait_for_event("power status", ["Charging", "Full"]) and wait_for_event("battery presence", '1'):
        menu(validation_menu, initial_menu_items)
    else:
        OUTPUT = "FAILURE: Did not find power status 'Charging' or 'Full' and battery connected"
        print_to_console_and_logcat(OUTPUT)
        VERDICT = FAILURE
        menu(validation_menu[1:], initial_menu_items)
コード例 #3
0
def pre_check_verification(args):

    global VERDICT, OUTPUT
    if wait_for_event("power status", pre_check_status):
        menu(validation_menu, initial_menu_items)
    else:
        OUTPUT = "FAILURE: Did not find power status '{}'".format(
            pre_check_status)
        print_to_console_and_logcat(OUTPUT)
        VERDICT = FAILURE
        menu(validation_menu[1:], initial_menu_items)
コード例 #4
0
ファイル: database.py プロジェクト: bjvanderweij/expressivity
def select():
    work = -1
    while(work == -1):
        comp = util.menu('Choose a composer', getComposers() + ['MUSIC21 Corpus'] + ['Score Directory'])
        print(len(getComposers()), comp)
        if comp == len(getComposers()):
            return 'm21'
        elif comp == len(getComposers())+1:
            return 'sd'
        work = util.menu('Choose a work and performer', getWorks(getComposers()[comp]), cancel=True)

    selected = getWorks(getComposers()[comp])[work]
    return getComposers()[comp], selected[0], selected[1], selected[2]
コード例 #5
0
ファイル: main.py プロジェクト: anacsv/OlistTechExperience
def main():
    arq = 'arq.txt'
    #cria arquivo txt
    if not arqexiste(arq):
        criar_arq(arq)

    while True:
        resp = menu([
            'Listar Produtos', 'Cadastrar Produto', 'Deletar Produtos',
            'Alterar Produto', 'Sair'
        ])
        if resp == 1:
            #listar produtos cadastrados de um arquivo
            ler_arq(arq)
        elif resp == 2:
            #cadastrar novo produto
            formatacao('Novo cadastro')
            nome = str(input('Nome: '))
            tipo = str(input('Tipo: '))
            cadastrar(arq, nome, tipo)
        elif resp == 3:
            deletar(arq, input('Informe o nome do item para deletar: '))
        elif resp == 4:
            #altera item
            nome = str(input('Informe o nome do item que será alterado: '))
            novo_nome = str(input('Novo nome: '))
            novo_tipo = str(input('Novo tipo: '))
            alterar(arq, nome, novo_nome, novo_tipo)
        elif resp == 5:
            break
        else:
            print('Erro! digite uma opçao válida conforme a lista!')
コード例 #6
0
def playPerformance(selection, performance, expression, segmentation, name='ExpressivePerformance'):
    # Store?
    # Play again?
    # View first x notes?
    while True:
        choice = util.menu('What do you want to do?', ['Play performance', 'Store expression', 'Store midi', 'View first notes of performance', 'Plot performance', 'Save plot', 'View segmentation', 'Make segmentation audible', 'Quit'])
        if choice == 0:
            seq = Sequencer()
            seq.play(performance)
        elif choice == 1:
            n = input("Enter a name for saving this performance. [{0}]\n".format(name))
            if not n == '': name = n
            tools.savePerformance(selection, expression, name)
        elif choice == 2:
            n = input("Enter a name for saving this performance. [{0}.mid]\n".format(name))
            if not n == '': name = n
            performance.exportMidi('output/{0}.mid'.format(name))
        elif choice == 3:
            for note in performance[:30]:
                print(note)
        elif choice == 4: # Plot
            visualize(segmentation, expression)
        elif choice == 5: # Save plot
            n = input("Enter a name for saving this performance. [{0}.mid]\n".format(name))
            if not n == '': name = n
            visualize(segmentation, expression, store=name)
        elif choice == 6: # View segments
            pass
        elif choice == 7: # Play segments
            pass
        elif choice == 8: # Quit
            break
コード例 #7
0
ファイル: forum.py プロジェクト: PanYan1998/example-forum
def titled_render(subtitle=''):
    subtitle = subtitle + ' - ' if subtitle else ''
    return render({
        'title': subtitle + settings.SITE_NAME,
        'make_html': util.make_html,
        'trim_utf8': util.trim_utf8,
        'menu': util.menu(model.User())
    })
コード例 #8
0
def selectSubset(set):
    choice = 1
    subset = []
    while True:
        print('Subset: [', end=' ')
        print(', '.join([set[i] for i in subset]), end=' ')
        print(']')
        choice = util.menu('Select features', ['Done'] + set)
        if choice == 0:
            break
        subset.append(choice-1)
    return subset
コード例 #9
0
ファイル: database.py プロジェクト: bjvanderweij/expressivity
def selectWork():
    works = {}
    allworks = []
    for i in range(len(getComposers())):
        allworks += [(getWorks(getComposers()[i])[j], i, j) for j in range(len(getWorks(getComposers()[i])))]
    for work, i, j in allworks:
        s = getWorks(getComposers()[i])[j]
        works[getComposers()[i], s[0]] = (getComposers()[i], s[0], s[1], s[2])

    sortedkeys = sorted(works.keys())

    choice = util.menu('Choose a score', sortedkeys + ['Music21 Corpus'] + ['Score Directory'])
    if choice == len(sortedkeys):
        return 'm21'
    elif choice == len(sortedkeys)+1:
        return 'sd'
    return works[sortedkeys[choice]]
コード例 #10
0
    def play(self, notes):
        notes.printinfo()
        # Choose an output device
        devices = []
        for i in range(midi.get_count()):
            info = midi.get_device_info(i)
            devices.append("{0}, {1}, Input:{2}, Output:{3}".format(info[0], info[1], info[2], info[3]))

        device = util.menu("Choose an output device", devices)
        out = midi.Output(device)

        # Translate notes into midi events
        print("Preprocessing")
        events = notes.toEvents()

        print("Playing")
        lastTime = 0
        on = 0
        off = 0
        for e in events:
            # Calculate relative time and convert to seconds
            ticks = e[0] - lastTime
            # This is not right yet
            seconds = notes.ticks_to_seconds(ticks)
            if e[3] is 'on':
                #out.update_time(e[0]-lastTime)
                time.sleep(seconds)
                lastTime = e[0]
                out.note_on(e[1], e[2], 0)
            elif e[3] is 'off':
                #out.update_time(e[0]-lastTime)
                time.sleep(seconds)
                lastTime = e[0]
                # Sometimes note_offs are lost?
                # Unbelievably sending twice reduces this.
                out.note_off(e[1], e[2], 0)
                out.note_off(e[1], e[2], 0)
コード例 #11
0
ファイル: projeto_final.py プロジェクト: asaito2001/PJC
PATH_ABS = '/home/asaito2001/repos/python3/PJC/projeto_final'
BASE_ELEITORES = os.path.join(PATH_REL, 'dados', 'base_eleitores.csv')
CERTIDAO = os.path.join(PATH_REL, 'dados', 'certidao.html')

# Verificar existencia de arquivos
if not arq.existe_arquivo(BASE_ELEITORES):
    arq.criar_base_eleitores(BASE_ELEITORES)
    print('Arquivo base eleitores criado com sucesso!!')
else:
    print('Base de dados encontrada!')

# Programa principal
menu = ('Cadastro', 'Validação', 'Emissão Certidão', 'Sair do Sistema')
dados_busca = []
while True:
    opcao = util.menu(menu, 'QUITAÇÃO ELEITORAL', 40)
    if opcao == 1:
        dados = arq.cadastrar_eleitor()
        if arq.gravar_eleitor(dados, BASE_ELEITORES):
            print('Gravado com sucesso!')
        else:
            print('Não foi possível cadastrar o eleitor')
        sleep(1.5)
    elif opcao == 2:
        dados_busca = arq.buscar_eleitor(arq.solicitar_dados_busca(),
                                         BASE_ELEITORES)
        if voto.validar_eleitor(dados_busca):
            pass
            sleep(1.5)
        else:
            pass
コード例 #12
0
 elif a[1] == 'plot':
     (selection, expression) = tools.loadPerformance()
     if selection == None:
         selection = db.select()
     score = db.getScore1(selection)
     melodyscore = Score(score).melody()
     melody = tools.parseScore(melodyscore)
     segmentation = structure.reasonableSegmentation(melody)
     visualize(segmentation, expression)
     exit(0)
 elif a[1] == 'corpora':
     for x in tools.datasets():
         print('Name:\t[{0}]\tInfo:\t{1}'.format(x, tools.corpusInfo(x)))
     exit(0)
 elif a[1] == 'corpusinfo':
     choice = util.menu("Select corpus", tools.datasets())
     print(tools.corpusInfo(tools.datasets()[choice]))
     tools.extendedCorpusInfo(tools.datasets()[choice])
     exit(0)
 elif a[1] == 'features':
     s = db.select()
     score = Score(db.getScore1(s))
     melodyscore = score.melody()
     melody = tools.parseScore(melodyscore)
     segmentation = structure.reasonableSegmentation(melody)
     f = sf.vanDerWeijFeatures(melodyscore, segmentation)
     for x in f:
         #(dPitch, abs_dPitch, dDuration, abs_dDuration, silence, ddPitch, abs_ddPitch, pitch_direction)
         print('dpitch: {0} abs_dPitch: {1} dDuration: {2} abs_dDuration: {3} silence: {4}'.format(x[0], x[1], x[2], x[3], x[4]))
         print('ddPitch: {0} abs_ddPitch: {1} : pitch_direction: {2}'.format(x[5], x[6], x[7]))
     exit(0)
コード例 #13
0
    shuffle(colors)
    passed = True
    for color in colors:
        print insert_color_msg
        sleep(1)
        proc = display_on_screen(color)
        passed, OUTPUT = validate_response(color)
        if not passed:
            print_to_console_and_logcat(OUTPUT)
            VERDICT = FAILURE
            if proc:
                proc.kill()
            break
        if proc:
            proc.kill()

    if passed:
        OUTPUT = "Success"
        print_to_console_and_logcat(OUTPUT)
        VERDICT = SUCCESS


menu_items = [
    "Press enter when you are ready to begin the test", {
        check_color_message: check_color
    }, {
        "Do you want repeat the test ? (y/n)": validate_result
    }
]
menu(menu_items, menu_items[1:])
コード例 #14
0
ファイル: tools.py プロジェクト: bjvanderweij/expressivity
def chooseFeatures():
    choice = util.menu('Pick a dataset', ['Name:\t[{0}]\tInfo:\t{1}'.format(x, corpusInfo(x)) for x in os.listdir('data')])
    return loadFeatures(os.listdir('data')[choice])
コード例 #15
0
ファイル: pack.py プロジェクト: larsgroeber/prg1
import glob
import sys
import os
import shutil

import util
from header_adder import HeaderAdder

if len(sys.argv) != 3:
    print("Usage: {} SHEET_DIRECTORY SHEET_NUMBER".format(sys.argv[0]))
    exit(0)

print()
print('For which module is this directory a solution?')
module_menu = {'1': 'PRG', '2': 'EPR'}
module_name = module_menu[util.menu(module_menu)]

header_adder = HeaderAdder()

SHEETNUMBER = sys.argv[2]
directory_path: str = sys.argv[1]

if directory_path[0] not in ['.', '/']:
    directory_path = './' + directory_path

directory_name = directory_path.split("/")[-1]
base_directory = "/".join(directory_path.split("/")[:-1])
final_directory_path = base_directory + "/" + directory_name + ".final"

print("\nCreating directory {}".format(final_directory_path))
os.makedirs(final_directory_path, exist_ok=True)
コード例 #16
0
        VERDICT = FAILURE
    OUTPUT = message


def pre_check_verification(args):

    global VERDICT, OUTPUT
    if wait_for_event("power status", pre_check_status):
        menu(validation_menu, initial_menu_items)
    else:
        OUTPUT = "FAILURE: Did not find power status '{}'".format(
            pre_check_status)
        print_to_console_and_logcat(OUTPUT)
        VERDICT = FAILURE
        menu(validation_menu[1:], initial_menu_items)


initial_menu_items = [
    "Press enter when you are ready to begin the test", {
        pre_check_mess: pre_check_verification
    }
]

validation_menu = [{
    check_mess: wait_for_status
}, {
    "Do you want to repeat the test ? (y/n)": validate_result
}]

menu(initial_menu_items, initial_menu_items)
コード例 #17
0
ファイル: tools.py プロジェクト: bjvanderweij/expressivity
def loadPerformance(name=None):
    if not name:
        choice = util.menu('Pick a performance', os.listdir('expressiveperformances'))
        name = os.listdir('expressiveperformances')[choice]
    f = open('expressiveperformances/{0}'.format(name), 'rb')
    return pickle.load(f)
コード例 #18
0
ファイル: database.py プロジェクト: bjvanderweij/expressivity

def byIndexes(i, j):
    selected = getWorks(getComposers()[i])[j]
    return getComposers()[i], selected[0], selected[1], selected[2]

if __name__ == "__main__":
    import sequencer
    seq = sequencer.Sequencer()
    while(True):
        selection = select()
        choice = 0
        while choice != 8:

            choice = util.menu('Choose action', \
                ['Play with internal sequencer', 'Play with audacious', 'View score', 'View midi info', 'View score info',\
                'Export deviation data to CSV', 'Performance', 'Extract melody','Cancel'])
            if choice == 0:
                seq.play(NoteList(getPerformancePath1(selection)))
            elif choice == 1:
                os.system("audacious {0}".format(getPerformancePath1(selection)))
            elif choice == 2:
                getScore1(selection).show()
            elif choice == 3:
                nlist = NoteList(getScoreMidiPath1(selection))
                nlist.printinfo()
            elif choice == 4:
                score = getScore1(selection)
                parts = 0
                notes = 0
                for part in score:
コード例 #19
0
melody = score.melody()
chopinnotes = tools.parseScore(melody)
delta = structure.absolute_deltalist(structure.onset, chopinnotes)
sodelta1 = structure.normalize(structure.second_order_deltalist(delta))

score = Score(db.getScore1(mozart2).stripTies())
melody = score.melody()
mozartnotes = tools.parseScore(melody)
delta2 = structure.square(structure.absolute_deltalist(structure.pitch, mozartnotes))
sodelta2 = structure.normalize(structure.second_order_deltalist(delta2))

s1 = structure.second_order_deltarule(chopinnotes, sodelta1, 0.1)
s2 = structure.second_order_deltarule(mozartnotes, sodelta2, 0.1)

while True:
    choice = util.menu("Select", ['Schumann exp', 'Schumann score', 'Schumann noexp', 'chopin struct', 'lastig struct bach', 'struct moz'])
    if choice == 0:
        path = db.getPerformancePath1(schumann)
        os.system("audacious {0}".format(path))
    if choice == 1:
        os.system("viewmxml {0}".format(db.getScorePath1(schumann)))
    if choice == 2:
        path = db.getScoreMidiPath1(schumann)
        os.system("audacious {0}".format(path))
    if choice == 3:
        groups = structure.groupings(structure.list_to_tree(s1), 1)
        structured_notes = []
        loud = False
        for group in groups:
            if loud:
                loud = False
コード例 #20
0
ファイル: database.py プロジェクト: bjvanderweij/expressivity
def selectScore():
    scores = os.listdir('scores')
    path = 'scores/{0}'.format(scores[util.menu('Select score', scores)])
    return m21.converter.parse(path)
コード例 #21
0
ファイル: ex115.py プロジェクト: alair-py/exercicios-python
import util

arq = 'cursovideo.txt'

if not util.testararq(arq):
    util.criararq(arq)
util.menu(arq)
コード例 #22
0
# imports
from models import Node
import util
import ai

# driver code
(depart, arrive, start) = util.menu()  # utility to run app menu
route = ai.find_route(depart, arrive, start)  # model to generate best route
util.display_route(route)  # utility to display route
コード例 #23
0
COMP_CONF = COMP_CONF[1:-1]

try:
    sensor_info = get_sensor_hal_info(COMP_CONF)
    sensor_id = sensor_info["index"]
    sensor_type = sensor_info["type"]

except:
    OUTPUT = "Sensor was not found"
    print_test_result(False, OUTPUT)
    exit_test()

menu_items = [
    "Press enter when you are ready to begin the test",
    "The first test consists in determining that the sensor readings are correct when it starts with an object in front of it (Press ENTER to continue)",
    "Put an object in front of the sensor (Press ENTER to continue)", {
        "Sensor readings start now! In order to proceed press ENTER before any action (remove/put object in fornt of the sensor) is performed ":
        check_proximity_covered_sensor
    },
    "The second test consists in determining that the sensor readings are correct when it starts with no object in front of it (Press ENTER to continue)",
    "Remove any object that might be in front of the sensor (Press ENTER to continue)",
    {
        "Sensor readings start now!  In order to proceed press ENTER before any action (remove/put object in fornt of the sensor) is performed ":
        check_proximity_uncovered_sensor
    }, {
        "Do you want repeat the test (y/n)": validate_result
    }
]

menu(menu_items)