Ejemplo n.º 1
0
def main(socket, config_file, haproxy_file, debug):
    """Configure logging and start monitering"""
    if debug:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)
    conductor = Conductor(socket, config_file, haproxy_file)
    conductor.monitor()
Ejemplo n.º 2
0
def main():
    #clear terminal window before starting game
    os.system('clear')
    # Prompt to show intro
    intro()
    # Set player's home point using setHome; access from getAllCitiesList
    player = Conductor(getAllCitiesList()[setHome()], 0)
    #First city_print (method from City object - print current city, state, options, and possibly destination.)
    player.location.printCity()

    # Game really starts. Overarching while loop begins.
    game_over = False
    while not game_over:
        # New cargo
        dropped_off = False
        # get random new destination city
        go_to_id = getRandomCity().city_id
        while go_to_id == player.location.city_id:  # if the destination is the player's location
            go_to_id = getRandomCity().city_id
        #return city is current location, a.k.a. home from setHome().
        original_id = player.location.city_id
        picked_up = False
        # First time with a new destination - quest printed in printCity()
        new_go_to = True
        # goTo(go_to_id, player, original_id, picked_up)
        while not dropped_off:

            # if first time with new pickup quest, print in printCity() and don't do it again
            if new_go_to:
                print(goTo(go_to_id, player, original_id, picked_up))
                new_go_to = False

            # receive move input

            inputText = game_input(
                '> ', 'Whoops! Try again. For help, type \'help\' or \'h\'.',
                False, False, True)
            try:
                # If input is not an alternate command (look, map, etc). a.k.a. if input is a cardinal direction:
                if commands(inputText, player, go_to_id, original_id,
                            picked_up) == 0:
                    # move to input direction (1) if in directions possible (2) and set location to associated city (3)
                    player.location = eval(
                        move(inputText, player.location.directions_possible,
                             player.location.cities_possible))
                    # print new city
                    player.location.printCity()
            except TypeError:
                #
                print('Whoops! Try again. For help, type \'help\' or \'h\'.')

            if player.location.city_id == go_to_id and not picked_up:
                print(goTo(go_to_id, player, original_id, picked_up))
                picked_up = True
            elif player.location.city_id == original_id and picked_up:
                dropped_off = True
                player.points += 1
                print(goTo(go_to_id, player, original_id, picked_up))
Ejemplo n.º 3
0
    def test_device_decommissioning(self):
        """ Decommission a device successfully """

        if not env.host_string:
            execute(self.test_device_decommissioning,
                    hosts=get_mender_clients())
            return

        adm.check_expected_status("pending", len(get_mender_clients()))
        adm_id = adm.get_devices()[0]["id"]
        device_id = adm.get_devices()[0]["device_id"]

        adm.set_device_status(adm_id, "accepted")

        # wait until inventory is populated
        timeout = time.time() + (60 * 5)

        while time.time() < timeout:
            inventoryJSON = inv.get_devices()

            # we haven't gotten an inventory data yet.
            if len(inventoryJSON) == 0:
                continue

            if "attributes" in inventoryJSON[0]:
                break
            time.sleep(.5)
        else:
            assert False, "never got inventory"

        # get all completed decommission_device WFs for reference
        c = Conductor(get_mender_conductor())
        initial_wfs = c.get_decommission_device_wfs(device_id)

        # decommission actual device
        deviceauth.decommission(device_id)

        # check that the workflow completed successfully
        timeout = time.time() + (60 * 5)
        while time.time() < timeout:
            wfs = c.get_decommission_device_wfs(device_id)
            if wfs['totalHits'] == initial_wfs['totalHits'] + 1:
                break
            else:
                logger.info("waiting for decommission_device workflow...")
                time.sleep(.5)
        else:
            assert False, "decommission_device workflow didn't complete for [%s]" % (
                device_id, )

        # check device gone from inventory
        self.check_gone_from_inventory(device_id)

        # check device gone from deviceauth
        self.check_gone_from_deviceauth(device_id)

        # now check that the device no longer exists in admission
        self.check_gone_from_deviceadm(adm_id, device_id)
Ejemplo n.º 4
0
 def record_transition(self, fromtrack, totrack, userchoice=True):
     fromtrack, totrack = self._lookup_tracks(fromtrack, totrack)
     _log.info("Recording transition from track %s to %s.", fromtrack.id if fromtrack else "[No track]", totrack.id)
     
     Conductor.record_transition(self, fromtrack, totrack, userchoice)
     
     if userchoice:
         amount = self.config["user_choice_score"]
     else:
         amount = self.config["markov_choice_score"]
     self.score_transition(fromtrack, totrack, amount)
Ejemplo n.º 5
0
 def __init__(self, dbpath, config={}):
     Conductor.__init__(self, dbpath)
     self.chains = {}
     
     # Configuration defaults
     self.config = {"weight_function": self._calculate_weight,
                    "user_choice_score": 2,
                    "markov_choice_score": 1,
                    "min_score_divisor": 10,
                    "default_score": 0,
                    "default_userscore": 0,
                    "min_userscore": - 5,
                    "max_userscore": 5}
     
     self.config.update(config)
Ejemplo n.º 6
0
 def __init__(self):
     super(Supervisor, self).__init__()
     self.clock_bus = bus_registry.get('clock_bus')
     self.button_grid_bus = bus_registry.get('button_grid_bus')
     self.LED_grid_bus = bus_registry.get('LED_grid_bus')
     self.beat_clock_count = 0
     self.midi_clock_divider = 6
     self.conductor = Conductor()
     self.save_on_exit = False
     self.OLED_Screens = proxy_registry('OLED_Screens')
     self.OLED_Screens.text(1, ["world..."])
     # for i in range(4):
     self.OLED_Screens.set_encoder_assignment(f"Select Mode", 0)
     self.OLED_Screens.create_menu(0, ['Play','Select Instrument','Add Instrument','Load','Save','Quit'])
     self.OLED_Screens.create_menu(2, ['a','b','c','d','e','f','g','h','i','j','k'])
     self.keep_running = True
Ejemplo n.º 7
0
def find_longest_track():
    conductor = Conductor()
    api_key = conductor.api_key
    circuits = conductor.get_track_circuits()
    main_line_one = circuits[1]
    new_circuits = []
    for circuit_id, circuit in main_line_one.items():
        neighbors = circuit['Neighbors']
        right_neighbors = []
        left_neighbors = []
        for neighbor in neighbors:
            neighbor_type = neighbor['NeighborType']
            if neighbor_type == 'Left':
                left_neighbors.extend(neighbor['CircuitIds'])
            if neighbor_type == 'Right':
                right_neighbors.extend(neighbor['CircuitIds'])
        new_circuit = TrackCircuit(circuit['Track'], circuit['CircuitId'],
                                   left_neighbors, right_neighbors)
        new_circuits.append(new_circuit)
    print(new_circuits)
Ejemplo n.º 8
0
 def testHashStringAndVoltpereFunctions(self):
     self.testOpenManifold()
     voltConductor = Conductor(self.conjecture.element, self.conjecture.ring, self.conjecture.barn)
     voltpere = voltConductor.hashString("testcases")
     ampere = voltConductor.charge(voltpere)
     self.assertEqual(ampere, pow(self.conjecture.barn, voltpere, voltConductor.FERMAT_CUTOFF))
     henry = voltConductor.induce(ampere)
     self.assertEqual(henry, pow(ampere, self.conjecture.barn, voltConductor.FERMAT_CUTOFF))
     maxwell = voltConductor.refract(henry) 
     self.assertEqual(maxwell, pow(self.conjecture.ring, henry, voltConductor.FERMAT_CUTOFF))
     fermat = voltConductor.prime(maxwell)
     self.assertEqual(fermat, pow(self.conjecture.ring, maxwell, voltConductor.FERMAT_CUTOFF)) 
Ejemplo n.º 9
0
 def voltpereChanged(self, entry):
     if (len(self.GUI.VoltpereEntry.entry_get())):
         voltConductor = Conductor(self.element, self.ring, self.barn)
         voltpere = voltConductor.hashString(
             self.GUI.VoltpereEntry.entry_get())
         ampere = voltConductor.charge(voltpere)
         self.updateGUIAmpereField(ampere)
         henry = voltConductor.induce(ampere)
         self.updateGUIHenryField(henry)
         maxwell = voltConductor.refract(henry)
         self.updateGUIMaxwellField(maxwell)
         fermat = voltConductor.prime(maxwell)
         self.updateGUIFermatField(fermat)
     else:
         self.updateGUIAmpereField("")
Ejemplo n.º 10
0
Archivo: main.py Proyecto: wmodes/crs
def main():
    # Configure logging
    setup_logging()

    # create logger
    logger = logging.getLogger(__name__)

    # initialize stuff
    field = Field()
    
    osc = OSCHandler()
    conductor = Conductor()
    field.update(osc=osc)
    osc.update(field=field, conductor=conductor)
    conductor.update(field=field)

    if os.path.isfile('settings.py'):
        logger.info( "Loading settings from settings.py")
        execfile('settings.py')

    keep_running = True
    lastframe = None
    lasttime = 0
    while keep_running:
        # call user script
        osc.each_frame()

        if field.m_frame != lastframe or \
            time() - lasttime > 1:
            # do conductor calculations and inferences
            field.check_for_abandoned_cells()
            conductor.update_all_cells()
            conductor.update_all_conx()

            # send regular reports out
            osc.send_regular_reports()
            lastframe = field.m_frame
            lasttime = time()
        else:
            # Still on the same frame, sleep for a fraction of the frame time to not hog CPU
            #field.m_osc.send_laser('/conductor/sleep',[field.m_frame])    # Useful for debugging -- can see in OSC stream when this process was sleeping
            sleep((1.0/config.framerate)/10)

        keep_running = osc.m_run & field.m_still_running

    osc.m_oscserver.close()
Ejemplo n.º 11
0
def create_engine(db_path: str, training_data_path: str):
    db = NeuralNetworkDB()
    db.open(db_path)

    config = Config(db)

    training_data = TrainingData(db)
    training_data.load_file(training_data_path)

    # engine.neural_network_loader = NeuralNetworkLoader(engine)
    #
    engine = Engine()
    engine._db = db
    engine._config = config
    engine._training_data = training_data

    Engine._instance = engine

    engine._conductor = Conductor()
    engine._evolution_processor = EvolutionProcessor()
Ejemplo n.º 12
0
class Tune:
    def __init__(self):
        self.conductor = Conductor()

    def play(self):
        return self.conductor.play()
Ejemplo n.º 13
0
 def record_user_feedback(self, liked):
     """Called when a user likes or dislikes a transition."""
     Conductor.record_user_feedback(self, liked)
     self.score_transition(user_amount=(1 if liked else -1), *self.last_transition)
Ejemplo n.º 14
0
def main():

    CYCLETIME = 1/25.0

    # initialize stuff
    field = MyField()
    osc = MyOSCHandler()
    conductor = Conductor()
    field.update(osc=osc)
    osc.update(field=field, conductor=conductor)
    conductor.update(field=field)

    if os.path.isfile('settings.py'):
        print "Loading settings from settings.py"
        execfile('settings.py')

    keep_running = True
    lastframe = None
    while keep_running:
        # call user script
        osc.each_frame()

        if field.m_frame != lastframe or \
            time() - lasttime > 1:
            # do conductor calculations and inferences
            field.check_for_abandoned_cells()
            conductor.age_expire_cells()
            conductor.update_all_cells()
            conductor.age_expire_conx()
            conductor.update_all_conx()

            # send regular reports out
            osc.send_regular_reports()
            lastframe = field.m_frame
            lasttime = time()
        else:
            # Still on the same frame, sleep for a fraction of the frame time to not hog CPU
            #field.m_osc.send_laser('/conductor/sleep',[field.m_frame])    # Useful for debugging -- can see in OSC stream when this process was sleeping
            sleep((1.0/FRAMERATE)/10)

        keep_running = osc.m_run & field.m_still_running

    osc.m_oscserver.close()
Ejemplo n.º 15
0
def main():

    CYCLETIME = 1 / 25.0

    # initialize stuff
    field = MyField()
    osc = MyOSCHandler()
    conductor = Conductor()
    field.update(osc=osc)
    osc.update(field=field, conductor=conductor)
    conductor.update(field=field)

    if os.path.isfile('settings.py'):
        print "Loading settings from settings.py"
        execfile('settings.py')

    keep_running = True
    lastframe = None
    while keep_running:
        # call user script
        osc.each_frame()

        if field.m_frame != lastframe or \
            time() - lasttime > 1:
            # do conductor calculations and inferences
            field.check_for_abandoned_cells()
            conductor.age_expire_cells()
            conductor.update_all_cells()
            conductor.age_expire_conx()
            conductor.update_all_conx()

            # send regular reports out
            osc.send_regular_reports()
            lastframe = field.m_frame
            lasttime = time()
        else:
            # Still on the same frame, sleep for a fraction of the frame time to not hog CPU
            #field.m_osc.send_laser('/conductor/sleep',[field.m_frame])    # Useful for debugging -- can see in OSC stream when this process was sleeping
            sleep((1.0 / FRAMERATE) / 10)

        keep_running = osc.m_run & field.m_still_running

    osc.m_oscserver.close()
Ejemplo n.º 16
0
 async def _agent_factory():
     config = config_factory()
     agent = await Agent.from_config(config)
     agent.conductor = Conductor.from_wallet_handle_config(
         agent.wallet_handle, config)
     return agent
Ejemplo n.º 17
0


import main
from conductor import Conductor
from shared import config
import itertools
import re

conductor = Conductor(None)

re_tests = {
    "Implemented & Successfully Tested": "Success",
    "Implemented & Not Tested": "Not Tested",
    "Not Implemented": "Not .* Implemented",
}

cell_results = {}
conx_results = {}

print "#\n# Cell tests\n#\n"

for status,regex in re_tests.iteritems():
    cell_results[status] = []
    for type,test in conductor.cell_tests.iteritems():
        docstring = test.__doc__
        #print "KILME:",regex
        if re.search(regex, docstring, flags=re.I):
            cell_results[status].append(type)

for status in re_tests:
Ejemplo n.º 18
0
    from trellis import Trellis
    from conductor import Conductor
    from actors import ActorThread, bus_registry, actor_registry, post, receive
    # t = Trellis(I2C_BUS).start()
    # sleep(30)
    # print("SETUP COMPLETE")
    # exit()
    # m = MidiOut(open_output('seq_out', autoreset=True, virtual=True)).start()
    m = MidiOut(fakeMidiOut()).start()
    c = MidiClock(120).start()
    e0 = Encoder(0).start()
    e1 = Encoder(1).start()
    e2 = Encoder(2).start()
    e3 = Encoder(3).start()
    b = ButtonGrid().start()
    c = Conductor().start()

    post('button_grid', {'event': 'press', 'x': 1, 'y': 1})
    sleep(0.001)
    post('button_grid', {'event': 'release', 'x': 1, 'y': 1})
    sleep(0.001)

    post('button_grid', {'event': 'press', 'x': 3, 'y': 3})
    sleep(0.001)
    post('button_grid', {'event': 'release', 'x': 3, 'y': 3})
    sleep(0.001)
    post('button_grid', {'event': 'press', 'x': 2, 'y': 2})
    sleep(0.001)
    post('button_grid', {'event': 'release', 'x': 2, 'y': 2})
    sleep(0.001)
    post('button_grid', {'event': 'press', 'x': 7, 'y': 7})
Ejemplo n.º 19
0
class Supervisor(object):
    """docstring for Supercell."""

    def __init__(self):
        super(Supervisor, self).__init__()
        self.clock_bus = bus_registry.get('clock_bus')
        self.button_grid_bus = bus_registry.get('button_grid_bus')
        self.LED_grid_bus = bus_registry.get('LED_grid_bus')
        self.beat_clock_count = 0
        self.midi_clock_divider = 6
        self.conductor = Conductor()
        self.save_on_exit = False
        self.OLED_Screens = proxy_registry('OLED_Screens')
        self.OLED_Screens.text(1, ["world..."])
        # for i in range(4):
        self.OLED_Screens.set_encoder_assignment(f"Select Mode", 0)
        self.OLED_Screens.create_menu(0, ['Play','Select Instrument','Add Instrument','Load','Save','Quit'])
        self.OLED_Screens.create_menu(2, ['a','b','c','d','e','f','g','h','i','j','k'])
        self.keep_running = True

    def run(self):
        debug("Supervisor running...")
        self.draw()
        while self.keep_running:
            if not self.button_grid_bus.empty():
                # debug("button pressed")
                m = self.button_grid_bus.get()
                self.process_cmds(m)
                self.draw()
            if not self.clock_bus.empty():
                clock_tick = self.clock_bus.get()
                self.conductor.step_beat(clock_tick)
                self.draw()
            sleep(0.01)
        return

    def command_cb(self, m):
        self.process_cmds(m)
        return

    def get_cmds(self):
        if not self.button_grid_bus.empty():
            # debug("button pressed")
            m = self.button_grid_bus.get()
            self.process_cmds(m)

    def process_cmds(self, m):
        if m['cmd'] is None:
            return None
        if m['cmd'] == 'quit':
            if self.save_on_exit:
                self.conductor.save()
            exit()
        elif m['cmd'] == 'toggle_save':
            self.save_on_exit = not self.save_on_exit
        elif m['cmd'] == 'CONFIG_A':
            self.conductor.gbl_cfg_state()
        elif m['cmd'] == 'CONFIG_B':
            self.conductor.ins_cfg_state()
        elif m['cmd'] == 'step_beat':
            self.conductor.step_beat(1)
        elif m['cmd'] == 'note':
            self.conductor.touch_note(m['x'], m['y'])
        elif m['cmd'] == 'encoder':
            self.conductor.touch_encoder(id=m['id'], action=m['action'])
        return

    def process_midi_tick(self):
        '''Perform midi tick subdivision so ticks only happen on beats'''
        self.beat_clock_count += 1
        if self.beat_clock_count >= self.midi_clock_divider:
            self.beat_clock_count %= self.midi_clock_divider
            return True
        return False

    def draw(self):
        status = self.conductor.get_status()
        led_grid = self.conductor.get_led_grid()
        screens = self.OLED_Screens.get_text().get()
        self.LED_grid_bus.put((status, led_grid, screens))
Ejemplo n.º 20
0
    print(
        'This agent implementation is not compatible with python versions 3.5 and lower'
    )
    sys.exit(1)

import asyncio
from agent import Agent
from config import Config
from conductor import Conductor

if __name__ == '__main__':

    loop = asyncio.get_event_loop()

    config = Config.from_args_file_defaults()

    agent = loop.run_until_complete(Agent.from_config(config))
    agent.set_conductor(
        Conductor.from_wallet_handle_config(agent.wallet_handle, config))

    @agent.route('test_protocol/1.0/testing')
    async def testing_handler(agent, msg):
        print('got testing')

    # Main loop
    try:
        loop.run_until_complete(agent.start())
    except KeyboardInterrupt:
        print("exiting")
        loop.run_until_complete(agent.shutdown())
Ejemplo n.º 21
0
        carriles = carriles1.mostrar_carriles(
        )  #Obtencion numero de carrilles de la clase Carril
        print(f"Esta pista contará con {carriles} carriles")
        print("--------------------------------------------------------------")
        juego = Juego(num_jugadores)  #Llamada al juego
        posiciones = []
        ljugadores = [
        ]  #Listas vacias necesarias para la inicializacion del juego.
        lugares_podio = []
        listan = Jugador(
            num_jugadores)  #Lista numero de jugadores invocando la clase
        lista2 = listan.numero_jugadores(
            ljugadores
        )  #Variable obtenida de listan. Ejemplo [Diego, Alejandro]
        print("--------------------------------------------------------------")
        conductores = Conductor(num_jugadores)
        conductores.mostrar_Conductores(ljugadores)
        print("--------------------------------------------------------------")
        autos = Carro(num_jugadores)
        autos.mostar_auto(ljugadores)
        print("--------------------------------------------------------------")
        print()
        lista = juego.inicio(
        )  #Formacion primera lista de posiciones en cero. Ejemplo [0, 0]

        # While para evaluar la distancia recorrida por turnos:
        while r:

            for i in range(len(ljugadores)):
                p = input(
                    f"Es el turno de {ljugadores[i]}, en el carril {i + 1} quieres girar el dado? (y/n): "
Ejemplo n.º 22
0
 def __init__(self):
     self.conductor = Conductor()