Beispiel #1
0
    def Program(self):
        functions = []
        if self.peek().type == "FUNCTION":
            functions = self.Functions()

        aslist = self.Assignments()
        return Program(assignments=aslist, functions=functions)
Beispiel #2
0
def convert_to_ast(node):
    program = Program()
    program.set_name(node.get_name())
    program.set_type(node.get_type())
    dclr_child = node.get_child_nodes()[0]
    dclr_list = DclrList()
    while True:
        if dclr_child is not None and dclr_child.get_name() == 'var':
            ident_name = dclr_child.get_child_nodes()[0]
            declaration = Declaration(ident_name.get_name())
            declaration.set_name(ident_name.get_name())
            declaration.set_type(symbol_table.get(ident_name.get_name()))
            dclr_list.add_declaration_to_list(declaration)
            AST.dot.edge(dclr_list.get_gv_name(), declaration.get_gv_name())
            length = len(dclr_child.get_child_nodes())
            dclr_child = dclr_child.get_child_nodes()[length - 1]
        else:
            break
    program.set_dclr_list(dclr_list)
    AST.dot.edge(program.get_gv_name(), dclr_list.get_gv_name())
    stmt_child = node.get_child_nodes()[2]
    stmt_list = generate_statement_list(stmt_child)
    if stmt_list.get_type_error():
        AST.dot.edge(program.get_gv_name(),
                     stmt_list.get_gv_name(),
                     color='red')
    else:
        AST.dot.edge(program.get_gv_name(), stmt_list.get_gv_name())
    program.set_stmt_list(stmt_list)
    return program
Beispiel #3
0
 def fromTextFile(self, path):
     with open(path, 'r') as f:
         appString = f.read()
         appString = appString.split(',')
         appString = [x for x in appString if x.strip()]
         appList = [Program(x) for x in appString]
         return self(apps=appList)
Beispiel #4
0
    def start(self, version):
        """Display the menu, wait for user input and then run the program

        Parameters:
            version - version number
        """
        # display menu and ask for input file path
        filePath = None
        cwdpath = ''
        while not filePath:
            cwdpath, filePath = self.displayMenu(version)

        # merge working directory and file path
        totalPath = os.path.join(cwdpath, filePath)

        # call program selector
        program = Program(cwdpath, totalPath)
        timer = Timer()
        timer.tic()
        try:
            program.run()
        except NoInputFileException as e:
            print e.message
        timer.toc()
        self.logger.info(timer.string('\n' 'iFlow run time'))

        # upon closing, ask input before ending. This to keep plot windows open.
        # self.askClose()

        return
Beispiel #5
0
def main():
    tokenizer = create_tokenizer("input.txt")
    open_output_file("output.txt")
    program = Program()
    program.parse()
    program.evaluate()
    close_output_file()
    tokenizer.destroy()
Beispiel #6
0
    def get_links(self, text):

        # download_links = []
        #
        # found = self.download_regex.findall(text)
        # #found2 = self.download2_regex.findall(text)
        #
        # info_links = self.get_info_links(self, text)
        #
        # #print(found2)
        #
        # #sys.exit()
        #
        # counter = 0
        #
        # for url in found:
        #
        #     # Configura o link de download
        #     url = url[13:-1]
        #
        #     #links.append(Program(url, self.get_version(self, text), downloads[counter]))
        #     download_links.append(Program(url, info_links[counter], None, 0, 0))
        #
        #     counter += 1
        #
        # counter = 0

        # for url in found2:
        #
        #     # Configura o link de download
        #     url = url[13:-1]
        #
        #     url = "http://www.reporting-download.com/download/?appid=" + url[42:]
        #
        #     #links.append(Program(url, self.get_version(self, text), downloads[counter]))
        #     download_links.append(Program(url, info_links[counter], None, 0, 0))
        #
        #     counter += 1

        links = []

        found = self.page_regex.findall(text)
        #_, last_week = self.get_downloads(self, "", text, False)

        counter = 0

        for url in found:

            l = self.create_links_list(self, url[:-2])  # Remove space and " chars

            if l is not None:
                l = html.unescape(l)

            links.append(Program(l, url[:-8], "", 0, None))#last_week[counter]))

            counter += 1

        return links
Beispiel #7
0
def main():
    app = Program(DB)

    choise = ''
    while True:
        print(UI)
        choise = input('Choise (1 - 6): ')
        if choise.isdigit():
            choise = int(choise)
            print('-' * WIDTH)

            # show
            if choise == 1:
                app.show()

            # add
            elif choise == 2:
                app.add()

            # change
            elif choise == 3:
                changeable_name = input("Name for change: ")
                app.change(name=changeable_name)

            # delete
            elif choise == 4:
                deletable_name = tuple  (input(\
                    "Name for delete: (1 or more names)\n"
                    "example: 'Name2 Name2 Name3 ... ' "\
                    ).replace(',',' ').split())
                print('-' * WIDTH)

                app.delete(*deletable_name)

            # search
            elif choise == 5:
                searchable_name = input("Search: ")
                app.search(searchable_name)

            # reset all
            elif choise == 6:
                sure_reset = input(
                    "Are you sure you want reset all contacts? (Y/n): ")
                if sure_reset.lower() == 'y':
                    app.reset_all()
                    print('Done.')
                elif sure_reset.lower() == 'n':
                    print('Reset  canceled')
                else:
                    print('Wrong choise!')

            # exit
            elif choise == 7:
                answer = input("Are you sure? ('Y/n')")
                if answer.lower() == 'y':
                    break
        else:
            print("Wrong choise!!!")
Beispiel #8
0
def main():
    print("dasm: Simple dcpu assembler\n")
    l = lark.Lark(grammar.grammar, start="start")

    parser = argparse.ArgumentParser(description='dcpu assembler')
    parser.add_argument("-i",
                        help="Assembly input file",
                        action="store",
                        metavar="<input file>",
                        type=str,
                        required=True,
                        dest="input_filename")
    parser.add_argument(
        "-o",
        help="Binary output file basename (without file extension)",
        metavar="<output file base name>",
        action="store",
        type=str,
        required=False,
        dest="output_filebase")

    args = parser.parse_args()

    try:
        fn = args.input_filename
        with open(fn) as f:
            lines = f.readlines()
    except:
        print(f"ERROR: Cannot open file {fn}")
        return 2

    contents = "".join(lines)

    t = l.parse(contents)
    # print(t.pretty())
    # print(t)

    n = dcpuTransformer().transform(t)

    program = Program(n.children)

    (path, name) = os.path.split(fn)  # remove path
    if args.output_filebase == None:
        outfn_noext = os.path.splitext(name)[0]  # remove extension
    else:
        outfn_noext = args.output_filebase

    program.write_as_bin(outfn_noext + ".bin")
    program.write_as_memfile(outfn_noext + ".mem")
    program.write_as_cfile(outfn_noext + ".c")
    program.write_as_listing(outfn_noext + ".list", lines)
    program.write_symbols(outfn_noext + ".symbols")
    program.write_as_simdata(outfn_noext + ".sim", lines)

    size = program.end_address - program.start_address + 1
    print(f"File '{name}' assembled\nOutput size: {size} words")
 def test_compute_minimum_area(self):
     from Drone import Drone
     drone_list = [
         Drone('test1', 30.0, 18.0, (3840, 2160), 12, 104),
         Drone('test2', 30.0, 18.0, (3840, 2160), 12, 104),
         Drone('test3', 30.0, 18.0, (3840, 2160), 6, 104)
     ]
     obtained = Program().compute_minimum_area(drone_list)
     self.assertEqual(obtained, (15.359299586316945, 8.639606017303281))
     self.assertEqual(obtained[0] * obtained[1], 132.6982971275077)
Beispiel #10
0
    def testLimitFiles(self):
        program = Program()
        with open("fileTest.txt", "r") as file:
            for line in file:
                program.open(line[0:-1])

        self.assertEqual(program.getRecentFiles(), [
            'peixe.txt', 'santanche.txt', 'osu.exe', 'cyberpunk.txt',
            'rambo.py', 'foo.txt', 'igor.py', 'sugoidesu.txt', 'bakamitai.mp3',
            'kurisu.txt'
        ])
Beispiel #11
0
def main():
    mode, length, width, file_path = load_data()

    program = Program(length, width, mode)
    program.read_file(file_path)

    if mode == 1:
        program.load_data()
        program.simulate1(length, width)
    elif mode == 2:
        program.simulate2(length, width)
Beispiel #12
0
 def compile(self, code):
     codeStream = InputStream(code)
     lexer = cargobotLexer(codeStream)
     stream = CommonTokenStream(lexer)
     parser = cargobotParser(stream)
     tree = parser.start()
     program = Program()
     listener = CargoBotListenerImpl(program)
     walker = ParseTreeWalker()
     walker.walk(listener, tree)
     return program
Beispiel #13
0
def part_one():

    # Setup
    program = Program(1024 * 1024)
    program.load_code("testInput.txt")

    # Run
    #program.load_input([1])
    program.run()
    print(program.is_done())

    output = program.get_output()
    print(output)
Beispiel #14
0
    def parse(self):
        '''Postcondition: Implements program -> function ID ( ) -> <block>'''
        self.match(self.lex.getNextTok(), TokenType.METHOD_TOK)
        self.match(self.lex.getNextTok(), TokenType.ID_TOK)
        self.match(self.lex.getNextTok(), TokenType.INPUTSTRT_TOK)
        self.match(self.lex.getNextTok(), TokenType.INPUTEND_TOK)

        program = Program(self.getBlock())

        self.match(self.lex.getNextTok(), TokenType.END_TOK)
        self.match(self.lex.getNextTok(), TokenType.EOS_TOK)

        return program
    def __init__(self, x, y, edge, start, goal, executable, auto):
        self.x, self.y = x, y
        self.edge = edge
        self.auto = auto
        self.goal = complex(*self[goal])

        self.bot_pos = self.start = complex(*self[start])
        self.bot_angle = complex(0, 1)
        self.window = Window(self.x, self.y)
        self.c_program = Program(executable)
        #self.c_program=IO()
        Thread(target=self.refresh, daemon=False).start()
        self.window.launch()
Beispiel #16
0
def generateCallTree(sourceFiles, options):
    firstFile = open(sourceFiles, "r") # Open first given file for reading
    callTree = []
    while True:
        try:
            line = firstFile.next().strip() # Read next line.
        except: # End of file
            break
        if isProgram(line): # Is this a line containing "program" statement?
            callTree.append(Program(firstFile, line))
        else: # Ordinary statement
            recognizeSourceLineAndUpdateTree(callTree, line)
    
    return callTree
Beispiel #17
0
 def parse(self):
     tok = self.get_next_token()
     self.match(tok, TokenType.MAIN_TOK)
     tok = self.get_next_token()
     self.match(tok, TokenType.LEFT_PAREN_TOK)
     tok = self.get_next_token()
     self.match(tok, TokenType.RIGHT_PAREN_TOK)
     tok = self.get_next_token()
     self.match(tok, TokenType.EOLN_TOK)
     block = self.get_statement_block()
     tok = self.get_next_token()
     if tok.Token.get_token_type() != TokenType.EOS_TOK:
         raise ParserException("invalid end of file")
     return Program(block)
Beispiel #18
0
 def parse(self):
     tok = self.lex.get_next_token()
     Parser.match(tok, TokenType.FUNCTION_TOK)
     functionName = self.get_id()
     tok = self.lex.get_next_token()
     Parser.match(tok, TokenType.LEFT_PAREN_TOK)
     tok = self.lex.get_next_token()
     Parser.match(tok, TokenType.RIGHT_PAREN_TOK)
     blk = self.get_block()
     tok = self.lex.get_next_token()
     Parser.match(tok, TokenType.END_TOK)
     tok = self.lex.get_next_token()
     if tok.get_tok_type() != TokenType.EOS_TOK:
         raise Exception("garbage at end of file")
     return Program(blk)
Beispiel #19
0
 def parse(self):
     tok = self.getNextToken()
     self.match(tok, TokenType.FUNCTION_TOK)
     functionName = self.getId()
     tok = self.getNextToken()
     self.match(tok, TokenType.LEFT_PAREN_TOK)
     tok = self.getNextToken()
     self.match(tok, TokenType.RIGHT_PAREN_TOK)
     blk = self.getBlock()
     tok = self.getNextToken()
     self.match(tok, TokenType.END_TOK)
     tok = self.getNextToken()
     if tok.getTokType() != TokenType.EOS_TOK:
         raise Exception("garbage at end of file")
     return Program(blk)
 def parse(self):
     token = self.lex.get_next_token()
     Parser.match(token, TokenType.FUNCTION_TOK)
     function_Name = self.get_id()
     token = self.lex.get_next_token()
     Parser.match(token, TokenType.LEFT_PAREN_TOK)
     token = self.lex.get_next_token()
     Parser.match(token, TokenType.RIGHT_PAREN_TOK)
     block = self.get_block()
     token = self.lex.get_next_token()
     Parser.match(token, TokenType.END_TOK)
     token = self.lex.get_next_token()
     if token.get_tok_type() != TokenType.EOS_TOK:
         raise Exception("File has Garbage")
         print("There is extra information on the julia")
     return Program(block)
Beispiel #21
0
    def test_run_invalid_input(self):
        program = Program()
        program.transport = mock.create_autospec(Transport)
        program.parser = mock.create_autospec(Parser)
        program.interpolator = mock.create_autospec(Interpolator)

        program.transport.read.return_value = 'input'
        program.parser.parse.side_effect = ValueError('Error')
        program.interpolator.interpolate.return_value = 'output'

        actual = program.run()

        program.transport.read.assert_called()
        program.parser.parse.assert_called()
        program.parser.parse.assert_called_with('input')
        program.interpolator.interpolate.assert_not_called()
        program.transport.write.assert_called_with('Invalid matrix!')
Beispiel #22
0
    def test_run(self):
        program = Program()
        program.transport = mock.create_autospec(Transport)
        program.parser = mock.create_autospec(Parser)
        program.interpolator = mock.create_autospec(Interpolator)

        program.transport.read.return_value = 'input'
        program.parser.parse.return_value = 'parsed_input'
        program.interpolator.interpolate.return_value = 'output'

        actual = program.run()

        program.transport.read.assert_called()
        program.parser.parse.assert_called()
        program.parser.parse.assert_called_with('input')
        program.interpolator.interpolate.assert_called_with('parsed_input')
        program.transport.write.assert_called_with('output')
Beispiel #23
0
    def __init__(self, action = None, learner = None):
        """Initialize new Learner. This can either be done from scratch or
        as a copy of a previous Learner, maintaining that Learner's action,
        which may be a pointer to a Team.

        Be wary of using deepcopy! The temptation to copy Learners via deepcopy
        was there, but this is a mistake since it will create copies of any Team
        pointed to by self.action. On the other hand, copying Programs via
        deepcopy is correct and a conveneient way to ensure that the new Program
        gets its own copy of the list of instructions.
        """

        # Set default value. This is so that setAction() will function properly
        # when checking the current self.action type. In general, the action
        # should always be set via setAction()
        self.action = 0

        # This counter keeps track of how many Teams hold a pointer to
        # this Learner, ie. how many Teams this Learner is a member of.
        self.num_referencing_teams = 0

        if learner is None:
            # Create Program associated with Learner
            self.program = Program()

            self.setAction(action)

            if action is None:
                print("WARNING - Learner::init - No Learner and no Action")
                # Assign Learner's action value
                self.setAction(randint(0, Learner.ATOMIC_ACTION_RANGE))

        else:
            # Make a copy of the other Learner's Program
            self.program = deepcopy(learner.program)

            # Copy the other Learner's action, whether it's atomic or not
            self.setAction(learner.action)

            # If new action is a Team pointer, update that Team's number of
            # referencing Learners
            if not self.isActionAtomic():
                self.action.incrementNumReferencingLearners()
Beispiel #24
0
def part_two():
	
	# Setup program
	program = list()
	for i in range(5):

		program.append(Program())
		program[i].load_code("thrusterProgram.txt")

	# Try all phase setting permutations
	phase_configuration_permutations = itertools.permutations([5, 6, 7, 8, 9])
	
	max_output = 0
	for phase_configuration in phase_configuration_permutations:

		# Start each program
		output = 0
		for i, phase in enumerate(phase_configuration):

			program[i].load_input([output, phase])
			program[i].run()
			output = program[i].get_output()

			#print("Output: %d from %d with phase %d" % (output, i, phase))

		# Run until done
		i = 0
		while not program[4].is_done():

			program[i].load_input([output])
			program[i].run()
			output = program[i].get_output()

			i = (i + 1) % 5

			#print([x.is_done() for x in program])
			#print("Output: %d from %d" % (output, i))

		if output > max_output:
			max_output = output

	print("Max output is: %d" % max_output)
Beispiel #25
0
def load_data():
    wb = load_workbook(CBOutreachFile)
    ws = wb['Outreach Events']

    findLastRowInput(ws)

    for i in range(firstRowInput, lastRowInput + 1):
        global data
        row = str(i)
        initiative = ws[cInitiative + row].value
        strategy = ws[cStrategy + row].value
        activity = ws[cActivity + row].value
        program = ws[cProgram + row].value

        if program is None:
            continue
        else:
            program = program.strip()

        date = ws[cDate + row].value  # type: datetime

        numPeople = ws[cNumPeople + row].value
        numPeopleUnique = ws[cNumPeopleUnique + row].value

        if initiative not in data:
            data[initiative] = {}
        if strategy not in data[initiative]:
            data[initiative][strategy] = {}
        if activity not in data[initiative][strategy]:
            data[initiative][strategy][activity] = {}
        if program not in data[initiative][strategy][activity]:
            data[initiative][strategy][activity][program] = Program(
                initiative, strategy, activity, program)

        programInstance = data[initiative][strategy][activity][
            program]  # type: Program
        programInstance.addEvent(date, numPeople, numPeopleUnique)

    getLastMonthAndYearWithEntries()
Beispiel #26
0
    def get_links(self, text):

        links = []

        found = self.page_regex.findall(text)
        _, last_week = self.get_downloads(self, "", text, False)

        counter = 0

        for url in found:

            l = self.create_links_list(self, url)

            if l is not None:

                l = html.unescape(l)

            links.append(Program(l, url[:-8], "", 0, last_week[counter]))

            counter += 1

        return links
Beispiel #27
0
def part_one():

	# Setup program
	program = Program()
	program.load_code("thrusterProgram.txt")

	# Try all phase setting permutations
	phase_configuration_permutations = itertools.permutations([0, 1, 2, 3, 4])
	
	max_output = 0
	for phase_configuration in phase_configuration_permutations:
		
		output = 0
		for phase in phase_configuration:	

			program.load_input([output, phase])
			program.reset()
			program.run()
			output = program.get_output()

		if output > max_output:
			max_output = output

	print("Highest signal to thrusters is: %d" % max_output)
Beispiel #28
0
def get_program(username):
    con = sql.connect('classes2.db')
    cur = con.cursor()
    cur.execute("SELECT major FROM Users WHERE username = ?", username)
    user = cur.fetchone()
    #have the user, now build their program
    courses = loadCourses.load()

    if user == "Computer Science":
        CS = Program("Computer Science")
        csBuild = programBuilder(2017, 0, 3, CS)
        return csBuild.planCourses()

    elif user == "Information Systems - Standard":
        IS0 = Program("Information Systems - Standard")
        is0Build = programBuilder(2017, 0, 3, IS0)
        return is0Build.planCourses()

    elif user == "Information Systems - Business Analysis/Systems Analysis":
        IS1 = Program(
            "Information Systems - Business Analysis/Systems Analysis")
        is1Build = programBuilder(2017, 0, 3, IS1)
        return is1Build.planCourses()

    elif user == "Information Systems - Business Intelligence":
        IS2 = Program("Information Systems - Business Intelligence")
        is2Build = programBuilder(2017, 0, 3, IS2)
        return is2Build.planCourses()

    elif user == "Information Systems - DB Administration":
        IS3 = Program("Information Systems - DB Administration")
        is3Build = programBuilder(2017, 0, 3, IS3)
        return is3Build.planCourses()

    elif user == "Information Systems - IT Enterprise Management":
        IS4 = Program("Information Systems - IT Enterprise Management")
        is4Build = programBuilder(2017, 0, 3, IS4)
        return is4Build.planCourses()
Beispiel #29
0
def part_one_and_two():

    program = Program()
    program.load_code("input.txt")
    program.run()
Beispiel #30
0
    children_string = match.group(3)

    # omit programs without children - they can't be root
    if children_string is not None:
        children_of_current_program = children_string.split(", ")
        possible_roots_names.append(name)

        for child in children_of_current_program:
            parent_of[child] = name
    else:
        children_of_current_program = []

    children_of[name] = children_of_current_program

    program_with_name[name] = Program(name, weight, [])

root_name = None

for program in possible_roots_names:
    if program not in parent_of:
        root_name = program
        break

print("Root: ")
print(root_name)

# build tree


def build(node_name):