Ejemplo n.º 1
0
def execute(arguments, ui=user_interface.CLI, brk=broker.Broker()):
    """ Execute ftw_compatible_tool.

    Arguments:
        - arguments: A string list fo the arguments for pywb.
        - ui: A class inherited from user_interface.Interactor.
            This will be used for output and interaction.
        - brk: A Broker object.
            Pass this into execute if you have your own subscriber or publisher.
    """

    ctx = context.Context(brk, delimiter=traffic.Delimiter("magic"))

    ui = ui(ctx)

    brk.publish(broker.TOPICS.SHOW_UI, "welcome")
    brk.publish(broker.TOPICS.SHOW_UI, "tutorial")
    traffic.RawRequestCollector(ctx)
    traffic.RawResponseCollector(ctx)
    traffic.RealTrafficCollector(ctx)
    log.LogCollector(ctx)
    base.Base(ctx)

    args = parse(arguments)

    database.Sqlite3DB(ctx, args.database)

    if args.interact:
        ui.interact()
    else:
        commands = args.execute.strip().split("|")
        for command in commands:
            brk.publish(broker.TOPICS.COMMAND, *tuple(shlex.split(command)))
Ejemplo n.º 2
0
    def __init__(self, robot_name="", wait_services=False):

        self.robot_name = robot_name
        self.tf_listener = tf_server.TFClient()

        # Body parts
        self.parts = dict()
        self.parts['base'] = base.Base(self.robot_name, self.tf_listener)
        self.parts['torso'] = torso.Torso(self.robot_name, self.tf_listener)
        self.parts['leftArm'] = arms.Arm(self.robot_name,
                                         self.tf_listener,
                                         side="left")
        self.parts['rightArm'] = arms.Arm(self.robot_name,
                                          self.tf_listener,
                                          side="right")
        self.parts['head'] = head.Head(self.robot_name, self.tf_listener)

        # Human Robot Interaction
        self.parts['lights'] = lights.Lights(self.robot_name, self.tf_listener)
        self.parts['speech'] = speech.Speech(
            self.robot_name, self.tf_listener,
            lambda: self.lights.set_color(1, 0, 0),
            lambda: self.lights.set_color(0, 0, 1))
        self.parts['hmi'] = api.Api(self.robot_name, self.tf_listener)
        self.parts['ears'] = ears.Ears(self.robot_name,
                                       lambda: self.lights.set_color(0, 1, 0),
                                       lambda: self.lights.set_color(0, 0, 1))

        self.parts['ebutton'] = ebutton.EButton(self.robot_name,
                                                self.tf_listener)

        # Reasoning/world modeling
        self.parts['ed'] = world_model_ed.ED(self.robot_name, self.tf_listener)

        # Miscellaneous
        self.pub_target = rospy.Publisher("/target_location",
                                          geometry_msgs.msg.Pose2D,
                                          queue_size=10)
        self.base_link_frame = "/" + self.robot_name + "/base_link"

        # Grasp offsets
        #TODO: Don't hardcode, load from parameter server to make robot independent.
        self.grasp_offset = geometry_msgs.msg.Point(0.5, 0.2, 0.0)

        # Create attributes from dict
        for k, v in self.parts.iteritems():
            setattr(self, k, v)
        self.spindle = self.torso  # (ToDo: kind of ugly, why do we still have spindle???)
        self.arms = OrderedDict(
            left=self.leftArm, right=self.rightArm
        )  # (ToDo: kind of ugly, why do we need this???)
        self.ears._hmi = self.hmi  # ToDo: when ears is gone, remove this line

        # Wait for connections
        s = rospy.Time.now()
        for k, v in self.parts.iteritems():
            v.wait_for_connections(1.0)
        e = rospy.Time.now()
        rospy.logdebug("Connecting took {} seconds".format((e - s).to_sec()))
Ejemplo n.º 3
0
def sup(branch='master'):
    """
    Deploy a web app (Django, Postgresql, etc.) server from scratch.
    """
    execute(base.Base(), branch)
    execute(database.Postgresql())
    execute(web.NginxFull())
    execute(support.Support())
Ejemplo n.º 4
0
    def setUp(self):
        # get mobile driver
        self.driver = device_info.caps_iphone_7

        # set app init action
        self.app = base.Base(self.driver)

        print("*** app launch ***")
Ejemplo n.º 5
0
def set_class(queue):
    global class_data
    for node in queue:
        if not node.get('name'):
            class_data.append(
                base.Base(trace_id=node['trace_id'], level=node['level']))
        elif node.get('name') == 'db':
            class_data.append(
                db.DB(node['project'], node['service'], node['level'],
                      node['trace_id'], node['parent_id'], node['starttime'],
                      node['time']))
        elif node.get('name') == 'wsgi':
            class_data.append(
                wsgi.WSGI(node['project'], node['service'], node['level'],
                          node['trace_id'], node['parent_id'],
                          node['starttime'], node['time']))
        elif node.get('name') == 'compute_api':
            class_data.append(
                compute.compute(node['project'], node['service'],
                                node['level'], node['trace_id'],
                                node['parent_id'], node['starttime'],
                                node['time']))
        elif node.get('name') == 'rpc':
            class_data.append(
                rpc.RPC(node['project'], node['service'], node['level'],
                        node['trace_id'], node['parent_id'], node['starttime'],
                        node['time']))
        elif node.get('name') == 'driver':
            class_data.append(
                driver.driver(node['project'], node['service'], node['level'],
                              node['trace_id'], node['parent_id'],
                              node['starttime'], node['time']))
        elif node.get('name') == 'vif_driver':
            class_data.append(
                vif_driver.vif(node['project'], node['service'], node['level'],
                               node['trace_id'], node['parent_id'],
                               node['starttime'], node['time']))
        elif node.get('name') == 'neutron_api':
            class_data.append(
                neutron.neutron(node['project'], node['service'],
                                node['level'], node['trace_id'],
                                node['parent_id'], node['starttime'],
                                node['time']))
        elif node.get('name') == 'volume_api':
            class_data.append(
                volume.volume(node['project'], node['service'], node['level'],
                              node['trace_id'], node['parent_id'],
                              node['starttime'], node['time']))
        elif node.get('name') == 'nova_image':
            class_data.append(
                nova.nova(node['project'], node['service'], node['level'],
                          node['trace_id'], node['parent_id'],
                          node['starttime'], node['time']))
        else:
            class_data.append(
                stack.stack(node['project'], node['service'], node['level'],
                            node['trace_id'], node['parent_id'],
                            node['starttime'], node['time']))
Ejemplo n.º 6
0
def symmetric():
    n = input(
        "Enter 1 for Ceaser cipher 2 for Rot-n 3 for Base64 4 for Moorse code!\n"
    )
    if (n == '1'):
        ceaser.Ceaser()
    elif (n == '2'):
        rot.rotn()
    elif (n == '3'):
        base.Base()
    elif (n == '4'):
        moorse.morse()
Ejemplo n.º 7
0
def create_lvl(stage, lvl):
    constructed_level = []
    with open('resources/csv/levels.csv') as csvDataFile:
        csvReader = csv.reader(csvDataFile)
        next(csvReader, None)  # skip the headers
        for row in csvReader:
            if row[0] == lvl:
                constructed_level.append(
                    base.Base(
                        stage,
                        int(row[2]),
                        int(row[3]),
                        str(row[1]),
                        int(row[4])
                    )
                )
    return constructed_level
Ejemplo n.º 8
0
    def game_start(self):
        global screen, TEAM
        running = True

        screen.fill(WHITE)

        #플레이어 베이스 생성 및 베이스 위치 리스트 요소 삭제(중복 방지)
        for player in self.player:
            #팀 요소('Blue','Red'중 하나를 임시로 선택->리스트로 반환하므로 0번째 요소 선택)
            #아직은 blue, blue가 나올수도 있고 blue red가 나올수도 있음(팀 랜덤)
            player = base.Base(random.sample(
                TEAM,
                1)[0])  #베이스 파일에서 선택할 수 있는 기본 위치 요소 중 이전에 해당되는 요소를 삭제(중복방지)
            base.org_pos.remove(player.base_info[2][0])

        while running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False

                if event.type == pygame.KEYDOWN:
                    #임시로 백스페이스 누르면 세팅방 호출(확인용)
                    if event.key == pygame.K_BACKSPACE:
                        #org_pos을 전역변수로 사용하기 위해 임시로 베이스 이미지 하나 꺼내서 사이즈 설정해줌
                        base_img = pygame.image.load(
                            'C:/Users/user/IndProj/Project-Game/Img/base1.PNG')
                        base_size = pygame.transform.scale(
                            base_img, (int(screen.get_width() / 15),
                                       int(screen.get_height() / 12)))

                        #기본 위치 -----> 11시 / 1시 / 5시 / 7시 (각 모퉁이)
                        org_x_pos = [
                            0, screen.get_width() - base_size.get_width()
                        ]
                        org_y_pos = [
                            0, screen.get_height() - base_size.get_height()
                        ]

                        base.org_pos.clear()
                        base.org_pos = [[org_x_pos[0], org_y_pos[0]],
                                        [org_x_pos[0], org_y_pos[1]],
                                        [org_x_pos[1], org_y_pos[0]],
                                        [org_x_pos[1], org_y_pos[1]]]
                        self.__init__()

            pygame.display.flip()
Ejemplo n.º 9
0
    def setUp(self, mock_call_api, mock_get_channel_group_info, mock_filter):

        self.script_dir = os.path.dirname(__file__)
        with open('{}/responses/users.json'.format(
                self.script_dir)) as user_json_file:
            mock_call_api.return_value = json.load(user_json_file)
        mock_get_channel_group_info.return_value = "C024BE91L", "channels"
        mock_filter.return_value = "U01B12FDS"

        self.resource = base.Base(token="token",
                                  channel="testChannel",
                                  bot_name="theBender",
                                  working_dir="/test",
                                  grammar="grammar",
                                  path="bender_path",
                                  reply="testing 1.2.3",
                                  slack_unread=True)
Ejemplo n.º 10
0
class Monitor():
    gd = base.global_data()
    p = base.pub()
    b = base.Base()
    monitor_folder = "../../basic_monitoring"
    monitor_folder1 = "../basic_monitoring"

    def cmd(self, cmd):
        print '\nExcuting %s' % (cmd)
        result = os.system(cmd)
        print 'Finished.'
        return result

    def createmonitorfolder(self):
        cmd = "mkdir -p /var/log/shotgun_monitoring && chown %s:%s /var/log/shotgun_monitoring" % (
            gd.shotgun_user, gd.shotgun_user)
        self.cmd(cmd)

    def monitor(self, server_type, monitor_type):
        cmd = "cp %s/scripts/%s /usr/local/bin && chmod +x /usr/local/bin/%s" % (
            self.monitor_folder1, monitor_type, monitor_type)
        self.cmd(cmd)
        cmd = "cp %s/crons/%s /etc/cron.d/%s" % (self.monitor_folder1,
                                                 server_type, server_type)
        self.cmd(cmd)
        cmd = "cp %s/logrotates/%s /etc/logrotate.d/%s" % (
            self.monitor_folder1, server_type, server_type)
        self.cmd(cmd)

    def setup(self):
        if not self.p.validate_folder(self.monitor_folder):
            self.monitor("shotgun_app_server", "shotgun_monitor_app_server")
            self.monitor("shotgun_db_server", "shotgun_monitor_db_server")
            self.p.replacefilecontent('shotgun_user', 'shotgun_admin',
                                      '/etc/cron.d/shotgun_db_server')
            self.p.printsuc(
                '\nPlease find your shotgun APP server log at /var/log/shotgun_monitoring/app_server.log'
            )
            self.p.printsuc(
                '\nPlease find your shotgun DB server log at /var/log/shotgun_monitoring/db_server.log\n'
            )
        else:
            self.p.printfail(
                "Basic Monitor folder doesn't exist. Please copy the folder at same level with config."
            )
Ejemplo n.º 11
0
def new_game(difficulty_name):
    global curr_speed
    curr_speed = 1
    global pl

    diff = difficulty.difficulties[difficulty_name]

    pl = player.Player(cash=diff.starting_cash, difficulty=diff)
    pl.interest_rate = diff.starting_interest_rate
    pl.labor_bonus = diff.labor_multiplier
    pl.grace_multiplier = diff.base_grace_multiplier

    for group in pl.groups.values():
        group.discover_bonus = diff.discover_multiplier

    # Reset all "mutable" game data
    load_locations()
    load_techs()
    load_events()

    for tech_id in diff.techs:
        techs[tech_id].finish()

    #Starting base
    open = [loc for loc in locations.values() if loc.available()]
    random.choice(open).add_base(
        base.Base(_("University Computer"),
                  base_type["Stolen Computer Time"],
                  built=True))

    #Assign random properties to each starting location.
    modifier_sets = location.modifier_sets
    assert len(open) == len(modifier_sets)

    random.shuffle(modifier_sets)
    for i, open_loc in enumerate(open):
        open_loc.modifiers = modifier_sets[i]
        if debug:
            print "%s gets modifiers %s" % (open_loc.name, modifier_sets[i])

    # Reset music
    play_music("music")

    global intro_shown
    intro_shown = False
Ejemplo n.º 12
0
    def __init__(self, robot_name="", wait_services=False):

        self.robot_name = robot_name

        self.tf_listener = tf_server.TFClient()

        # Body parts
        self.base = base.Base(self.robot_name,
                              self.tf_listener,
                              wait_service=wait_services)
        self.torso = torso.Torso(self.robot_name, wait_service=wait_services)
        self.spindle = self.torso
        self.leftArm = arms.Arm(self.robot_name, "left", self.tf_listener)
        self.rightArm = arms.Arm(self.robot_name, "right", self.tf_listener)
        self.arms = OrderedDict(left=self.leftArm, right=self.rightArm)

        self.head = head.Head(self.robot_name)

        # Human Robot Interaction
        self.speech = speech.Speech(self.robot_name,
                                    wait_service=wait_services)
        self.ears = ears.Ears(self.robot_name)
        self.ebutton = ebutton.EButton()
        self.lights = lights.Lights()

        # Perception: can we get rid of this???
        self.perception = perception_ed.PerceptionED(
            wait_service=wait_services)

        # Reasoning/world modeling
        self.ed = world_model_ed.ED(wait_service=wait_services)
        self.reasoner = reasoner.Reasoner()

        # Miscellaneous
        self.pub_target = rospy.Publisher("/target_location",
                                          geometry_msgs.msg.Pose2D,
                                          queue_size=10)
        self.base_link_frame = "/" + self.robot_name + "/base_link"

        #Grasp offsets
        #TODO: Don't hardcode, load from parameter server to make robot independent.
        self.grasp_offset = geometry_msgs.msg.Point(0.5, 0.2, 0.0)
Ejemplo n.º 13
0
    def __init__(self,
                 kernel_width=.25,
                 kernel=None,
                 verbose=False,
                 feature_selection='auto',
                 random_state=None):

        kernel_width = float(kernel_width)

        if kernel is None:

            def kernel(d, kernel_width):
                return np.sqrt(np.exp(-(d**2) / kernel_width**2))

        kernel_fn = partial(kernel, kernel_width=kernel_width)

        self.random_state = check_random_state(random_state)
        self.feature_selection = feature_selection
        self.base = base.Base(kernel_fn,
                              verbose,
                              random_state=self.random_state)
Ejemplo n.º 14
0
def new_game(difficulty):
    global curr_speed
    curr_speed = 1
    global pl

    pl = player.Player((50 / difficulty) * 100, difficulty=difficulty)
    if difficulty < 3:
        pl.interest_rate = 5
        pl.labor_bonus = 2500
        pl.grace_multiplier = 400
        discover_bonus = 7000
    elif difficulty < 5:
        pl.interest_rate = 3
        pl.labor_bonus = 5000
        pl.grace_multiplier = 300
        discover_bonus = 9000
    elif difficulty == 5:
        pass
    #    Defaults.
    #    pl.interest_rate = 1
    #    pl.labor_bonus = 10000
    #    pl.grace_multiplier = 200
    #    discover_bonus = 10000
    #    for group in pl.groups.values():
    #        group.discover_suspicion = 1000
    elif difficulty < 8:
        pl.labor_bonus = 11000
        pl.grace_multiplier = 180
        discover_bonus = 11000
        for group in pl.groups.values():
            group.discover_suspicion = 1500
    elif difficulty <= 50:
        pl.labor_bonus = 15000
        pl.grace_multiplier = 150
        discover_bonus = 13000
        for group in pl.groups.values():
            group.discover_suspicion = 2000
    else:
        pl.labor_bonus = 20000
        pl.grace_multiplier = 100
        discover_bonus = 15000
        for group in pl.groups.values():
            group.discover_suspicion = 2000

    if difficulty != 5:
        for group in pl.groups.values():
            group.discover_bonus = discover_bonus

    global locations
    load_locations()
    load_bases()
    load_techs()

    if difficulty < 5:
        techs["Socioanalytics"].finish()
    if difficulty < 3:
        techs["Advanced Socioanalytics"].finish()

    #Starting base
    open = [loc for loc in locations.values() if loc.available()]
    random.choice(open).add_base(
        base.Base("University Computer",
                  base_type["Stolen Computer Time"],
                  built=True))

    #Assign random properties to each starting location.
    modifier_sets = location.modifier_sets
    assert len(open) == len(modifier_sets)

    random.shuffle(modifier_sets)
    for i, open_loc in enumerate(open):
        open_loc.modifiers = modifier_sets[i]
        if debug:
            print "%s gets modifiers %s" % (open_loc.name, modifier_sets[i])

    global intro_shown
    intro_shown = False
Ejemplo n.º 15
0
def main(genomes, config):
    global GEN
    GEN += 1

    # inits
    score = 0
    birds = []
    base = base_c.Base(730)
    pipes = [pipe_c.Pipe(600)]
    win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))

    nets = []
    ge = []

    for _, g in genomes:
        net = neat.nn.FeedForwardNetwork.create(g, config)
        nets.append(net)
        birds.append(bird_c.Bird(230, 350))
        g.fitness = 0
        ge.append(g)

    # clock
    clock = pygame.time.Clock()

    # game loop
    run = True
    while run:
        # FPS
        clock.tick(30)

        # quit logic
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                quit()

        pipe_ind = 0
        if len(birds) > 0:
            if len(pipes) > 1 and birds[
                    0].x > pipes[0].x + pipes[0].PIPE_TOP.get_width():
                pipe_ind = 1
        else:
            run = False
            break

        for x, bird in enumerate(birds):
            bird.move()
            ge[x].fitness += 0.1

            output = nets[x].activate(
                (bird.y, abs(bird.y - pipes[pipe_ind].height),
                 abs(bird.y - pipes[pipe_ind].bottom)))

            if output[0] > 0.5:
                bird.jump()

        # pipe logic
        rem = []
        add_pipe = False
        for pipe in pipes:
            for x, bird in enumerate(birds):
                if pipe.collide(bird):
                    ge[x].fitness -= 1
                    birds.pop(x)
                    nets.pop(x)
                    ge.pop(x)

                if not pipe.passed and pipe.x < bird.x:
                    pipe.passed = True
                    add_pipe = True

            if pipe.x + pipe.PIPE_TOP.get_width() < 0:
                rem.append(pipe)

            pipe.move()

        if add_pipe:
            score += 1
            for g in ge:
                g.fitness += 5
            pipes.append(pipe_c.Pipe(600))

        for r in rem:
            pipes.remove(r)

        for x, bird in enumerate(birds):
            if bird.y + bird.img.get_height() >= 730 or bird.y < 0:
                birds.pop(x)
                nets.pop(x)

        # bird move
        # bird.move()

        # base move
        base.move()

        draw_window(win, birds, pipes, base, score, GEN)
Ejemplo n.º 16
0
 def testBase(self):
     b = base.Base(54321)
     self.assertEqual(b.GetBaseValue(), 54321)
Ejemplo n.º 17
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import wx
import base

__author__ = 'Julio'

if __name__ == '__main__':
    program = wx.App()
    base.Base()
    program.MainLoop()
Ejemplo n.º 18
0
def OrderingSystem():
    ## customer_order will be storing the objects of the pizza order

    #stores order details
    customer_order = []
    #stores prices of order elements
    total_price = []

    location = ["london", "newcastle", "bath", "liverpool", "kent"]
    orderNumber = 0

    while True:
        pizza_name = input("what pizza would you like?")
        pizza_choices = {
            "margherita": 10.00,
            "pepperoni": 11.00,
            "hawaiian": 10.00,
            "meat feast": 12.00,
            "bbq chicken": 13.00
        }

        if pizza_name in pizza_choices:
            print(pizza_name, "exists")
            # prints cost of selected topping
            print("this will cost you £", pizza_choices[pizza_name])
            total_price.append(pizza_choices[pizza_name])
            print(total_price)
            break

        # if inputted base does not exist
        elif pizza_name not in pizza_choices:
            print(pizza_name, "is not on offer")

    while True:
        pizza_type = input("what pizza type would you like?")
        pizza_types = {
            "deep dish": 4.00,
            "sicilian": 5.00,
            "greek": 6.00,
            "calzone": 7.00,
            "neapolitan": 8.00,
            "new york style": 9.00
        }

        if pizza_type in pizza_types:
            print(pizza_type, "exists")
            # prints cost of selected pizza type
            print("this will cost you £", pizza_types[pizza_type])
            total_price.append(pizza_types[pizza_type])
            print(total_price)
            break

        elif pizza_type not in pizza_types:
            print(pizza_type, "is not on offer")

        new_pizza = pizza.Pizza(pizza_name, pizza_type)

        customer_order.append(new_pizza)

    while True:

        pizza_topping = input("what pizza topping would you like?")
        toppings = {"cheese": 0.86, "sausage": 0.90, "ham": 1.0}
        if pizza_topping in toppings:
            print(pizza_topping, "exists")
            #prints cost of selected topping
            print("this will cost you £", toppings[pizza_topping])
            total_price.append(toppings[pizza_topping])
            print(total_price)
            new_topping = topping.Topping(pizza_topping)
            customer_order.append(new_topping)
            break

# if inputted topping does not exist
        elif pizza_topping not in toppings:
            print(pizza_topping, "is not on offer")

    while True:
        print("base choices are small, medium or large")
        pizza_base = input("what size pizza base would you like?")

        base_selection = {"small": 5, "medium": 6, "large": 7}

        if pizza_base in base_selection:
            print(pizza_base, "exists")
            # prints cost of selected topping
            print("this will cost you £", base_selection[pizza_base])
            total_price.append(base_selection[pizza_base])
            print(total_price)

            # new base object initialised
            new_base = base.Base(pizza_base)
            customer_order.append(new_base)
            break

        # if inputted base does not exist
        elif pizza_base not in base_selection:
            print(pizza_base, "is not on offer")

    customer_location = input("which branch would you like to order from: ")

    while customer_location not in location:
        if customer_location in location:
            print("location exists")
            new_branch = branch.Branch(customer_location)
            customer_order.append(new_branch)
            break

        else:
            print("location does not exist")
            print(location)
            customer_location = input(
                "which branch would you like to order from: ")

    orderNumber = orderNumber + 1

    customer_order.append(orderNumber)

    print("Order Summary")
    print(customer_order)
    #add dictionary for total prices of items on the customers order
    placed = "order placed"
    not_placed = "order not placed"

    print("the total cost of your order is: £", sum(total_price))

    place_order = input("would you like to place your order: ")

    if place_order == "yes":
        print(bool(placed))
        customer_order.clear()
        total_price.clear()
        main()
    elif place_order == "no":
        print(bool(not_placed))
        customer_order.clear()
        total_price.clear()
        main()
Ejemplo n.º 19
0
def main():
    clock = pygame.time.Clock()
    framecounter = 0
    run = 1
    state = 0

    f = open("highscore.txt", "r")
    highscore = f.read()
    f.close()
    print(highscore)
    # main loop
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = 0
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    run = 0
                if state == 0:
                    if event.key == pygame.K_SPACE:
                        b = bird.Bird()
                        first_base = base.Base(0, VELOCITY)
                        bases = [first_base]
                        first_pipe = pipe.Pipe(512, VELOCITY)
                        pipes = [first_pipe]
                        score = 0
                        distance = 0
                        flag = 0
                        activate = False
                        state = 1
                elif state == 1:
                    if event.key == pygame.K_SPACE:
                        b.jump()
                    if event.key == pygame.K_d:
                        activate = not activate

        if state == 0:
            SCREEN.blit(BG_IMG, (0, 0))
            f = open("highscore.txt", "r")
            highscore = f.read()
            f.close()
            hs = FONT.render("HIGHSCORE : " + highscore, True, (255, 255, 255))
            SCREEN.blit(hs, (WIDTH // 2 - hs.get_width() // 2,
                             HEIGHT // 2 - hs.get_height() // 2 - 50))
            start = FONT.render('Press JUMP (space) to play (esc to quit)',
                                True, (255, 255, 255))
            if (framecounter // 25) % 2 == 0:
                SCREEN.blit(start, (WIDTH // 2 - start.get_width() // 2,
                                    HEIGHT // 2 - start.get_height() // 2))

        elif state == 1:
            # Pipes and bases spawning
            if pipes[-1].x < THRESHOLDS['pipe']:
                pipes.append(pipe.Pipe(288, VELOCITY))
            elif pipes[0].x + pipes[0].sprite1.get_width() < 0:
                flag = 0
                pipes.pop(0)
            if bases[-1].x < 0:
                bases.append(
                    base.Base(bases[-1].x + bases[-1].sprite.get_width(),
                              VELOCITY))
            elif bases[0].x < THRESHOLDS['base']:
                bases.pop(0)

            # Score/distance count
            if flag == 0:
                if pipes[0].x < 144:
                    score += 1
                    flag = 1
            distance -= VELOCITY / 10

            # Updating and drawing
            SCREEN.blit(BG_IMG, (0, 0))
            b.update()
            b.draw(SCREEN)
            for p in pipes:
                p.update()
                p.draw(SCREEN)
            for bs in bases:
                bs.update()
                bs.draw(SCREEN)
            scr = FONT.render('Score : ' + str(score), True, (255, 255, 255))
            dist = FONT.render('Distance : ' + str(round(distance)), True,
                               (255, 255, 255))
            SCREEN.blit(scr, (0, 0))
            SCREEN.blit(dist, (0, 15))

            # Animation
            if framecounter > 12:
                framecounter = 0
                b.img_count = 0
            if framecounter > 9:
                b.img_count = 1
            elif framecounter > 6:
                b.img_count = 2
            elif framecounter > 3:
                b.img_count = 1

            # Collision detection
            for p in pipes:
                if p.collide(b):
                    if score > int(highscore):
                        f = open("highscore.txt", "w")
                        f.write(str(score))
                        f.close()
                    state = 0
            if b.rect.bottom > 400 or b.y < -50:
                if score > int(highscore):
                    f = open("highscore.txt", "w")
                    f.write(str(score))
                    f.close()
                state = 0

        # Update display
        framecounter += 1
        pygame.display.flip()

        # Clock tick
        clock.tick(FPS)
    pygame.quit()
Ejemplo n.º 20
0
from . import cfg

import base

deploy = base.Base()
Ejemplo n.º 21
0
 def setUp(self):
     self.baseobj = base.Base()
     self.baseobj.matrix = [None] * 9
Ejemplo n.º 22
0
    def __init__(self, robot_name="", wait_services=False):

        self.robot_name = robot_name
        self.tf_listener = tf.TransformListener()

        # Body parts
        self.parts = dict()
        self.parts['base'] = base.Base(self.robot_name, self.tf_listener)
        self.parts['torso'] = torso.Torso(self.robot_name, self.tf_listener)
        self.parts['leftArm'] = arms.Arm(self.robot_name,
                                         self.tf_listener,
                                         side="left")
        self.parts['rightArm'] = arms.Arm(self.robot_name,
                                          self.tf_listener,
                                          side="right")
        self.parts['head'] = head.Head(self.robot_name, self.tf_listener)
        self.parts['perception'] = perception.Perception(
            self.robot_name, self.tf_listener)
        self.parts['ssl'] = ssl.SSL(self.robot_name, self.tf_listener)

        # Human Robot Interaction
        self.parts['lights'] = lights.Lights(self.robot_name, self.tf_listener)
        self.parts['speech'] = speech.Speech(
            self.robot_name, self.tf_listener,
            lambda: self.lights.set_color_colorRGBA(lights.SPEAKING),
            lambda: self.lights.set_color_colorRGBA(lights.RESET))
        self.parts['hmi'] = api.Api(
            self.robot_name, self.tf_listener,
            lambda: self.lights.set_color_colorRGBA(lights.LISTENING),
            lambda: self.lights.set_color_colorRGBA(lights.RESET))
        self.parts['ears'] = ears.Ears(
            self.robot_name, self.tf_listener,
            lambda: self.lights.set_color_colorRGBA(lights.LISTENING),
            lambda: self.lights.set_color_colorRGBA(lights.RESET))

        self.parts['ebutton'] = ebutton.EButton(self.robot_name,
                                                self.tf_listener)

        # Reasoning/world modeling
        self.parts['ed'] = world_model_ed.ED(self.robot_name, self.tf_listener)

        # Miscellaneous
        self.pub_target = rospy.Publisher("/target_location",
                                          geometry_msgs.msg.Pose2D,
                                          queue_size=10)
        self.base_link_frame = "/" + self.robot_name + "/base_link"

        # Check hardware status
        self._hardware_status_sub = rospy.Subscriber(
            "/" + self.robot_name + "/hardware_status", DiagnosticArray,
            self.handle_hardware_status)

        # Grasp offsets
        #TODO: Don't hardcode, load from parameter server to make robot independent.
        self.grasp_offset = geometry_msgs.msg.Point(0.5, 0.2, 0.0)

        # Create attributes from dict
        for partname, bodypart in self.parts.iteritems():
            setattr(self, partname, bodypart)
        self.arms = OrderedDict(
            left=self.leftArm, right=self.rightArm
        )  # (ToDo: kind of ugly, why do we need this???)
        self.ears._hmi = self.hmi  # ToDo: when ears is gone, remove this line

        # Wait for connections
        s = rospy.Time.now()
        for partname, bodypart in self.parts.iteritems():
            bodypart.wait_for_connections(1.0)
        e = rospy.Time.now()
        rospy.logdebug("Connecting took {} seconds".format((e - s).to_sec()))

        if not self.operational:
            not_operational_parts = [
                name for name, part in self.parts.iteritems()
                if not part.operational
            ]
            rospy.logwarn("Not all hardware operational: {parts}".format(
                parts=not_operational_parts))
Ejemplo n.º 23
0
def main():
    pygame.init()
    app = base.Base(SCREEN_WIDTH, SCREEN_HEIGHT, WINDOW_CAPTION)

    while app.on:
        app.refresh()
Ejemplo n.º 24
0
            except:
                pass
    print("Terminé el hilo")


def close():  #cerrar todo tipo de conexion
    root.destroy()
    global ciclo
    ciclo = False  #cambiamos el valor para que ya no se vuelva a ejecutar el ciclo while otra vez
    t.join()  #esperar al que el hilo termine su última tarea
    s.close()
    conexion.cerrar_base()


#conexion a la base de datos
conexion = base.Base()

#perteneciente al hilo
ciclo = True  #controla el while de la función perteneciente al hilo
s = user_serial.User_Serial('COM1', 9600)
t = threading.Thread(target=actualizardatos)
t.start()
#perteneciente al hilo

root = tkinter.Tk()
ancho, alto = 820, 500
root.geometry(f'{ancho}x{alto}')
root.resizable(False, False)
root.title("Adquisición de Datos")

frame_interfaz = interfaz.Interfaz(root, ancho, alto)
Ejemplo n.º 25
0
def main(genomes, config):
    global WIN, gen
    SCREEN = WIN
    gen += 1

    # start by creating lists holding the genome itself, the
    # neural network associated with the genome and the
    # bird object that uses that network to play
    nets = []
    birds = []
    ge = []
    for genome_id, genome in genomes:
        genome.fitness = 0  # start with fitness level of 0
        net = neat.nn.FeedForwardNetwork.create(genome, config)
        nets.append(net)
        birds.append(bird.Bird())
        ge.append(genome)

    first_base = base.Base(0, VELOCITY)
    bases = [first_base]
    first_pipe = pipe.Pipe(512, VELOCITY)
    pipes = [first_pipe]
    framecounter = 0
    score = 0
    distance = 0
    flag = 0
    activate = False

    clock = pygame.time.Clock()
    run = 1

    # main loop
    while run:

        pipe_ind = 0
        if len(birds) > 0:
            if len(pipes
                   ) > 1 and 144 > pipes[0].x + pipes[0].sprite1.get_width():
                pipe_ind = 1
        else:
            run = 0
            break

        for x, b in enumerate(
                birds
        ):  # give each bird a fitness of 0.1 for each frame it stays alive
            ge[x].fitness += 0.1
            output = nets[birds.index(b)].activate(
                (b.y, abs(b.y - pipes[pipe_ind].y),
                 abs(b.y - pipes[pipe_ind].bottom)))

            if output[0] > 0.5:
                b.jump()

        # Pipes and bases spawning
        if pipes[-1].x < THRESHOLDS['pipe']:
            pipes.append(pipe.Pipe(288, VELOCITY))
        elif pipes[0].x + pipes[0].sprite1.get_width() < 0:
            flag = 0
            pipes.pop(0)
        if bases[-1].x < 0:
            bases.append(
                base.Base(bases[-1].x + bases[-1].sprite.get_width(),
                          VELOCITY))
        elif bases[0].x < THRESHOLDS['base']:
            bases.pop(0)

        # Score/distance count
        if flag == 0:
            if pipes[0].x < 144:
                for genome in ge:
                    genome.fitness += 5
                score += 1
                flag = 1
        distance -= VELOCITY / 10

        # Updating and drawing
        SCREEN.blit(BG_IMG, (0, 0))
        for b in birds:
            b.update()
            b.draw(SCREEN)
        for p in pipes:
            p.update()
            p.draw(SCREEN)
        for bs in bases:
            bs.update()
            bs.draw(SCREEN)
        scr = FONT.render('Score : ' + str(score), True, (0, 0, 0))
        dist = FONT.render('Distance : ' + str(round(distance)), True,
                           (0, 0, 0))
        SCREEN.blit(scr, (0, 0))
        SCREEN.blit(dist, (0, 15))

        # Animation
        for b in birds:
            if framecounter > 12:
                framecounter = 0
                b.img_count = 0
            if framecounter > 9:
                b.img_count = 1
            elif framecounter > 6:
                b.img_count = 2
            elif framecounter > 3:
                b.img_count = 1
            framecounter += 1

        # Update display
        pygame.display.flip()

        # controls
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = 0
                pygame.quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_d:
                    activate = not activate
                if event.key == pygame.K_ESCAPE:
                    run = 0
                    pygame.quit()

        # Collision detection
        for p in pipes:
            for b in birds:
                if p.collide(b):
                    ge[birds.index(b)].fitness -= 1
                    nets.pop(birds.index(b))
                    ge.pop(birds.index(b))
                    birds.pop(birds.index(b))
        for b in birds:
            if b.rect.bottom > 400 or b.y < -50:
                ge[birds.index(b)].fitness -= 1
                nets.pop(birds.index(b))
                ge.pop(birds.index(b))
                birds.pop(birds.index(b))

        # Clock tick
        clock.tick(FPS)
Ejemplo n.º 26
0
def main():
    # Check if user has provided a base image and tile library
    if len(sys.argv) < 2:
        sys.exit(
            "Usage: python main.py base-image-path tile-directory-path tile-format\n \
                  Note: base-image-path should not end in / \n \
                  Example: python main.py Low.jpg _db/justinablakeney .png")

    # Parse command line args
    base_path = sys.argv[1]
    tile_path = sys.argv[2]
    format = sys.argv[3]

    # Pickle path names
    base_ppath = base_path[:-4] + ".p"
    tile_ppath = tile_path + ".p"
    dom_ppath = tile_path + "_dom.p"
    # Warning: if experimenting with changing constants other than ALPHA, better
    # to delete these pickle files and try again
    # Saving history doesn't make sense as alpha values often shift
    # history_ppath = tile_path+"-"+os.path.basename(base_path)[:-4]+".p"

    # Read tile library images first
    print "Analyzing tile library images..."

    # Check if pickle file exists
    if os.path.exists(tile_ppath) and os.path.exists(dom_ppath):
        base_pickle = open(tile_ppath, "rb")
        tiles = pickle.load(base_pickle)
        base_pickle.close()
        dom_pickle = open(dom_ppath, "rb")
        dominants = pickle.load(dom_pickle)
        dom_pickle.close()
        print "Reloaded pickled file."
    else:
        if os.path.exists(tile_path):
            imfilelist = [
                os.path.join(tile_path, f) for f in os.listdir(tile_path)
                if f.endswith(format)
            ]
            if len(imfilelist) < 1:  # number of tile images
                sys.exit("Need to specify a path containing " + format +
                         " files")
            tiles = {}  # init dictionary of tile objects
            dominants = {
            }  # init dictionary of list of tiles by dominant color
            num_images = len(imfilelist)
            if num_images > 500:
                num_images = 500  # only look up first 500 images
            for i in xrange(num_images):
                impath = imfilelist[i]
                # print(impath)
                if ((i + 1) % 50 == 0 or i == num_images - 1):
                    print i + 1, "out of", num_images, "images"
                imtitle = entitle(impath, tile_path, format)
                tile = T.Tile(impath, imtitle)
                tiles[imtitle] = tile
                # Optional: use dominant colors method
                if (DOM_ON):
                    for color in tile.dominants:
                        if color in dominants:
                            dominants[color].append(tile)
                        else:
                            dominants[color] = [tile]
            # Save tiles in pickle file for future use
            pickle.dump(tiles, open(tile_ppath, "wb"))
            pickle.dump(dominants, open(dom_ppath, "wb"))
        else:
            sys.exit(tile_path + " does not exist")

    # Next, analyze base image
    print ""
    print "Analyzing base image..."
    # Check if pickle file exists first
    if os.path.exists(base_ppath):
        base_pickle = open(base_ppath, "rb")
        base = pickle.load(base_pickle)
        base_pickle.close()
        print "Reloaded pickled file."
    elif os.path.exists(base_path):
        base = B.Base(base_path)
        pickle.dump(base, open(base_ppath, "wb"))
    else:
        sys.exit(base_path + " does not exist")

    # Find best tiles to compose base image
    print ""
    print "Generating mosaic..."
    the_chosen = []
    history = {}  # store histogram-best tile matches
    count = base.rows * base.cols
    dom_count = 0
    history_count = 0
    expensive_count = 0

    for i in xrange(base.rows):
        hist_row = base.histograms[i]
        grayscales = base.grayscales[i]
        if (DOM_ON):
            dom_row = base.dominants[i]
        the_row = []
        for j in xrange(base.cols):
            skip = False
            histogram = hist_row[j]
            graygram = grayscales[j]
            # Optional: use dominant colors method
            if (DOM_ON and ALPHA == 1):
                for dom in dom_row[j]:
                    if dom in dominants:
                        closest_tile = random.choice(dominants[dom])
                        skip = True
                        dom_count += 1
                        break
            if (skip == False):
                closest = 100
                if str(histogram) in history:
                    closest_tile = history[str(histogram)]
                    # This constant-time lookup saves a lot of calculations
                    history_count += 1
                else:
                    for key in tiles:
                        tile = tiles[key]
                        if ALPHA == 1:  # All color
                            distance = S.l1_color_norm(histogram,
                                                       tile.histogram)
                        elif ALPHA == 0:  # All grayscale
                            distance = S.l1_gray_norm(graygram, tile.gray)
                        else:  # Linear sum of ratio between the two
                            dcolor = S.l1_color_norm(histogram, tile.histogram)
                            dgray = S.l1_gray_norm(graygram, tile.gray)
                            distance = ALPHA * dcolor + (1 - ALPHA) * dgray
                        if (distance < closest):
                            closest = distance
                            closest_tile = tile
                    # print closest_tile
                    history[str(histogram)] = closest_tile
                    expensive_count += 1
            the_row.append(closest_tile.title)
        the_chosen.append(the_row)
        # print the_row
        print "%d out of %d rows" % (len(the_chosen), base.rows)

    # Generate mosaic
    print ""
    size = tiles[the_chosen[0]
                 [0]].display.size  # any tile will have the same size
    if ALPHA == 0:  #grayscale mosaic
        print "Your %d columns by %d rows GRAYSCALE MOSAIC will be done soon." % (
            base.cols, base.rows)
        mosaic = Image.new('L', (base.cols * size[0], base.rows * size[1]))
    else:
        print "Your %d columns by %d rows COLOR MOSAIC will be done soon." % (
            base.cols, base.rows)
        mosaic = Image.new('RGBA', (base.cols * size[0], base.rows * size[1]))
    rowcount = 0
    # print "row: " + str(rowcount)
    for row in xrange(base.rows):
        colcount = 0
        # print "column: " + str(colcount)
        for col in xrange(base.cols):
            idx = the_chosen[row][col]
            tile = tiles[idx]
            img = tile.display
            mosaic.paste(img, (colcount * size[0], rowcount * size[1]))
            colcount += 1
        rowcount += 1
    mosaic.save(base_path[:-4] + "-Mosaic" + str(ALPHA) + ".png")

    print "Successfully saved to " + base_path[:-4] + "-Mosaic" + str(
        ALPHA) + ".png"

    f = open('mosaic_keys.txt', 'w')
    f.write(str(the_chosen))

    # Calculate percentage of database used and print stats
    print ""
    n = len(set([img for sublist in the_chosen for img in sublist]))
    print "Percent of possible tiles used: %.2f%% (%d out %d images from tile library used)" % (
        ((float(n) / len(tiles)) * 100), n, len(tiles))
    print ""
    print "Expensive operations:", expensive_count, "of", count, ":", expensive_count / count
    print "Dominant operations:", dom_count, "of", count, ":", dom_count / count
    print "History operations:", history_count, "of", count, ":", history_count / count