Example #1
0
    def generateXpcomCppHeader(self, config, filename, cache_dir):
        prefixname = filename[:-4]
        targetFilePath  = mozpath.join(config.topobjdir, 'dist/include', prefixname  + ".h")
        if not self.targetNeedBuild(targetFilePath):
            return

        sourceFilePath = mozpath.join(config.topobjdir, 'dist/idl', filename)

        includePaths = [mozpath.join(config.topobjdir, 'dist/idl'),
            mozpath.join(self.libxul_sdk, 'idl')]
        import xpidl
        import header
        try:
            filename = mozpath.join('../../../dist/idl', filename)
            p = xpidl.IDLParser(outputdir=cache_dir)
            idl = p.parse(open(sourceFilePath).read(), filename=filename)
            idl.resolve(includePaths, p)
            outfd = open(targetFilePath, 'w')
            header.print_header(idl, outfd, filename)
            outfd.close()
            deps = set()
            self.updateIdlDeps(config, idl.deps, deps)
            self.addDependencies(targetFilePath, deps)
            self.addDependencies(targetFilePath, [targetFilePath])
            print('%s -> %s' % (sourceFilePath, targetFilePath))
        except Exception as e:
            print("Failed to generate IDL from %s to %s!" % (sourceFilePath, targetFilePath));
            print(e)
Example #2
0
def main():
    log('server.main', '+' * 20)
    log('server.main', 'Server started')

    print_header()

    datactl.makefile()

    printing.printf('Waiting for connections',
                    style=printing.STATUS,
                    log=True,
                    logtag='server.main')

    Thread(target=handleinput).start()

    socketctl.init()
    Thread(target=socketctl.connect).start()

    while True:
        try:
            datactl.update()
        except KeyboardInterrupt:
            # Make sure everything made it into the data file
            datactl.update()

            socketctl.close()

            log('server.main', 'Server stopped')
            log('server.main', '-' * 20)

            # Quit everything (closes all the many threads)
            osexit(1)
Example #3
0
def main():
    print_header()

    l = get_data()
    answers = recurse(iter(l))
    print("The answer to part 1 is: {} and to part 2 is : {}".format(
        answers[0], answers[1]))
Example #4
0
def main():
    print_header()

    # Input is: 452 players; last marble is worth 71250 points
    print("Answer to part 1 is: {}".format(marbles(452, 71250)))

    # Input is: 452 players; last marble is worth 7125000 points
    print("Answer to part 2 is: {}".format(marbles(452, 7125000)))
Example #5
0
def main():
    print_header()

    input_lines = open('input').read().splitlines()

    input_lines.sort()

    solution(input_lines)
Example #6
0
def main():
    print_header()
    input = open('input').read()
    p1 = polymer(input)
    print("The answer to the first puzzle is: {}".format(p1[1]))

    p2 = biggest_reaction(p1[0])
    print("The answer to the second part of the puzzle is: {}".format(p2))
Example #7
0
def main():
    header.print_header()
    location = get_location()
    html = get_html_from_web(location)
    report = get_weather_from_html(html)
    print('The temp in {} is {} and {}'.format(
        report.loc,
        report.temp,
        report.cond
    ))
Example #8
0
def main():
    print_header()

    fabric = {}
    input_lines = open('input').read().splitlines()

    p1 = compute_overlap(fabric, input_lines)
    print("The number of overlapped squares is: {}".format(p1))

    p2 = get_not_overlapping_id(fabric, input_lines)
    print("The ID of the non-overlapping cut is: {}".format(p2))
Example #9
0
def main():
    print_header()

    # Your puzzle input is 7403.

    grid = [[0 for x in range(301)] for y in range(301)]

    for y in range(1, 301):
        for x in range(1, 301):
            grid[x][y] = compute_power(7403, x, y)

    compute_puzzle(grid)
Example #10
0
    def testOverloadedVirtual(self):
        i = self.p.parse("""[uuid(abc)] interface foo {
attribute long bar;
void getBar();
};""", filename='f')
        self.assertTrue(isinstance(i, xpidl.IDL))
        class FdMock:
            def write(self, s):
                pass
        try:
            header.print_header(i, FdMock(), filename='f')
        except Exception as e:
            self.assertEqual(e.args[0], "Unexpected overloaded virtual method GetBar in interface foo")
Example #11
0
def main():
    print_header()

    OPERATIONS = [
        addr, addi, mulr, muli, banr, bani, borr, bori, setr, seti, gtir, gtri,
        gtrr, eqir, eqri, eqrr
    ]

    # Before, Op, After
    sol1, codes = solve1(OPERATIONS)
    print('Solution to part 1 is: {}'.format(sol1))

    print('Solution to part 2 is: {}'.format(solve2(codes)))
Example #12
0
def process(input_dir, cache_dir, header_dir, xpt_dir, deps_dir, module, stems):
    p = IDLParser(outputdir=cache_dir)

    xpts = {}
    deps = set()

    # Write out dependencies for Python modules we import. If this list isn't
    # up to date, we will not re-process XPIDL files if the processor changes.
    for imported in ('header', 'typelib', 'xpidl', 'xpt'):
        path = sys.modules[imported].__file__

        if path.endswith('.pyc'):
            path = path[0:-1]

        deps.add(path)

    for stem in stems:
        path = os.path.join(input_dir, '%s.idl' % stem)
        idl_data = open(path).read()

        idl = p.parse(idl_data, filename=path)
        idl.resolve([input_dir], p)

        header_path = os.path.join(header_dir, '%s.h' % stem)
        deps_path = os.path.join(deps_dir, '%s.pp' % stem)

        xpt = BytesIO()
        write_typelib(idl, xpt, path)
        xpt.seek(0)
        xpts[stem] = xpt

        deps |= set(dep.replace('\\', '/') for dep in idl.deps)

        with FileAvoidWrite(header_path) as fh:
            print_header(idl, fh, path)

    # TODO use FileAvoidWrite once it supports binary mode.
    xpt_path = os.path.join(xpt_dir, '%s.xpt' % module)
    xpt_link(xpts.values()).write(xpt_path)

    deps_path = os.path.join(deps_dir, '%s.pp' % module)
    with FileAvoidWrite(deps_path) as fh:
        # Need output to be consistent to avoid rewrites.
        s_deps = sorted(deps)
        fh.write('%s: %s\n' % (xpt_path, ' '.join(s_deps)))
        for dep in s_deps:
            fh.write('%s:\n' % dep)
Example #13
0
def main():
    print_header()

    datactl.makefile()

    printing.printf('Waiting for connections', style=printing.STATUS)

    Thread(target=handleinput).start()

    socketctl.init()
    Thread(target=socketctl.connect).start()

    while True:
        try:
            datactl.update()
        except KeyboardInterrupt:
            datactl.update()
            socketctl.close()
            osexit(1)
Example #14
0
def process(input_dir, cache_dir, header_dir, xpt_dir, deps_dir, module,
            stems):
    p = IDLParser(outputdir=cache_dir)

    xpts = {}
    mk = Makefile()
    rule = mk.create_rule()

    # Write out dependencies for Python modules we import. If this list isn't
    # up to date, we will not re-process XPIDL files if the processor changes.
    rule.add_dependencies(iter_modules_in_path(topsrcdir))

    for stem in stems:
        path = os.path.join(input_dir, '%s.idl' % stem)
        idl_data = open(path).read()

        idl = p.parse(idl_data, filename=path)
        idl.resolve([input_dir], p)

        header_path = os.path.join(header_dir, '%s.h' % stem)
        deps_path = os.path.join(deps_dir, '%s.pp' % stem)

        xpt = BytesIO()
        write_typelib(idl, xpt, path)
        xpt.seek(0)
        xpts[stem] = xpt

        rule.add_dependencies(idl.deps)

        with FileAvoidWrite(header_path) as fh:
            print_header(idl, fh, path)

    # TODO use FileAvoidWrite once it supports binary mode.
    xpt_path = os.path.join(xpt_dir, '%s.xpt' % module)
    xpt_link(xpts.values()).write(xpt_path)

    rule.add_targets([xpt_path])
    deps_path = os.path.join(deps_dir, '%s.pp' % module)
    with FileAvoidWrite(deps_path) as fh:
        mk.dump(fh)
Example #15
0
def main():
    regular_map = networkx.Graph()
    print_header()

    with open('input') as f:
        directions = f.readline()[1:-1]

    pos = {0}
    stack = []
    start, end = {0}, set()

    for step in directions:
        # 4 cases here:

        # Pipe means split in groups
        if step == "|":
            end.update(pos)
            pos = start

        # General direction
        elif step in "NSWE":
            direction = {'N': 1, 'S': -1, 'W': -1j, 'E': 1j}[step]
            regular_map.add_edges_from((p, p + direction) for p in pos)
            pos = {p + direction for p in pos}

        # Group starts in case of (
        elif step == '(':
            stack.append((start, end))
            start, end = pos, set()

        # Group ends in case of )
        elif step == ')':
            pos.update(end)
            start, end = stack.pop()

    lengths = networkx.algorithms.shortest_path_length(regular_map, 0)

    print('Answer to part 1 is: {}'.format(max(lengths.values())))
    print('Answer to part2 is: {}'.format(sum(1 for values in lengths.values() if values >= 1000)))
Example #16
0
def process(input_dir, inc_paths, cache_dir, header_dir, xpt_dir, deps_dir, module, stems):
    p = IDLParser(outputdir=cache_dir)

    xpts = {}
    mk = Makefile()
    rule = mk.create_rule()

    # Write out dependencies for Python modules we import. If this list isn't
    # up to date, we will not re-process XPIDL files if the processor changes.
    rule.add_dependencies(iter_modules_in_path(topsrcdir))

    for stem in stems:
        path = os.path.join(input_dir, "%s.idl" % stem)
        idl_data = open(path).read()

        idl = p.parse(idl_data, filename=path)
        idl.resolve([input_dir] + inc_paths, p)

        header_path = os.path.join(header_dir, "%s.h" % stem)
        deps_path = os.path.join(deps_dir, "%s.pp" % stem)

        xpt = BytesIO()
        write_typelib(idl, xpt, path)
        xpt.seek(0)
        xpts[stem] = xpt

        rule.add_dependencies(idl.deps)

        with FileAvoidWrite(header_path) as fh:
            print_header(idl, fh, path)

    # TODO use FileAvoidWrite once it supports binary mode.
    xpt_path = os.path.join(xpt_dir, "%s.xpt" % module)
    xpt_link(xpts.values()).write(xpt_path)

    rule.add_targets([xpt_path])
    deps_path = os.path.join(deps_dir, "%s.pp" % module)
    with FileAvoidWrite(deps_path) as fh:
        mk.dump(fh)
Example #17
0
    def testOverloadedVirtual(self):
        i = self.p.parse("""
        [scriptable, uuid(00000000-0000-0000-0000-000000000000)] interface nsISupports {};
        [uuid(abc)] interface foo : nsISupports {
          attribute long bar;
          void getBar();
        };""",
                         filename='f')
        self.assertTrue(isinstance(i, xpidl.IDL))
        i.resolve([], self.p, {})

        class FdMock:
            def write(self, s):
                pass

        try:
            header.print_header(i, FdMock(), filename='f')
            self.assertTrue(False, "Header printing failed to fail")
        except Exception as e:
            self.assertEqual(
                e.args[0],
                "Unexpected overloaded virtual method GetBar in interface foo")
Example #18
0
def main():
    print_header()

    with open('input') as f:
        lines = f.readlines()

        grid = [['.' for x in range(len(lines[0]) - 1)]
                for y in range(len(lines))]

        for x in range(len(lines[0]) - 1):
            for y in range(len(lines)):
                grid[x][y] = lines[x][y]

    def check(grid, x, y, dx, dy, string):
        x1 = x + dx
        y1 = y + dy

        if 0 <= x1 <= 49 and 0 <= y1 <= 49:
            if grid[x1][y1] == string:
                return 1
        return 0

    def production(minutes, grid):
        prevs = []

        for i in range(1, minutes + 1):
            new_grid = [['.' for x in range(len(lines[0]) - 1)]
                        for y in range(len(lines))]
            for x in range(len(lines[0]) - 1):
                for y in range(len(lines)):

                    # Open
                    if grid[x][y] == '.':
                        number = 0
                        for dx in range(-1, 2):
                            for dy in range(-1, 2):
                                if dx == 0 and dy == 0:
                                    continue
                                number += check(grid, x, y, dx, dy, '|')
                        if number >= 3:
                            new_grid[x][y] = '|'
                        else:
                            new_grid[x][y] = '.'

                    # Tree
                    if grid[x][y] == '|':
                        number = 0
                        for dx in range(-1, 2):
                            for dy in range(-1, 2):
                                if dx == 0 and dy == 0:
                                    continue
                                number += check(grid, x, y, dx, dy, '#')
                        if number >= 3:
                            new_grid[x][y] = '#'
                        else:
                            new_grid[x][y] = '|'

                    # Lumber
                    if grid[x][y] == '#':
                        number_lumber = 0
                        number_trees = 0
                        for dx in range(-1, 2):
                            for dy in range(-1, 2):
                                if dx == 0 and dy == 0:
                                    continue
                                number_lumber += check(grid, x, y, dx, dy, '#')
                                number_trees += check(grid, x, y, dx, dy, '|')
                        if number_lumber >= 1 and number_trees >= 1:
                            new_grid[x][y] = '#'
                        else:
                            new_grid[x][y] = '.'
            grid = new_grid

            prev = '\n'.join(''.join(row) for row in grid)

            # Check for patterns return if found
            if prev in prevs:
                rep = prevs.index(prev)
                print('Found Pattern: {} is a repeat of: {}'.format(rep, i))
                period = i - (1 + rep)
                while (rep + 1) % period != minutes % period:
                    rep += 1
                number_lumber = prevs[rep].count('#')
                number_trees = prevs[rep].count('|')
                return number_lumber * number_trees

            prevs.append(prev)

        number_lumber = 0
        number_trees = 0
        for x in range(len(lines[0]) - 1):
            number_lumber += grid[x].count("#")
            number_trees += grid[x].count('|')

        return number_lumber * number_trees

    print("Answer to part 1 is: " + str(production(10, grid)))
    print("Answer to second part is: " + str(production(1000000000, grid)))
Example #19
0
def main():
    print_header()
    print("Answer to part 1 is: {}".format(solve(INPUT, True)))
    print("Answer to part 2 is: {}".format(solve(INPUT)))
Example #20
0
def main():
    print_header()
    data = get_data()
    print("Answer to part 1 is: {}".format(solve(data[0], data[1], True)))
    print("Answer to part 2 is: {}".format(solve(data[0], data[1])))
Example #21
0
def main():
    print_header()

    compute_checksum()

    common_box_id()
Example #22
0
def main():
    print_header()

    compute_frequency()

    compute_duplicate_frequency()
Example #23
0
def main():
    print_header()
    sys.setrecursionlimit(3000)
    clay = collections.defaultdict(bool)

    with open('input') as f:
        lines = f.readlines()
        for line in lines:
            line = line.strip('\n')
            a, depth = line.split(',')
            if a[0] == 'x':
                x = int(a.split('=')[1])
                y1 = int(depth.split('..')[0].split('=')[1])
                y2 = int(depth.split('..')[1])

                for y in range(y1, y2 + 1):
                    clay[(x, y)] = True

            else:
                y = int(a.split('=')[1])
                x1 = int(depth.split('..')[0].split('=')[1])
                x2 = int(depth.split('..')[1])

                for x in range(x1, x2 + 1):
                    clay[(x, y)] = True

    ymax = max(clay, key=lambda x: x[1])[1]

    def flow(clay, bottom):
        still, moving = set(), set()

        def traverse(p):
            if p in moving:
                return

            moving.add(p)

            x, y = p

            if y >= bottom:
                return False

            below = (x, y + 1)

            if below not in clay:
                traverse(below)

            if below not in clay and below not in still:
                return False

            left = (x - 1, y)
            right = (x + 1, y)

            left_finite = left in clay or traverse(left)
            right_finite = right in clay or traverse(right)

            if left_finite and right_finite:
                still.add(p)
                while left in moving:
                    still.add(left)
                    left = (left[0] - 1, y)
                while right in moving:
                    still.add(right)
                    right = (right[0] + 1, y)

            return left_finite or right_finite

        traverse((500, 0))
        return still, moving

    still, moving = flow(clay, ymax)
    print('Part 1: ' + str(len(moving)))
    print('Part 2: ' + str(len(still)))
Example #24
0
def main():
    print_header()

    get_word(get_data())
Example #25
0
import networkx

from header import print_header

print_header()

target_x = 13
target_y = 726

depth = 3066


def geoindex_known(geoindex):
    # A region's erosion level is its geologic index plus the cave system's depth, all modulo 20183.
    e = (geoindex + depth) % 20183
    return e, e % 3


def generate_cave(target_x, target_y):
    cave = {}
    sum = 0
    for y in range(target_y + 1):
        for x in range(target_x + 1):
            if (x == 0 and y == 0) or (x == target_x and y == target_y):
                erosion, type = geoindex_known(0)

            elif y == 0:
                erosion, type = geoindex_known(x * 16807)

            elif x == 0:
                erosion, type = geoindex_known(y * 48271)
Example #26
0
def main():
    print_header()

    print("Answer to part one: {}".format(assembly_steps(1)))

    print("Answer to part two: {}".format(assembly_steps(5)))