示例#1
0
    def location_exists(self, given_location_id, try_cached):
        loc_exists = False
        loc_array = None

        utils.d_print(4, "(given_location_id): ", given_location_id)

        try:

            # first check if we can try the cached array
            if not (try_cached and self.cached_locations):
                # if try_cached is set to false OR if the cached_locations are empty, then refresh.
                self.cached_locations = self.api_outbound.get_locations(
                    self.org_id, [], [])

            loc_array = self.cached_locations

            print(loc_array)
            for location in loc_array:
                if given_location_id == location['id']:
                    loc_exists = True

            utils.d_print(1, "loc_exists: ", loc_exists)

        except:
            utils.print_exception(1)

        return loc_exists
示例#2
0
def solve_2(filename, sum_to=1309761972):
    data = format_input(read_from_file(filename))
    start_index, end_index = 0, 0
    current_sum = data[start_index]
    d_print(data)
    while True:
        d_print("sum({}) = {}".format(data[start_index:end_index+1], current_sum)) 
        if current_sum > sum_to:
            d_print("Moving start up, and subtracting {}".format(data[start_index]))
            current_sum -= data[start_index]
            start_index += 1
            # the list isn't sorted, so we may need to backtrack
            while current_sum > sum_to:
                d_print("Moving end back, and substracting {}".format(data[end_index]))
                current_sum -= data[end_index]
                end_index -= 1

            if end_index <= start_index:
                end_index = start_index
                current_sum = data[start_index]

        elif current_sum < sum_to:
            d_print("Moving end up and adding {}".format(data[end_index]))
            end_index += 1
            current_sum += data[end_index]

        else:
            # we have a contiguous sum that equals our goal
            sorted_data = sorted(data[start_index:end_index+1])
            return sorted_data[0] + sorted_data[-1]
示例#3
0
def solve_2(filename):
    adapter_ratings = format_input(read_from_file(filename))
    d_print(sorted(adapter_ratings))
    d_tree = possible_connections_tree(sorted(adapter_ratings))
    d_print(d_tree)
    total = total_configurations(0, d_tree, {})
    return total
示例#4
0
 def turn(self, command, angle):
     rotate_by = angle / 90  # how many rotational 'units' we need to change by
     self.facing_direction_index += rotate_by * turning_direction[command]
     # wrap when we've turned past our directions list
     self.facing_direction_index = int(self.facing_direction_index %
                                       len(ordered_directions))
     d_print(self.facing_direction_index)
示例#5
0
def solve_1(filename):
    memory = {}
    mask_to_directives = format_input(read_from_file(filename))
    for mask, directives in mask_to_directives.items():
        d_print("{}: {}".format(mask, directives))
        for address, value in directives:
            memory[address] = apply_mask(mask, value)
    return sum(memory.values())
示例#6
0
 def print_state(self):
     facing = ordered_directions[self.facing_direction_index]
     x, y = self.position
     d_print("The ship is at position ({}, {}) facing {}.".format(
         x, y, facing))
     x, y = self.waypoint
     d_print("The wanypoint is at position ({}, {}) relative to the ship.".
             format(x, y))
示例#7
0
def apply_mask(mask, value):
    masked_value = ''
    for i in range(len(mask)):
        if mask[-(i + 1)] != 'X':
            masked_value = '{}{}'.format(int(mask[-(i + 1)]), masked_value)
        else:
            masked_value = '{}{}'.format(value >> i & 1, masked_value)
    d_print('{} -> {}'.format(masked_value, int(masked_value, 2)))
    return int(masked_value, 2)
示例#8
0
 def print_state(self):
     d_print("**************************\n")
     for y, row in enumerate(self.map):
         row_to_print = ''
         for x, col in enumerate(row):
             if (x, y) == self.current_position:
                 row_to_print += 'X' if self.is_tree() else 'O'
             else:
                 row_to_print += self.map[y][x]
         d_print(row_to_print)
示例#9
0
def rules_regex_for_key(key, rules_dict, cache, is_part_2=False):
    # convert each key into it's piece of the regex - store that in a cache since it looks like there
    # is a lot of repetition in the keys, so performance could be problematic in building this.
    # for the sample this is the regex string that should be produced: r'^a((aa|bb)(ab|ba)|(ab|ba)(aa|bb))b$'
    rules = rules_dict[key]
    d_print("{}: {}".format(key, rules))
    # case 0: the key has already been solved and is in the cache - don't bother recomputing it
    if key in cache:
        return cache[key]

    # case 1: the base case where we have one of our characters
    if isinstance(rules, str):
        str_pattern = '({})'.format(rules)
        cache[key] = str_pattern
        return str_pattern

    # This is a little gross, I'm sure there's a sensible way to build the 11 case wildcard, but this is easier
    if is_part_2 and key == '8':
        rule_str = rules_regex_for_key('42', rules_dict, cache, is_part_2)
        str_pattern = '({})+'.format(rule_str)
        cache[key] = str_pattern
        return str_pattern

    # The original regex only matches 24 characters. The longest string in the input is 96 characters.
    # So the repeating pattern here can be something like:  ab | aabb | aaa(ab)*bbb so since regexes
    # don't really count very well, we'll have to add in the possibilities manually, which totally sucks.
    # so our regex should follow this pattern (but be more ginormous) ab | a(ab)+b | aa(ab)+bb | ... up
    # to 36 a's and b's on either side to be safe. Bleh. I'm going to want to do this in a loop :P
    if is_part_2 and key == '11':
        rule_42 = rules_regex_for_key('42', rules_dict, cache, is_part_2)
        rule_31 = rules_regex_for_key('31', rules_dict, cache, is_part_2)

        rules_strs = ['({}{})'.format(rule_42, rule_31)]
        repeating = '({}{})+'.format(rule_42, rule_31)
        for i in range(36):
            str_42 = '{}'.format(rule_42) * (i + 1)
            str_31 = '{}'.format(rule_31) * (i + 1)
            rule_str = '({}{}{})'.format(str_42, repeating, str_31)
            rules_strs.append(rule_str)
        str_pattern = '({})'.format('|'.join(rules_strs))
        return str_pattern
    # end of the part 2 grossness.

    if isinstance(rules, list):
        rules_strs = []
        for subrules in rules:
            rule_str = ''
            for rule in subrules:
                rule_str += rules_regex_for_key(rule, rules_dict, cache,
                                                is_part_2)
            rules_strs.append(rule_str)
        str_pattern = '({})'.format('|'.join(rules_strs))
        cache[key] = str_pattern
        return str_pattern
示例#10
0
 def row_to_be_skipped(row_no):
     utils.d_print(6, "Row: ", row_no, "specific_rows:", self.specific_rows)
     ret_val = False
     # skip the first row; it is the names of various columns; we start with row_no 1.
     if row_no == 0:
         ret_val = True
     elif self.specific_rows:  # we check if this is not None
         if str(row_no) not in self.specific_rows:
             ret_val = True
     utils.d_print(6, "Row: ", row_no, "Skip?:", ret_val)
     return ret_val
示例#11
0
    def push_to_bts(self):
        company_prefixes = []
        inbound_api = None

        try:
            # 1. load the workbook
            wb = load_workbook(filename = self.filename)

            # 2. set up the inbound API
            org = organization.Organization("Name", utils.global_args.client)
            org_id = org.get_id()
            inbound_api = api_inbound.APIInbound(5, org_id, utils.global_args.env, utils.global_args.header_entitled_org)

            # get company prefixes, head quarters GLN, etc.
            org_params = org.get_properties()
            # if we are asked to use a different HQ GLN, use it.
            if utils.global_args.hq_gln:
                org_params['hq_gln'] = utils.global_args.hq_gln

            # 3. start parsing the excel sheet
            #     a. first gather global params
            sheet_names = wb.sheetnames
            utils.d_print(2, "Sheet Names in the Excel Sheet: ", sheet_names)


            # if arguments indicate specific rows to be pushed, push the same.
            if utils.global_args.specific_rows:
                self.specific_rows = utils.global_args.specific_rows.split(',')
            else:
                self.specific_rows = None

            if 'if' in utils.global_args.isheets:
                # b. next push if there are any facilities
                facilities = wb['Facilities']
                self.parse_and_push_worksheet(org_params, facilities, 'Facility', inbound_api)

            if 'ip' in utils.global_args.isheets:
                # c. next push any products   
                products = wb['Products']
                self.parse_and_push_worksheet(org_params, products, 'Product',inbound_api)

            if 'ie' in utils.global_args.isheets:
                # d. next push any events
                events = wb['Events']
                self.parse_and_push_worksheet(org_params, events, 'Event',inbound_api)

            if 'ipl' in utils.global_args.isheets:
                # e. next push any events
                payloads = wb['Payloads']
                self.parse_and_push_worksheet(org_params, payloads, 'Payload',inbound_api)
        except:
            utils.print_exception(1)

            return