Beispiel #1
0
def executor():
    console.header('day 2, part 1')

    timer = Timer()
    pair_count = 0
    triplet_count = 0

    timer.start()
    for id in DataProvider.load('day2'):
        if has(2, id):
            pair_count += 1
        if has(3, id):
            triplet_count += 1
    timer.end()

    console.log('Pairs',
                str(pair_count),
                fg='cyan',
                bold=True,
                color_status=True,
                include_brackets=True)
    console.log('Triplets',
                str(triplet_count),
                fg='cyan',
                bold=True,
                color_status=True,
                include_brackets=True)
    console.log('Checksum',
                str(pair_count * triplet_count),
                fg='cyan',
                bold=True,
                color_status=True,
                include_brackets=True)

    timer.output()
Beispiel #2
0
def executor():
    console.header('day 2, part 2')

    timer = Timer()
    used_ids = set([])
    pairs = []
    ids = DataProvider.load('day2')

    timer.start()
    for id in ids:
        if id not in used_ids:
            used_ids.add(id)
            for inner in ids:
                if inner in used_ids:
                    continue

                distance = hamming_distance(id, inner)

                if distance == 1:
                    pairs.append((
                        id,
                        inner,
                    ))
    timer.end()

    console.log(' ',
                'Pairs',
                fg='cyan',
                bold=True,
                color_status=True,
                include_brackets=True)
    print(pairs)

    timer.output()
Beispiel #3
0
def executor():
    console.header('day 1 - part 2')

    master_freq = 0
    master_freq_set = set([master_freq])
    master_freq_list = [master_freq]

    count = 0

    timer = Timer()

    timer.start()
    try:
        while True:
            count += 1
            for freq in DataProvider.load('day1'):
                master_freq = master_freq + int(freq)
                master_freq_set.add(master_freq)
                master_freq_list.append(master_freq)

                if len(master_freq_set) != len(master_freq_list):
                    raise Exception('Found it!')
            if count % 10 == 0:
                console.log(' ', 'Looped {} times so far.'.format(count))
    except:
        pass
    timer.end()

    console.log('Dupe',
                master_freq,
                fg='cyan',
                bold=True,
                color_status=True,
                include_brackets=True)
    timer.output()
Beispiel #4
0
def executor():
    console.header('day 3, part 1')

    max_x = 1000
    max_y = 1000
    elements = DataProvider.load('day3')
    claim_ids = []
    timer = Timer()

    timer.start()
    claims = numpy.zeros([max_x, max_y])
    for element in elements:
        claim = Claim(element)
        claims = claim.fill_claim(claims)

    for element in elements:
        claim = Claim(element)
        if claim.claim_is_alone(claims):
            claim_ids.append(claim.claim_id)
    timer.end()

    console.log(' ',
                'Claim Ids',
                fg='cyan',
                bold=True,
                color_status=True,
                include_brackets=True)
    print(claim_ids)
    timer.output()
Beispiel #5
0
    def __init__(self):
        self.initialise_windows()
        self.initialise_overview_table()

        self.category_list = CategoryList.from_csv(categories_path)
        self.category_menu = CategoryMenu(self.category_list.categories)
        self.textbuffer = PriceTextBuffer()

        self.example_text_timer = Timer(3)
        self.standby_timer = Timer(5)
        self.reset_time_pointer_to_now()

        self.purchase_list = PurchaseList.from_csv(spending_data_path)
        self.populate_overview_table()
        self.update_table_highlight()
Beispiel #6
0
 def __init__(self,
              uType,
              regs,
              mem=None,
              execTime=1,
              continuePipeline=None):
     self.busy = False
     self.type = uType
     self.memory = mem
     self.execTime = execTime
     self.continuePipeline = continuePipeline
     self.regs = regs
     self.clock = 0
     self.timer = Timer()
     self.currentStage = 0
     self.blocked = False
     self.stages = [None, self.issue, self.read, self.execute, self.write]
     self.Vi = None
     self.Vj = None
     self.Vk = None
Beispiel #7
0
def executor():
    console.header('day 5, part 1')

    timer = Timer()
    polymer = DataProvider.read('day5').strip()

    timer.start()
    polymer = Polymer.react(polymer)
    timer.end()

    console.log('polymer', polymer)
    console.log('length', str(len(polymer)))
    timer.output()
Beispiel #8
0
def executor():
    console.header('day 5, part 2')

    timer = Timer()
    polymer = DataProvider.read('day5').strip()

    timer.start()
    polymer = Polymer.get_best_score(polymer)
    timer.end()

    console.log('Best', polymer)
    console.log('Length', str(len(polymer)))
    timer.output()
Beispiel #9
0
    def __init__(self, mem):
        self.mem = mem
        self.localMem = []
        self.tagMask = pow(2, BANDWIDTH) - 1
        self.indexMask = 0
        self.offsetMask = 0
        self.noOfSets = 0
        self.noOfBlocks = 0
        self.setSize = 0
        self.blockSize = 0
        self.clock = 0
        self.hitTime = 1

        self.blocked = False
        self.reqLoc = None
        self.reqTimer = Timer()
        self.requestee = None
        self.missStage = {'stage': 'EVICT', 'loc': 0}
        self.memFetchLoc = None
        self.noOfHits = 0
        self.noOfMiss = 0
Beispiel #10
0
def executor():
    console.header('day 11, part 1')

    timer = Timer()
    serial_number = 3214

    GRID_X = 300
    GRID_Y = 300

    timer.start()
    console.log('Task', 'Building empty power grid')
    grid = [[0] * GRID_Y for i in range(GRID_X)]

    console.log('Task', 'Calculating power levels')
    for x in range(GRID_X):
        for y in range(GRID_Y):
            grid[x][y] = power_level(x, y, serial_number)

    max_x = GRID_X - 3
    max_y = GRID_Y - 3

    max_power = -999
    target_x = -1
    target_y = -1

    console.log('Task', 'Finding 3x3 grid with the highest power level')
    for x in range(max_x):
        for y in range(max_y):
            cell = grid[x:x + 3]
            cell = [inner[y:y + 3] for inner in cell]
            power = 0
            for row in cell:
                power += sum(row)

            if power > max_power:
                max_power = power
                target_x = x
                target_y = y
    timer.end()

    console.header('output')
    console.log('Power', max_power)
    console.log('X', target_x)
    console.log('Y', target_y)
    timer.output()
Beispiel #11
0
def executor():
    console.header('day 8, part 1')

    console.log('Task', 'Configure application...')
    timer = Timer()
    data = DataProvider.read('day8').strip()
    #data = '2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2'
    elements = [int(el) for el in data.split(' ')]

    timer.start()
    console.header('executing')
    score, rest = parse(elements)
    timer.end()

    console.header('output')
    console.log('Score', score)
    console.log('Rest', rest)
    timer.output()
Beispiel #12
0
def executor():
    console.header('day 4, part 2')

    timer = Timer()
    days = DataProvider.load('day4')

    fsm = FiniteStateMachine(StartState)

    timer.start()
    days.sort()
    for day in days:
        fsm.execute(day.strip())

    fsm.to(End2State)
    fsm.execute(None)
    timer.end()

    console.log('Minute', '', fg='cyan', bold=True, color_status=True, include_brackets=True)
    timer.output()
Beispiel #13
0
def executor():
    console.header('day 3, part 1')

    max_x = 1000
    max_y = 1000
    count = 0
    timer = Timer()

    timer.start()
    claims = numpy.zeros([max_x, max_y])
    for element in DataProvider.load('day3'):
        claim = Claim(element)
        claims = claim.fill_claim(claims)

    for x in range(max_x):
        for y in range(max_y):
            if claims[x][y] > 1:
                count += 1
    timer.end()

    console.log('Count', str(count), fg='cyan', bold=True, color_status=True, include_brackets=True)
    timer.output()
Beispiel #14
0
class Cache:
    def __init__(self, mem):
        self.mem = mem
        self.localMem = []
        self.tagMask = pow(2, BANDWIDTH) - 1
        self.indexMask = 0
        self.offsetMask = 0
        self.noOfSets = 0
        self.noOfBlocks = 0
        self.setSize = 0
        self.blockSize = 0
        self.clock = 0
        self.hitTime = 1

        self.blocked = False
        self.reqLoc = None
        self.reqTimer = Timer()
        self.requestee = None
        self.missStage = {'stage': 'EVICT', 'loc': 0}
        self.memFetchLoc = None
        self.noOfHits = 0
        self.noOfMiss = 0

    def config(self, noOfBlocks, blockSize, setSize=1):
        self.setSize = setSize
        self.noOfSets = noOfBlocks / self.setSize
        self.noOfBlocks = noOfBlocks
        self.blockSize = blockSize
        offsetBits = 0
        indexBits = 0

        while pow(2, offsetBits) < blockSize:
            offsetBits += 1

        while pow(2, indexBits) < noOfBlocks:
            indexBits += 1

        self.offsetMask = (1 << offsetBits) - 1
        self.indexMask = ((1 << indexBits) - 1) << offsetBits
        self.tagMask = self.tagMask & ~(self.indexMask | self.offsetMask)
        for i in range(0, self.noOfSets):
            cSet = []
            for j in range(0, self.setSize):
                cSet.append({'tag': None, 'dirty': False, 'words': []})
            self.localMem.append(cSet)

    def tick(self, clock):
        self.clock = clock
        self.blocked = not self.reqTimer.tick()

    def fetchBlock(self, loc, requestee, data=None):
        location = self.memFetchLoc or loc
        offset = location % self.blockSize
        index = (location / self.blockSize) % self.noOfSets
        tag = location / (self.blockSize * self.noOfSets)

        cSet = self.localMem[index]

        block = None
        for blk in cSet:
            if blk['tag'] == tag:
                block = blk
                break

        if self.requestee is not None and self.requestee != requestee:
            return BUSY

        # hit
        if self.memFetchLoc is None and block is not None:
            if self.requestee is None:
                self.requestee = requestee
                self.blocked = not self.reqTimer.tick(self.hitTime)

            if requestee == self.requestee and not self.blocked:
                self.requestee = None

                # LRU
                cSet.remove(block)
                cSet.insert(0, block)

                self.noOfHits += 1
                if data is None:
                    return block['words'][offset]
                else:
                    block['words'][offset] = data
                    block['dirty'] = True
                    return True
            else:
                return BUSY

        # miss
        else:
            if self.requestee is None:
                self.requestee = requestee

            if self.memFetchLoc is None:
                self.memFetchLoc = loc

            self.blocked = not self.reqTimer.tick(1)

            evictBlock = cSet[-1]
            # write if dirty
            if (evictBlock['dirty'] and self.missStage['stage'] == 'EVICT'
                    and self.missStage['loc'] < self.blockSize):

                loc = ((evictBlock['tag'] << int(
                    math.log(self.blockSize, 2) + math.log(self.noOfSets, 2)))
                       | (index << int(math.log(self.blockSize, 2)))
                       | self.missStage['loc'])

                memResult = self.mem.write(
                    loc,
                    evictBlock['words'][self.missStage['loc']],
                    requestee=self)

                self.missStage['loc'] += 1 if memResult != BUSY else 0
                if self.missStage['loc'] < self.blockSize:
                    self.mem.lock(self)
                return BUSY
            else:
                if self.missStage['stage'] == 'EVICT':
                    self.missStage = {'stage': 'FETCH', 'loc': 0}
                    evictBlock['tag'] = None
                    evictBlock['dirty'] = False
                    evictBlock['words'] = []

                if self.missStage['loc'] < self.blockSize:

                    loc = ((tag << int(
                        math.log(self.blockSize, 2) +
                        math.log(self.noOfSets, 2))) |
                           (index << int(math.log(self.blockSize, 2)))
                           | self.missStage['loc'])

                    memResult = self.mem.read(loc, requestee=self)
                    if memResult != BUSY:
                        self.missStage['loc'] += 1
                        evictBlock['words'].append(memResult)
                        if self.missStage['loc'] < self.blockSize:
                            self.mem.lock(self)
                    return BUSY
                else:
                    self.missStage = {'stage': 'EVICT', 'loc': 0}
                    self.requestee = None
                    evictBlock['tag'] = tag

                    # LRU
                    cSet.pop(-1)
                    cSet.insert(0, evictBlock)

                    self.noOfMiss += 1

                    if loc != self.memFetchLoc:
                        self.memFetchLoc = None
                        return BUSY

                    self.memFetchLoc = None

                    if data is None:
                        return evictBlock['words'][offset]
                    else:
                        evictBlock['words'][offset] = data
                        evictBlock['dirty'] = True
                        return True

    def getMem(self):
        return self.mem.getRawMem()
Beispiel #15
0
class Program:
    def __init__(self):
        self.initialise_windows()
        self.initialise_overview_table()

        self.category_list = CategoryList.from_csv(categories_path)
        self.category_menu = CategoryMenu(self.category_list.categories)
        self.textbuffer = PriceTextBuffer()

        self.example_text_timer = Timer(3)
        self.standby_timer = Timer(5)
        self.reset_time_pointer_to_now()

        self.purchase_list = PurchaseList.from_csv(spending_data_path)
        self.populate_overview_table()
        self.update_table_highlight()

    def initialise_windows(self):
        silica.add_window((0, 0, 22, -4), "categories").set_title("Categories")
        silica.add_window((22, 0, -1, -4), "overview").set_title("Overview")
        silica.add_window((0, -3, 22, -1), "cost").set_title("Enter cost")
        silica.add_window((22, -3, -1, -1), "time").set_title("\u2190 Selected week \u2192")
        silica.add_centered_window((38, 3), "examples").set_title("Examples")

    def initialise_overview_table(self):
        self.overview_table = Table(["Category", "Total"])
        cat_column = self.overview_table.get_column("Category")
        cat_column.proportional_width = 2
        total_column = self.overview_table.get_column("Total")
        total_column.minimum_width = 10
        total_column.proportional_width = 1

    def populate_overview_table(self):
        self.overview_table.clear_rows()
        category_totals = self.get_purchases_in_selected_week().group_purchases_by_category()
        category_totals_names = [purchase.category_name for purchase in category_totals]

        for category in self.category_list:
            if category.name in category_totals_names:
                for purchase in category_totals:
                    if purchase.category_name == category.name:
                        cost = purchase.cost
                row = (category.name, str(cost))
                self.overview_table.add_row(row)

    def update_table_highlight(self):
        category_totals = self.get_purchases_in_selected_week().group_purchases_by_category()
        category_totals_names = [purchase.category_name for purchase in category_totals]

        category_totals_names_sorted = []
        for category in self.category_list:
            if category.name in category_totals_names:
                category_totals_names_sorted.append(category.name)

        selected_cat = self.category_menu.selected_item.name
        try:
            row_number = category_totals_names_sorted.index(selected_cat)
        except ValueError:
            self.overview_table.highlighted_cells = []
            return
        self.overview_table.highlighted_cells = [(1, row_number)]

    def get_purchases_in_selected_week(self):
        week_start = datetime_tools.get_start_of_week(self.time_pointer)
        week_end = datetime_tools.get_end_of_week(self.time_pointer)
        purchase_list = self.purchase_list.get_purchases_within_time_period(week_start, week_end)
        return purchase_list

    def reset_time_pointer_to_now(self):
        self.time_pointer = datetime_tools.get_start_of_week(datetime.now())

    def draw_category_menu(self):
        cat_window = silica.get_window("categories")
        width = cat_window.screen.width
        height = cat_window.screen.height
        cat_screen = self.category_menu.render(width, height)
        cat_window.draw((0, 0), cat_screen)

    def draw_text_buffer(self):
        cat_screen = silica.get_window("cost")
        cat_screen.draw((1, 0), "$ " + self.textbuffer.get())

    def draw_selected_week(self):
        time_window = silica.get_window("time")
        date_string_1 = datetime_tools.get_human_readable_string(self.time_pointer)
        date_string_2 = datetime_tools.get_human_readable_string(datetime_tools.get_end_of_week(self.time_pointer))
        date_string = date_string_1 + " - " + date_string_2
        time_window.draw((0, 0), date_string.center(time_window.screen.width))

    def draw_subtotals(self):
        food_spending = 0
        total_spending = 0

        selected_purchases = self.get_purchases_in_selected_week()
        for purchase in selected_purchases.purchases:
            if purchase.category_name.startswith("Food: "):
                food_spending += float(purchase.cost)
            total_spending += float(purchase.cost)
        overview_window = silica.get_window("overview")
        overview_window.draw((-12, -2), f" Food: ${food_spending:.0f}")
        overview_window.draw((-12, -1), f"Total: ${total_spending:.0f}")

    def parse_keypress(self, key):
        if not key.is_empty():
            self.standby_timer.start()

        if key == "q":
            sys.exit()
        if key == Key.UP:
            self.category_menu.previous()
            self.example_text_timer.start()
            self.update_table_highlight()
        if key == Key.DOWN:
            self.category_menu.next()
            self.example_text_timer.start()
            self.update_table_highlight()
        if key == Key.PAGEUP:
            self.category_menu.pointer = 0
            self.example_text_timer.start()
            self.update_table_highlight()
        if key == Key.PAGEDOWN:
            self.category_menu.pointer = -1
            self.example_text_timer.start()
            self.update_table_highlight()
        if key == Key.LEFT:
            self.time_pointer -= datetime_tools.one_week_delta
            self.populate_overview_table()
            self.update_table_highlight()
        if key == Key.RIGHT:
            self.time_pointer += datetime_tools.one_week_delta
            self.populate_overview_table()
            self.update_table_highlight()
        if key == Key.ENTER:
            tb = self.textbuffer.get()
            if tb != "":
                current_category = self.category_menu.selected_item
                self.purchase_list.add_purchase(current_category.name, float(tb))
                self.textbuffer.clear()
                self.reset_time_pointer_to_now()
                self.populate_overview_table()
                self.update_table_highlight()
                self.purchase_list.save()

        if key.is_character():
            self.textbuffer.add(str(key))
        if key == Key.BACKSPACE:
            self.textbuffer.backspace()

    def main(self):
        overview_window = silica.get_window("overview")
        examples_window = silica.get_window("examples")
        hint = self.category_menu.selected_item.hint
        examples_window.draw((0, 0), hint.center(examples_window.screen.width))
        examples_window.visible = not self.example_text_timer.is_expired()

        key = silica.get_keypress()
        self.parse_keypress(key)

        # Draw different border on overview window if on current week
        start_time = datetime_tools.get_start_of_week(self.time_pointer)
        end_time = datetime_tools.get_end_of_week(self.time_pointer)

        if start_time <= datetime_tools.now() <= end_time:
            overview_window.set_theme("double")
        else:
            overview_window.set_theme("normal")

        self.overview_table.render_to_window(overview_window)
        self.draw_category_menu()
        self.draw_selected_week()
        self.draw_text_buffer()
        self.draw_subtotals()

        silica.process()
Beispiel #16
0
def executor(ctx):
    console.header('day 10, both parts')

    timer = Timer()
    data = DataProvider.load('day10')

    # data = [
    #     'position=< 9,  1> velocity=< 0,  2>',
    #     'position=< 7,  0> velocity=<-1,  0>',
    #     'position=< 3, -2> velocity=<-1,  1>',
    #     'position=< 6, 10> velocity=<-2, -1>',
    #     'position=< 2, -4> velocity=< 2,  2>',
    #     'position=<-6, 10> velocity=< 2, -2>',
    #     'position=< 1,  8> velocity=< 1, -1>',
    #     'position=< 1,  7> velocity=< 1,  0>',
    #     'position=<-3, 11> velocity=< 1, -2>',
    #     'position=< 7,  6> velocity=<-1, -1>',
    #     'position=<-2,  3> velocity=< 1,  0>',
    #     'position=<-4,  3> velocity=< 2,  0>',
    #     'position=<10, -3> velocity=<-1,  1>',
    #     'position=< 5, 11> velocity=< 1, -2>',
    #     'position=< 4,  7> velocity=< 0, -1>',
    #     'position=< 8, -2> velocity=< 0,  1>',
    #     'position=<15,  0> velocity=<-2,  0>',
    #     'position=< 1,  6> velocity=< 1,  0>',
    #     'position=< 8,  9> velocity=< 0, -1>',
    #     'position=< 3,  3> velocity=<-1,  1>',
    #     'position=< 0,  5> velocity=< 0, -1>',
    #     'position=<-2,  2> velocity=< 2,  0>',
    #     'position=< 5, -2> velocity=< 1,  2>',
    #     'position=< 1,  4> velocity=< 2,  1>',
    #     'position=<-2,  7> velocity=< 2, -2>',
    #     'position=< 3,  6> velocity=<-1, -1>',
    #     'position=< 5,  0> velocity=< 1,  0>',
    #     'position=<-6,  0> velocity=< 2,  0>',
    #     'position=< 5,  9> velocity=< 1, -2>',
    #     'position=<14,  7> velocity=<-2,  0>',
    #     'position=<-3,  6> velocity=< 2, -1>',
    # ]

    lines = [[int(i) for i in re.findall(r'-?\d+', line)] for line in data]
    index = -1
    size = -1

    console.log('Task', 'Finding smallest sized object to work with')
    timer.start()
    for i in range(20000):
        minx = min(x + i * vx for (x, y, vx, vy) in lines)
        maxx = max(x + i * vx for (x, y, vx, vy) in lines)
        miny = min(y + i * vy for (x, y, vx, vy) in lines)
        maxy = max(y + i * vy for (x, y, vx, vy) in lines)

        test_size = maxx - minx + maxy - miny

        if size == -1 or test_size < size:
            size = test_size
            index = i

    console.log('Found', 'Min Size {} for index {}'.format(size, index))

    console.log('Task', 'Building data map')
    my_map = [[' '] * 200 for j in range(400)]
    for (x, y, vx, vy) in lines:
        my_map[y + index * vy][x + index * vx - 250] = '*'

    console.log('Task', 'Saving map to file')
    with open(join(ctx.obj['BASE_PATH'], 'output.txt'), 'w+') as handle:
        for m in my_map:
            handle.write(''.join(m) + '\n')

    timer.end()

    console.header('output')
    timer.output()
Beispiel #17
0
def main():
    global cam, turret

    #start cam
    cam = Camera.Capture(cfg)
    cam.daemon = True
    cam.start()
    i = 0
    while (i < 50):  #allow 5sec for startup
        i += 1
        sleep(0.1)
        if cam.rawframe != None:
            break
    frame = cam.getFrame()  #need during init

    #start turret
    turret = Turret.Targetting(cfg)
    turret.daemon = True
    turret.recenter()
    turret.start()

    #start controller
    cmdlistener = Controller.Listener(cfg)
    cmdlistener.startlisteners()
    key = ""

    #display
    displaytext = ""  #for writing message in window
    if os.environ.get('DISPLAY') and int(cfg['camera']['display']):
        display = True
        print 'display found'
    else:
        display = False
        print 'no display'
    if display:
        cv2.namedWindow("display", cv2.cv.CV_WINDOW_AUTOSIZE)
        cv2.setMouseCallback("display", on_click, 0)

    #tracking functions
    track = Tracker.Tracking(cfg, display)
    tracker = None  #dlib object tracking

    #motion detection
    avgframe = np.float32(frame)
    avgtimer = threading.Event()  #TODO: put this in Timer thread?

    #speak
    speak = Speak.Speak(cfg)
    speak.say("ready")

    cam.resetFPS()

    while (1):

        #capture frame,position
        framexy = turret.xy
        frame = cam.getFrame()
        if display:  #default display
            displayframe = frame

        #targetting color (hsv)
        if track.mode == 4:
            cx, cy, displayframe = track.targetHsv(frame)
            if cx:
                turret.sendTarget(turret.coordToPulse((cx, cy)), framexy)
        #targetting object (dlib)
        if track.mode == 5:
            tracker.update(frame)
            rect = tracker.get_position()
            cx = (rect.right() + rect.left()) / 2
            cy = (rect.top() + rect.bottom()) / 2
            turret.sendTarget(turret.coordToPulse((cx, cy)), framexy)
            if display:
                pt1 = (int(rect.left()), int(rect.top()))
                pt2 = (int(rect.right()), int(rect.bottom()))
                cv2.rectangle(displayframe, pt1, pt2, (255, 255, 255), 3)
        #detect motionhsv, motionobj
        elif track.mode == 2 or track.mode == 3:
            if avgtimer.isSet():
                #learn image for motion detection
                cv2.accumulateWeighted(frame, avgframe, 0.8)
                resframe = cv2.convertScaleAbs(avgframe)
            else:
                cnt, motionmask = track.getMotionContour(
                    frame, resframe, track.areathresholdobject
                    if track.mode == 3 else track.areathresholdcolor)
                if display:
                    displayframe = cv2.cvtColor(motionmask.copy(),
                                                cv2.COLOR_GRAY2RGB)
                if not cnt == None:
                    #motionhsv
                    if track.mode == 2:  #mask for mean
                        track.bgrtarget = cv2.mean(frame, motionmask)
                        framehsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
                        track.hsvtarget = cv2.mean(framehsv, motionmask)
                        track.setColorRange()
                        turret.armed = True
                        displaytext = "Targetting " + Speak.BGRname(
                            track.bgrtarget)
                        speak.say(displaytext)
                        track.mode = 4  #hsvtarget
                        cam.resetFPS()
                    #motionobj
                    if track.mode == 3:  #object points
                        x, y, w, h = cv2.boundingRect(cnt)
                        if x > 3 and y > 3:  # and x+w<cam.w-3 and y+h<cam.h-3: #object inside frame #TODO: which sides?
                            points = (x, y, x + w, y + h)
                            tracker = dlib.correlation_tracker()
                            tracker.start_track(frame, dlib.rectangle(*points))
                            displaytext = "Targetting object"
                            speak.say(displaytext)
                            track.mode = 5  #dlib
                            cam.resetFPS()
                        else:
                            cv2.rectangle(displayframe, (x, y), (x + w, y + h),
                                          (0, 0, 255), 2)
        #face
        elif track.mode == 1:
            detector = dlib.get_frontal_face_detector()
            faces = detector(frame)
            best_area = 0
            best_face = None
            for d in faces:
                area = (d.left() - d.right()) * (d.top() - d.bottom())
                if area > best_area:
                    best_area = area
                    best_face = d
            if not best_face == None:  #face points
                points = (best_face.left(), best_face.top(), best_face.right(),
                          best_face.bottom())
                tracker = dlib.correlation_tracker()
                tracker.start_track(frame, dlib.rectangle(*points))
                displaytext = "Targetting human"
                speak.say(displaytext)
                track.mode = 5  #dlib
                #if face, go for shirt color
#                xs = int(x + (x/2)) #shirt
#                ys = int(y+(h*1.7)) #shirt
#                framecenter = frame[ys-track.sampleradius:ys+track.sampleradius, xs-track.sampleradius:xs+track.sampleradius]
#                framecenterhsv = cv2.cvtColor(framecenter, cv2.COLOR_BGR2HSV)
#                track.hsvtarget = [int(cv2.mean(framecenterhsv)[0]), int(cv2.mean(framecenterhsv)[1]), int(cv2.mean(framecenterhsv)[2])]
#                track.setColorRange()
#                track.bgrtarget = [int(cv2.mean(framecenter)[0]), int(cv2.mean(framecenter)[1]), int(cv2.mean(framecenter)[2])]
#                speak.say("Hey, you in the " + Speak.BGRname(track.bgrtarget) + " shirt")
#                track.mode = 4 #hsvtarget

#display frame
        if display:
            if displaytext:
                textsize = 0.003 * cam.w
                cv2.putText(displayframe, displaytext, (5, cam.h - 5),
                            cv2.FONT_HERSHEY_SIMPLEX, textsize, (0, 255, 255))
            cv2.imshow('display', displayframe)
            cv2.waitKey(1)

# Command Handler --------------------------
        if cmdlistener.cmdsent.isSet():
            key = cmdlistener.cmd
            cmdlistener.reset()
            #quit/restart
            if key == "?" or key == "h":
                f = open(
                    os.path.dirname(os.path.abspath(__file__)) + '/help.txt',
                    'r')
                print(f.read())
            elif key == "q" or key == "r":
                turret.quit()
                cam.quit()
                cmdlistener.quit()
                cfg.write()
                if display:
                    cv2.destroyAllWindows()
                if key == "q":
                    speak.say("quitting. bye")
                    return 0
                if key == "r":
                    speak.say("restarting")
                    return 1
#--- Targeting ---
            elif key == " ":  #reset all
                speak.say("Reset")
                displaytext = ""
                turret.armed = False
                track.mode = 0
                turret.recenter()
                cam.resetFPS()
            elif key == "t":  #sample center of image
                sampleradius = 0.02 * (cam.w /
                                       float(cfg['camera']['scaledown']))
                framecenter = frame[(cam.h / 2) - sampleradius:(cam.h / 2) +
                                    sampleradius, (cam.w / 2) -
                                    sampleradius:(cam.w / 2) + sampleradius]
                framecenterhsv = cv2.cvtColor(framecenter, cv2.COLOR_BGR2HSV)
                track.hsvtarget = [
                    int(cv2.mean(framecenterhsv)[0]),
                    int(cv2.mean(framecenterhsv)[1]),
                    int(cv2.mean(framecenterhsv)[2])
                ]
                track.setColorRange()
                track.bgrtarget = [
                    int(cv2.mean(framecenter)[0]),
                    int(cv2.mean(framecenter)[1]),
                    int(cv2.mean(framecenter)[2])
                ]
                displaytext = "Targetting " + Speak.BGRname(track.bgrtarget)
                speak.say(displaytext)
                track.mode = 4
                cam.resetFPS()
            elif key == "1":  #start face detect
                displaytext = "Seeking humans."
                speak.say(displaytext)
                track.mode = 1  #face
                cam.resetFPS()
                #track.faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
            elif key == "2" or key == "3":  #start motion detect: 2:hsv or 3:dlib
                displaytext = "Motion " + ("by color"
                                           if key == "2" else "by object")
                speak.say(displaytext)
                Timer.Countdown(5, avgtimer).thread.start()
                sleep(.1)  #timer set
                track.mode = int(key)  #motiondetect
#--- Controls ---
            elif key == "j":  #joke/taunt
                speak.taunt()
            elif key == "g":  #test fire
                turret.fire()
#--- Settings ---
            elif key == "i":  #fps
                print(cam.getFPS())
                cam.resetFPS()
            elif key == "p":  #toggle armed
                turret.armed = not turret.armed
                if turret.armed:
                    speak.say("armed")
                else:
                    speak.say("disarmed")
            elif key == "n":  #toggle noisy
                if speak.quiet:
                    speak.quiet = 0
                    speak.say("talking")
                else:
                    speak.say("quiet")
                    sleep(.1)
                    speak.quiet = 1
                cfg['speak']['quiet'] = speak.quiet
            elif key == "+":  #volume
                speak.volume(.1)
                speak.say("check")
            elif key == "-":
                speak.volume(-.1)
                speak.say("check")
            elif key == "y":  #restart speak
                speak = Speak.Speak()
                speak.say("ok")
            elif key == "w":  #pause display
                cam.resetFPS()
                if not display and os.environ.get('DISPLAY') and int(
                        cfg['camera']['display']):
                    display = True
                    print("- display resumed -")
                else:
                    display = False
                    print("- display paused -")


#--- Tolerance ---
            else:
                adjustpercent = 0.10  #step +/- percent for manual key adjustments
                adjust = lambda val, sign: val * (1 + (sign * adjustpercent))
                if key == "l" or key == "m":  #target sensitivity
                    turret.firesensitivity = adjust(turret.firesensitivity,
                                                    1 if key == "l" else -1)
                    cfg['tolerance'][
                        'firesensitivity'] = turret.firesensitivity
                if key == "a" or key == "z":  #threshhold area
                    track.areathresholdcolor = adjust(track.areathresholdcolor,
                                                      1 if key == "a" else -1)
                    cfg['tolerance']['colortrack'][
                        'areathreshold'] = track.areathresholdcolor
                if key == "s" or key == "x":  #threshhold area
                    track.areathresholdobject = adjust(
                        track.areathresholdobject, 1 if key == "s" else -1)
                    cfg['tolerance']['objecttrack'][
                        'areathreshold'] = track.areathresholdobject
                print "Area(Color):", track.areathresholdcolor, "Area(Object):", track.areathresholdobject, "Trigger:", turret.firesensitivity
Beispiel #18
0
class Unit:
    def __init__(self,
                 uType,
                 regs,
                 mem=None,
                 execTime=1,
                 continuePipeline=None):
        self.busy = False
        self.type = uType
        self.memory = mem
        self.execTime = execTime
        self.continuePipeline = continuePipeline
        self.regs = regs
        self.clock = 0
        self.timer = Timer()
        self.currentStage = 0
        self.blocked = False
        self.stages = [None, self.issue, self.read, self.execute, self.write]
        self.Vi = None
        self.Vj = None
        self.Vk = None

    def Busy(self):
        return self.busy

    def _setNotBusy(self):
        self.busy = False
        self.blocked = False
        self.Vi = None
        self.Vj = None
        self.Vk = None
        self.Op = None
        self.currentStage = 0

    def operate(self, op):
        if op.find('ADD') >= 0:
            return self.Vj + self.Vk
        elif op.find('SUB') >= 0:
            return self.Vj - self.Vk
        elif op.find('AND') >= 0:
            return self.Vj & self.Vk
        elif op.find('OR') >= 0:
            return self.Vj | self.Vk

        elif op.find('ADD.D') >= 0:
            return float(self.Vj) + float(self.Vk)
        elif op.find('SUB.D') >= 0:
            return float(self.Vj) - float(self.Vk)
        elif op.find('MUL.D') >= 0:
            return float(self.Vj) * float(self.Vk)
        elif op.find('DIV.D') >= 0:
            return float(self.Vj) / float(self.Vk)
        elif op.find('LUI') >= 0:
            return self.Vj << 16
        elif op.find('L') >= 0:
            return self.Vj

    # def _result(self):
    def issue(self, inst=None, bookKeep=False, clock=None):
        if inst is None:
            print "Issue: " + str(self.clock)

        if clock is not None:
            self.clock = clock

        if bookKeep:
            self.Op.mark('ISSUE', self.clock)
            print self.Op.inst + " > IS (" + str(self.clock) + ")"
            if self.Op.cmd == 'J':
                self.continuePipeline(int(self.Op.Fi))
                self._setNotBusy()
            return True

        Fi = inst.reg('Fi')
        Fj = inst.reg('Fj')
        Fk = inst.reg('Fk')

        if inst.cmd in ['SW', 'S.D', 'BEQ', 'BNE']:
            Fi = None
            Fj = inst.reg('Fi')
            Fk = inst.reg('Fj')

        if Fi is None or self.regs[Fi]['result'] is None:
            self.busy = True
            self.Op = inst

            if Fi is not None:
                self.regs[Fi]['result'] = {
                    'type': self.type,
                    'clock': self.clock
                }

            if Fj is not None:
                self.regs[Fj]['source'].append(self.type)

            if Fk is not None:
                self.regs[Fk]['source'].append(self.type)

            self.currentStage = 0
            self.blocked = not self.timer.tick(1)
            return True
        else:
            inst.mark('WAW', 'Y')
            return False

    def read(self, bookKeep=False):
        print "Read: " + str(self.clock)

        i = 'Fi'
        j = 'Fj'
        k = 'Fk'

        if self.Op.cmd in ['SW', 'S.D', 'BEQ', 'BNE']:
            k = j
            j = i

        Fj = self.Op.reg(j)
        Fk = self.Op.reg(k)

        if not bookKeep:
            val = None
            self.blocked = False
            if self.Vj is None or self.Vj == BUSY:
                if Fj is None:
                    self.Vj, mem = self.Op.val(j)
                elif (self.regs[Fj]['result'] is None
                      or self.regs[Fj]['result']['type'] == self.type
                      or self.regs[Fj]['result']['clock'] == self.clock):

                    val = self.regs[Fj]['value']
                    self.Vj, mem = self.Op.val(j, val)
                else:
                    self.Op.mark('RAW', 'Y')
                    self.blocked = True

            if self.Vk is None or self.Vk == BUSY:
                if Fk is None:
                    self.Vk, mem = self.Op.val(k)
                elif (self.regs[Fk]['result'] is None
                      or self.regs[Fk]['result']['type'] == self.type
                      or self.regs[Fk]['result']['clock'] == self.clock):
                    val = self.regs[Fk]['value']
                    self.Vk, mem = self.Op.val(k, val)
                else:
                    self.Op.mark('RAW', 'Y')
                    self.blocked = True

        elif not self.blocked:
            if Fj is not None:
                self.regs[Fj]['source'].remove(self.type)
            if Fk is not None:
                self.regs[Fk]['source'].remove(self.type)

            if ((self.Op.cmd == 'BEQ' and self.Vj == self.Vk)
                    or (self.Op.cmd == 'BNE' and self.Vj != self.Vk)):
                self.continuePipeline(int(self.Op.val('Fk')[0]))

            self.Op.mark('READ', self.clock)
            print self.Op.inst + " > RE (" + str(self.clock) + ")"

            if self.Op.cmd in ['BNE', 'BEQ']:
                self.continuePipeline()
                self._setNotBusy()

    def execute(self, bookKeep=False):
        print "Execute: " + str(self.clock)

        if not bookKeep:
            if self.type[:2] in ['In', 'FP']:
                if not self.blocked:
                    self.Vi = self.operate(self.Op.cmd)
                    self.blocked = not self.timer.tick(self.execTime)
                else:
                    self.blocked = not self.timer.tick()
            elif self.type[:2] == 'mA':
                self.blocked = True
                if self.Op.cmd in ['LW', 'L.D']:
                    val = self.memory.read(self.Vj, requestee=self)
                    if val != BUSY:
                        self.Vi = (self.Vi or '') + val
                        if self.Op.cmd == 'LW' or len(self.Vi) == 64:
                            self.Vi = int(self.Vi, 2)
                            self.blocked = False
                        else:
                            self.Vj += 1
                else:
                    val = self.memory.write(self.Vk,
                                            self.Vj[:32],
                                            requestee=self)
                    if val != BUSY:
                        self.Vj = self.Vj[32:]
                        if len(self.Vj) == 0:
                            self.blocked = False
                        else:
                            self.Vk += 1
        elif not self.blocked:
            self.Op.mark('EXECUTE', self.clock)
            print self.Op.inst + " > EX (" + str(self.clock) + ")"

    def write(self, bookKeep=False):
        print "Write: " + str(self.clock)
        if not bookKeep:
            if self.Op.cmd not in ['SW', 'S.D']:
                self.regs[self.Op.reg('Fi')]['value'] = self.Vi
        else:
            if self.Op.cmd not in ['SW', 'S.D']:
                self.regs[self.Op.reg('Fi')]['result'] = None
            self.Op.mark('WRITE', self.clock)
            print self.Op.inst + " > WR (" + str(self.clock) + ")"
            self._setNotBusy()

    def tick(self, clock, bookKeep=False):
        self.clock = clock

        if self.busy and self.currentStage < 5:
            if bookKeep and not self.blocked:
                print self.type + '<cycle Ends>',
                self.stages[self.currentStage](bookKeep=True)

            elif not bookKeep:
                if not self.blocked and self.timer.tick():
                    self.currentStage += 1

                if self.currentStage > 1:
                    print self.type + '<cycle start>',
                    self.stages[self.currentStage]()

    def getStage(self):
        return self.currentStage
Beispiel #19
0
                        found = True

            if found == False:
                for i in range(len(comp.quorry())):
                    if comp.quorry()[i] in text:
                        comp.Steve(text)
                        found = True

            if found == False:
                for i in range(len(Wikipedia.quorry())):
                    if Wikipedia.quorry()[i] in text:
                        Wikipedia.Steve(text)
                        found = True

            if found == False:
                for i in range(len(Timer.quorry())):
                    if Timer.quorry()[i] in text:
                        Timer.Steve(text)
                        found = True

            if found == False:
                for i in range(len(greating.quorry())):
                    if greating.quorry()[i] in text:
                        greating.Steve(text)
                        found = True

            if found == False:
                for i in range(len(Speek.quorry())):
                    if Speek.quorry()[i] in text:
                        Speek.Steve(text)
                        found = True
Beispiel #20
0
def executor():
    console.header('day 7, part 1')

    timer = Timer()
    steps = DataProvider.load('day7')
    # steps = [
    #     'Step C must be finished before step A can begin.',
    #     'Step C must be finished before step F can begin.',
    #     'Step A must be finished before step B can begin.',
    #     'Step A must be finished before step D can begin.',
    #     'Step B must be finished before step E can begin.',
    #     'Step D must be finished before step E can begin.',
    #     'Step F must be finished before step E can begin.',
    # ]

    timer.start()

    console.log('Task', 'Build nodes')
    node_names = set([])
    for step in steps:
        [parent, child] = re.match(r'Step ([A-Z]) .*? step ([A-Z]).*',
                                   step).group(1, 2)
        node_names.add(parent)
        node_names.add(child)

    console.log('Info', 'Creating {} nodes'.format(len(node_names)))
    nodes = []
    for node_name in node_names:
        nodes.append(Node(node_name))

    console.log('Info', 'Executing steps')
    count = 0
    for step in steps:
        count += 1
        console.log('Info', 'Step {} / {}'.format(count, len(steps)))

        [parent, child] = re.match(r'Step ([A-Z]) .*? step ([A-Z]).*',
                                   step).group(1, 2)

        parent = find(parent, nodes)
        child = find(child, nodes)

        parent.add_child(child)

    console.log('Info', 'Creating root node and children')
    root_node = Node('-')
    for node in [node for node in nodes if node.is_root()]:
        root_node.add_child(node)

    console.header('node picker')
    available_picks = root_node.child_nodes
    output = ''
    while available_picks:
        picks = set(sorted([n.name for n in available_picks]))
        pick = min(picks)

        console.log(
            'Info', 'Picking {} from {{ {} }}'.format(
                pick, ', '.join([n.name for n in available_picks])))

        node = find(pick, nodes)
        node.triggered = True
        output += node.name
        available_picks = list(
            filter(lambda n: n.name != pick, available_picks)) + [
                n for n in node.child_nodes if n.can_trigger()
            ]

    timer.end()

    console.header('output')
    console.log('Output', output)
    timer.output()