def callback(self, context, dt):
     self.delta += dt
     if self.state == 0:
         h.touch_file(h.path('src', 'src5.c'))
         self.state = 1
     if self.delta > 0.5:
         h.touch_file(h.path('src', 'sub', 'src6.c'))
     if self.delta > 1.0:
         return False
     return True
Beispiel #2
0
def alias():
    import json
    import helpers
    actionList = json.loads(
        helpers.read_file('{}/{}'.format(helpers.path('util'),
                                         'action-list.json')))
    bashrcFilepath = helpers.run_command_output('cd {} && cd ../'.format(
        helpers.path('util'))) + '.baconrc'
    contents = helpers.read_file(bashrcFilepath)
    pat = re.compile('alias {}='.format())
    match = re.search(pat, contents)
    formattedAlias = '\nalias {}="python {}/actions.py"'.format(
        actionList['alias'], helpers.path('util'))
    if not match:
        contents += formattedAlias
    helpers.write_file(bashrcFilepath, contents)
Beispiel #3
0
    def test_find_most_sleepy_guard(self):
        entries = read_raw_entries(path(__file__, 'test-input.txt'))
        shifts = process_shifts(entries)

        guard, mins_asleep = find_most_sleepy_guard(shifts)

        self.assertEqual(10, guard)
        self.assertEqual(50, mins_asleep)
Beispiel #4
0
    def test_find_most_sleepy_minute(self):
        entries = read_raw_entries(path(__file__, 'test-input.txt'))
        shifts = process_shifts(entries)

        guard, mins_asleep = find_most_sleepy_guard(shifts)

        min = find_sleepiest_minute(guard, shifts)

        self.assertEqual(24, min)
Beispiel #5
0
def profile():
    import helpers
    import os
    utilDir = helpers.path('util')
    if not os.path.exists(utilDir + '/profiles/profile.py'):
        snippet = '''{\n\t"settings" : {\n\n\t\t}\n}'''
        helpers.run_command('mkdir {}/profiles'.format(utilDir), False)
        helpers.write_file(utilDir + '/profiles/profile.py', snippet)
        print("\nprofile added!\n")
        msg.done
Beispiel #6
0
def helpers():
    import helpers
    # get bacon filepath
    baconHelpersFilepath = helpers.run_command_output(
        'cd {} && cd ../ && pwd'.format(helpers.path('util'))).replace(
            '\n', '') + '/bacon/template/helpers.py'
    utilityHelpersFilepath = '/{}/{}'.format(helpers.path('util'),
                                             'helpers.py')
    # get target helpers content
    content = helpers.read_file(utilityHelpersFilepath)
    customHelpers = content.split(
        "# custom helpers start here\n# =========================")[1]
    # get default helpers template from bacon
    newDefaultHelpers = helpers.read_file(baconHelpersFilepath)
    # pack content and save
    newContent = newDefaultHelpers + customHelpers
    # print(newContent)
    helpers.write_file(utilityHelpersFilepath, newContent)
    msg.done()
Beispiel #7
0
    def test_movement(self):
        entries = read_raw_entries(path(__file__, 'tests/movement.txt'))
        grid_map, elves, goblins = parse_map(entries)

        print_state('Initial', grid_map, elves, goblins)

        for i in range(5):
            j = 0
            for f in sort_fighters(elves, goblins):
                j += 1
                f.move(grid_map, elves + goblins)

                print_state('{}.{}'.format(i, j), grid_map, elves, goblins)
Beispiel #8
0
    def test_target_selection(self):
        entries = read_raw_entries(
            path(__file__, 'tests/target_selection/start_map.txt'))
        grid_map, elves, goblins = parse_map(entries)

        print_state('Initial', grid_map, elves, goblins)

        i = 0
        for f in sort_fighters(elves, goblins):
            i += 1
            f.move(grid_map, elves + goblins)

            print_state('0.{}'.format(i), grid_map, elves, goblins)
Beispiel #9
0
    def __init__(self, models):
        super(SimulatorC2, self).__init__()
        self.name = self.__class__.__name__

        # Modelica package dependencies
        self.deps = ['FluidJM', 'DHP']

        # Path to dependencies and problem
        self.paths = helpers.path(self.deps, models['file'])

        # Compiler options
        self.options = {
            "state_initial_equations": True,
            "enable_variable_scaling": True
        }

        self.simulator_model = models['sim']
        self.optimization_problem = models['opt']

        self.load()
Beispiel #10
0
    def __init__(self, models):
        super(SimulatorC2, self).__init__()
        self.name = self.__class__.__name__

        # Modelica package dependencies
        self.deps = ['FluidJM', 'DHP']

        # Path to dependencies and problem
        self.paths = helpers.path(self.deps, models['file'])

        # Compiler options
        self.options = {
            "state_initial_equations": True,
            "enable_variable_scaling": True
        }

        self.simulator_model = models['sim']
        self.optimization_problem = models['opt']

        self.load()
Beispiel #11
0
    def test_process_shifts(self):
        entries = read_raw_entries(path(__file__, 'test-input.txt'))

        shifts = process_shifts(entries)
        self.assertEqual(5, len(shifts))

        self.assertEqual(10, shifts[0].guard_id)
        self.assertEqual(datetime.date(1518, 11, 1), shifts[0].date)

        self.assertEqual(5, shifts[0].sleep_times[0].sleep_start)
        self.assertEqual(25, shifts[0].sleep_times[0].sleep_until)
        self.assertEqual(20, shifts[0].sleep_times[0].mins_asleep())

        self.assertEqual(30, shifts[0].sleep_times[1].sleep_start)
        self.assertEqual(55, shifts[0].sleep_times[1].sleep_until)
        self.assertEqual(25, shifts[0].sleep_times[1].mins_asleep())

        self.assertEqual(45, shifts[0].mins_asleep())

        self.assertEqual(
            list(range(5, 25)) + list(range(30, 55)), shifts[0].list_of_mins())
Beispiel #12
0
def execute():
	baconBitsPath = helpers.run_command_output('cd {} && cd ../ && pwd'.format(helpers.path('util')), False).replace('\n', '')
	baconrcFile = baconBitsPath + '/.baconrc'
	DATA = helpers.read_file(baconrcFile)
	utilList = os.listdir(baconBitsPath)
	addPerks = helpers.kv_set(settings, 'perks')
	count = 0
	# print(utilList)
	# print(addPerks)
	APPENDED_DATA_STR = DATA
	for item in utilList:
		path = baconBitsPath + '/' + item
		try:
			alias = helpers.get_alias(path)
		except:
			alias = False
		if alias:
			aliasStr = 'alias {ALIAS}="python {PATH}/actions.py"'.format(ALIAS= alias, PATH= path)
			# print(aliasStr)
			pat = re.compile(aliasStr)
			match = re.search(pat, DATA)
			if not match:
				count += 1
				print('\nadding alias: {}'.format(alias))
				APPENDED_DATA_STR += '\n' + aliasStr
				if addPerks == "True" or addPerks == "true":
					aliasStrGoto = '''        elif [ $1 = "{ALIAS}" ]; then
            cd {PATH}
        #~~~ bacon:goto placeholder'''.format(ALIAS= alias, PATH= path)
					aliasStrShowme = '''        elif [ $1 = "{ALIAS}" ]; then
            open {PATH}
        #~~~ bacon:showme placeholder'''.format(ALIAS= alias, PATH= path)
					APPENDED_DATA_STR = APPENDED_DATA_STR.replace('        #~~~ bacon:goto placeholder', aliasStrGoto)
					APPENDED_DATA_STR = APPENDED_DATA_STR.replace('        #~~~ bacon:showme placeholder', aliasStrShowme)
	if count > 0:
		helpers.write_file(baconrcFile, APPENDED_DATA_STR)
	else:
		print("\n:: Nothing to add ::")

	msg.done()
Beispiel #13
0
def execute():
    baconBitsPath = helpers.run_command_output(
        'cd {} && cd ../ && pwd'.format(helpers.path('util')),
        False).replace('\n', '')
    baconrcFile = baconBitsPath + '/.baconrc'
    DATA = helpers.read_file(baconrcFile)
    utilList = os.listdir(baconBitsPath)
    count = 0
    # print(utilList)
    MODIFIED_DATA_STR = DATA
    for item in utilList:
        path = baconBitsPath + '/' + item
        try:
            alias = helpers.get_alias(path)
        except:
            alias = False
        if alias:
            aliasStr1 = '''        elif [ $1 = "{ALIAS}" ]; then
            cd {PATH}
        #~~~ bacon:goto placeholder'''.format(ALIAS=alias, PATH=path)
            aliasStr2 = '''        elif [ $1 = "{ALIAS}" ]; then
            open {PATH}
        #~~~ bacon:showme placeholder'''.format(ALIAS=alias, PATH=path)
            pat = re.compile(
                'elif \[ \$1 = "{ALIAS}" \]; then'.format(ALIAS=alias))
            match = re.search(pat, DATA)
            if not match:
                count += 1
                print('\nadding utility to goto and showme: {}'.format(alias))
                MODIFIED_DATA_STR = MODIFIED_DATA_STR.replace(
                    '        #~~~ bacon:goto placeholder', aliasStr1)
                MODIFIED_DATA_STR = MODIFIED_DATA_STR.replace(
                    '        #~~~ bacon:showme placeholder', aliasStr2)
    if count > 0:
        helpers.write_file(baconrcFile, MODIFIED_DATA_STR)
    else:
        print("\n:: Nothing to add ::")

    msg.done()
Beispiel #14
0
 def test_example_2_with_boost(self):
     entries = read_raw_entries(path(__file__, 'test-input.txt'))
     armies = parse_input(entries)
     r, imm_system_wins = solve_24(armies, 1570)
     self.assertEqual(51, r)
     self.assertTrue(imm_system_wins)
 def test_sample(self):
     entries = read_raw_entries(path(__file__, 'test-input.txt'))
     r = solve_18(entries)
     self.assertEqual(1147, r)
Beispiel #16
0
import helpers, json

actionList = json.loads(
    helpers.read_file('{}/{}'.format(helpers.path('util'),
                                     'action-list.json')))


def statusMessage():
    if len(actionList['actions']) > 0:
        print("")
        for item in actionList['actions']:
            print('''[ {} {} ]\t\t{}'''.format(actionList['alias'],
                                               item['name'],
                                               item['description']))
        print("")
    else:
        print('''
<tool-name> is working successfully!
''')


def done():
    print('''
[ Process Completed ]
''')


def example():
    print('''
process working!
''')
Beispiel #17
0
 def test_example_1(self):
     entries = read_raw_entries(path(__file__, 'test-input.txt'))
     armies = parse_input(entries)
     r, imm_system_wins = solve_24(armies)
     self.assertEqual(5216, r)
     self.assertFalse(imm_system_wins)
Beispiel #18
0
 def test_example(self):
     stars = read_stars(path(__file__, 'test-input.txt'))
     solve_10(stars)
    def test_solve_7a(self):
        entries = read_raw_entries(path(__file__, 'test-input.txt'))
        steps = process_into_steps(entries, 0)
        r = solve_7a(steps)

        self.assertEqual('CABDFE', r)
 def test_puzzle_sample_1(self):
     r = run_puzzle(path(__file__, 'test-data/01b-sample-1.txt'))
     self.assertEqual(0, r)
 def test_example(self):
     nanobots = parse_input(path(__file__, 'test-input.txt'))
     in_range = solve_23(nanobots)
     self.assertEqual(7, in_range)
 def test_example_1_with_additional_point(self):
     points = parse_input(
         path(__file__, 'test-input-1-with-additional-point.txt'))
     c = solve_25(points)
     self.assertEqual(1, c)
Beispiel #23
0
                break

            if star.has_neighbor(stars):
                neighbor_count += 1
            else:
                lone_stars += 1
                if lone_stars > lone_star_threshold:
                    break

        if run and (neighbor_count / len(stars) > 0.5):
            print(time)
            print_sky(stars)

        for star in stars:
            star.update()

        time += 1


def get_sky_range(stars):
    min_x = min(stars, key=lambda s: s.x).x
    max_x = max(stars, key=lambda s: s.x).x
    min_y = min(stars, key=lambda s: s.y).y
    max_y = max(stars, key=lambda s: s.y).y
    return max_x, max_y, min_x, min_y


if __name__ == '__main__':
    stars = read_stars(path(__file__, 'input.txt'))
    solve_10(stars)
 def test_example_1(self):
     points = parse_input(path(__file__, 'test-input-1.txt'))
     c = solve_25(points)
     self.assertEqual(2, c)
        polymer = new_polymer

    return polymer


def solve_5b(polymer):
    letters = list(string.ascii_lowercase)

    shortest_polymer = len(polymer) * 2

    for letter in letters:
        print(letter)
        stripped = re.sub(r'[{}{}]'.format(letter, letter.swapcase()), '',
                          polymer)
        print('{} stripped length: {}'.format(letter, len(stripped)))
        compressed_polymer_length = len(solve_try_1(stripped))
        if (compressed_polymer_length) < shortest_polymer:
            shortest_polymer = compressed_polymer_length

    return shortest_polymer


if __name__ == '__main__':
    polymer = read_raw_entries(path(__file__, 'input.txt'))[0]
    result = solve_try_1(polymer)
    print('Compressed polymer length: {}'.format(len(result)))

    polymer = read_raw_entries(path(__file__, 'input.txt'))[0]
    result = solve_5b(polymer)
    print('Shortest possible compressed polymer length: {}'.format(result))
Beispiel #26
0
def actionlist():
    import helpers
    helpers.run_command('code {}/action-list.json'.format(
        helpers.path('util')))
Beispiel #27
0
                                   key=lambda kv: kv[1])
    return sorted_influence_list[len(sorted_influence_list) - 1][1]


def solve_6b(points, threshold):
    grid, max_x, max_y, min_x, min_y = setup_grid(points)

    total_size = 0
    for i in range(min_x, max_x + 1):
        for j in range(min_y, max_y + 1):
            if grid[i][j].is_within_threshold(threshold):
                total_size += 1

    return total_size


if __name__ == '__main__':
    entries = read_raw_entries(path(__file__, 'input.txt'))
    points = convert_points(entries)

    r = solve_6a(points)

    print('Largest size: {}'.format(r))

    entries = read_raw_entries(path(__file__, 'input.txt'))
    points = convert_points(entries)

    r = solve_6b(points, 10000)

    print('Largest size: {}'.format(r))
    def test_solve_6a(self):
        entries = read_raw_entries(path(__file__, 'test-input.txt'))
        points = convert_points(entries)

        r = solve_6a(points)
        self.assertEqual(17, r)
 def test_example_part_2(self):
     nanobots = parse_input(path(__file__, 'test-input-part-2.txt'))
     distance = solve_23_part_2(nanobots)
     self.assertEqual(36, distance)
Beispiel #30
0
    return max(scores)


def solve_9_with_deque(input: str, multiplier: int = 1):
    player_count, last_marble_value = parse_params(input)
    last_marble_value *= multiplier

    scores: List[int] = []
    for i in range(0, player_count):
        scores.append(0)

    circle = DequeCircle()

    marble_value = 1
    while marble_value <= last_marble_value:
        score, string_rep = circle.add_marble(marble_value)
        scores[(marble_value - 1) % player_count] += score
        marble_value += 1

    return max(scores)


if __name__ == '__main__':
    input = read_raw_entries(path(__file__, 'input.txt'))[0].strip()
    r = solve_9(input, 1)
    print('9a. Winning score: {}'.format(r))

    input = read_raw_entries(path(__file__, 'input.txt'))[0].strip()
    r = solve_9(input, 100)
    print('9b. Winning score: {}'.format(r))
Beispiel #31
0
def do_action(ARGS):
    import helpers
    argDict = helpers.arguments(ARGS)

    name = helpers.path('util').split('/')[-1]
    fullPath = helpers.path('util')
    titleString = "Action"
    if argDict:
        if 'args' in argDict:
            if argDict['args'] == 'true':
                titleString = "Action With Arguments"
    newFeature = helpers.user_input('''
-- New {} --
Please give your new action a name [Eg: OpenFile]: '''.format(titleString))
    newAction = helpers.user_input('''
What would you like to call the action? ''')

    basicSnippet = '''import messages as msg
import helpers

# settings = helpers.get_settings()

def execute():
	msg.example()
'''
    argSnippet = '''import messages as msg
import helpers

# settings = helpers.get_settings()

def execute(ARGS):
	argDict = helpers.arguments(ARGS)
	print(argDict)
'''
    finalPath = helpers.path('util') + '/' + newFeature + '.py'
    statusMsg = '''
NAME:           {}
NEW MODULE:     {}
NEW ACTION:     {}
LOCATION:       {}'''.format(name, newFeature, newAction, finalPath)
    print(statusMsg)
    template = basicSnippet
    if argDict:
        if 'args' in argDict:
            if argDict['args'] == 'true':
                template = argSnippet
    helpers.write_file(finalPath, template)
    data = helpers.read_file(fullPath + '/actions.py')
    data = data.replace(
        '# new imports start here', '''import {}
# new imports start here'''.format(newFeature))

    basicContent = '''
elif action == "{newAction}":
	{newFeature}.execute()
# new actions start here'''.format(newFeature=newFeature, newAction=newAction)
    argContent = '''
elif action == "{newAction}":
	{newFeature}.execute(args)
# new actions start here'''.format(newFeature=newFeature, newAction=newAction)

    newContent = basicContent
    if argDict:
        if 'args' in argDict:
            if argDict['args'] == 'true':
                newContent = argContent
    data = data.replace("# new actions start here", newContent)
    helpers.write_file(fullPath + '/actions.py', data)
    actionData = json.loads(helpers.read_file(fullPath + '/action-list.json'))
    newItem = {}
    newItem['name'] = newAction
    newItem['description'] = ''
    actionData['actions'].append(newItem)
    helpers.write_file(fullPath + '/action-list.json',
                       json.dumps(actionData, indent=4))
    msg.done()
 def test_example_1(self):
     entries = read_raw_entries(path(__file__, 'test-input.txt'))
     r = solve_12_good(entries)
     self.assertEqual(325, r)