Ejemplo n.º 1
0
def second_pass(path, symbol_table):
    p = Parser(path)
    code = Code()
    ram_address = 16
    hack = []
    while(p.hasMoreCommands()):
        command_type = p.commandType()
        if (command_type == CommandType.L):
            p.advance()
            continue
        elif (command_type == CommandType.C):
            dest = code.dest(p.dest())
            comp = code.comp(p.comp())
            jump = code.jump(p.jump())
            command = int("111" + comp + dest + jump, 2)
        else:  # command_type == CommandType.A
            symbol = p.symbol()
            if symbol.isdigit():
                address = int(symbol)
            else:
                if not symbol_table.contains(symbol):
                    symbol_table.add_entry(symbol, ram_address)
                    ram_address += 1
                address = symbol_table.get_address(symbol)
            command = address
        command = format(command, '016b')
        hack.append(command)
        p.advance()
    return hack
Ejemplo n.º 2
0
    def __init__(self, args):
        self.args = args
        
        self.cfg = Config()
        self.cfg.load(args.config)

        self.code = Code()
Ejemplo n.º 3
0
    def __init__(self, row):
        self.row = row
        indent = False

        self.event_name = row[0]
        self.assignID = row[1]
        self.srcCodeID = int(row[2])

        self.srcCodeText = base64.b64decode(row[3])
        self.sourceCodeObj = Code(self.srcCodeText,
                                  indent=indent,
                                  codeID=self.srcCodeID)

        self.sourceTime = row[4]
        self.sourceErrors = row[5]

        targetData = row[6]
        self.targetCodeID = None
        self.targetCodeObj = None

        if targetData != None:
            self.targetCodeID, self.targetTime, targetContents = targetData.split(
                ',')
            self.targetCodeID = int(self.targetCodeID)
            self.targetCodeText = base64.b64decode(targetContents)
            self.targetCodeObj = Code(self.targetCodeText,
                                      indent=indent,
                                      codeID=self.targetCodeID)
Ejemplo n.º 4
0
    def testComplexNamingAndScopesAndNamedArguments(self):
        '''This is a complex test that tests a lot of scope handling issues.
        The getWorkingCopy() method of a Code object should return a copy of the programcode
        in which all names are replaced by generic terms. "name000x", "const000x" and "meth000x".
        
        If we create a method with def name(): we create a new scope. within this scope some names 
        can be declared. If we call this method, names used within the parentheses should be renamed
        according to the current scope. However if we use named argument, as in add(nrtwo="1") the renaming
        of "nrtwo" should occur in the scope of the called method.    
        '''
        
        A = Code('''
def add(nrone=1, nrtwo=2):
    nrtwo = float(nrtwo)
    nrone = float(nrone)
    return nrone + nrtwo
    
print add(2,3) + add (nrtwo = "1")        
''')

        old_stdout = sys.stdout
        redirected_output = sys.stdout = StringIO()
        exec(A.getWorkingCopy())
        sys.stdout = old_stdout
        assert float(redirected_output.getvalue() ) == 7
Ejemplo n.º 5
0
    def __init__(self, asm):
        f = open(asm, 'r')
        lines = f.readlines()
        f.close()

        self.parser = Parser()
        self.symtaber = SymbolTable()
        self.coder = Code()

        self.asm_name = asm
        self.hack_name = asm.split('.')[0] + '.my.hack'

        for i in range(len(lines)):
            # 删除行首空白符
            line = lines[i].strip()
            print "line: ", line

            # 删除注释
            slash_idx = len(line)
            if '//' in line:
                slash_idx = line.index('//')
            line = line[:slash_idx]

            # 删除末尾空白符
            line = line.rstrip()
            if line == '':
                continue

            # 命令是否合法
            if not self.valid(line, self.parser, self.symtaber, self.coder):
                raise Exception("invalid instruction in line {0}".format(i +
                                                                         1))

            self.parser.coms.append(line)
        self.parser.len_coms = len(self.parser.coms)
Ejemplo n.º 6
0
 def __init__(self, file):
     self.__infilename = file
     if file.endswith('.asm'):
         self.__outfilename = file[:-3] + 'hack'
     else:
         self.__outfilename = file + '.hack'
     self.__code = Code()
     self.__parser = Parser(file)
Ejemplo n.º 7
0
 def test_get_max_in_list(self):
     list1 = [1, 24, 3, 12, 3, 4, 23]
     list2 = [1, 4, 3]
     list3 = list()
     code = Code();
     assert 24 == code.get_max_in_list(list1)
     assert 4 == code.get_max_in_list(list2)
     assert 0 == code.get_max_in_list(list3)
Ejemplo n.º 8
0
 def setUp(self):
     self.code = Code()
     self.code_cpp = self.code.from_file(
         "Algorithms/BinarySearch/codes/c++.html")
     self.code_pseudocode = self.code.from_file(
         "Algorithms/BinarySearch/codes/pseudocode.html")
     self.code_python = self.code.from_file(
         "Algorithms/BinarySearch/codes/python.html")
Ejemplo n.º 9
0
 def test_get_list_size(self):
     list1 = [1, 4, 3, 2, 3, 4]
     list2 = [1, 4, 3]
     list3 = list()
     code = Code()
     assert 6 == code.get_list_size(list1)
     assert 3 == code.get_list_size(list2)
     assert 0 == code.get_list_size(list3)
Ejemplo n.º 10
0
    def handle_file(self, file_name):
        """ Handle a file
            :param file_name: The filename to process
            :return: None
        """
        dir_name = os.path.dirname(file_name.path)
        basename = os.path.basename(file_name.path)
        path = CC_BASE + self.ROOT_PATH + "/" + os.path.abspath(dir_name)
        path = path.replace('//', '/')

        if not os.path.exists(path):
            os.makedirs(path)

        open_file = open(os.path.join(path, basename + HTML.FILE_EXT), "w")

        source_data = File.read_file(self.script_base + file_name.path)

        last_pos = dir_name.rfind("/")

        html_link = HTML.get_link(CC_BASE, "root", "") + \
            HTML.get_link(path, dir_name[last_pos + 1:], basename)

        open_file.write(HTML.get_header(html_link, HTML.SRC_PREFIX))

        processing_line = 1
        previous_line_is_continued = False

        for line in source_data.splitlines():
            line = line.decode("utf-8")
            line = line.replace("&", "&")
            line = line.replace(">", ">")
            line = line.replace("<", "&lt;")
            line = line.replace('"', '&quot;')

            line_covered = processing_line in file_name.lines and \
                Code.line_is_code(line) or \
                processing_line > 1 and \
                previous_line_is_continued

            if line_covered:
                span_class = "covered"
            elif Code.line_is_code(line):
                span_class = "not_covered"
            else:
                span_class = "not_code"

            line_to_save = HTML.get_html(
                HTML.LINE_SOURCE) % (processing_line, span_class, line)

            open_file.write(line_to_save)

            previous_line_is_continued = True if line.endswith("\\") else False
            processing_line = processing_line + 1

        open_file.write(
            HTML.get_html(HTML.SRC_SUFFIX) + HTML.get_footer(
                file_name.total_lines, file_name.covered_lines, False))
Ejemplo n.º 11
0
    def _survey_end(self, measurements, analysis):
        Code._survey_end(self, measurements, analysis)
        measurements["file.pbBinLines"] = sum(self.counts['PbBinLines'])

        if self.createOutFiles:
            for fileObj in self._outFiles.itervalues():
                try:
                    fileObj.close()
                except Exception:
                    pass
Ejemplo n.º 12
0
 def test_get_occurrence(self):
     string1 = "abababababab"
     string2 = "oublié aba trada"
     string3 = "I love chocolat"
     code = Code()
     assert 6 == code.get_occurrence("a", string1)
     assert 1 == code.get_occurrence("oublié", string2)
     assert 0 == code.get_occurrence("latlat", string3)
     assert 2 == code.get_occurrence("foo", "foobar foo")
     assert 3 == code.get_occurrence("foo", "foofoo foobar")
Ejemplo n.º 13
0
 def test_sort_list(self):
     list1 = [1, 24, 3, 12, 3, 4, 23]
     list2 = [1, 4, 3, 2]
     list3 = [1, -4, 3, 12]
     sorted_list1 = [1, 3, 3, 4, 12, 23, 24]
     sorted_list2 = [1, 2, 3, 4]
     sorted_list3 = [-4, 1, 3, 12]
     code = Code()
     assert sorted_list1 == code.sort_list(list1);
     assert sorted_list2 == code.sort_list(list2);
     assert sorted_list3 == code.sort_list(list3);
Ejemplo n.º 14
0
    def _survey_end(self, measurements, analysis):
        Code._survey_end(self, measurements, analysis)
        measurements["file.pbBinLines"] = sum(self.counts['PbBinLines'])
        measurements["file.pbGenLines"] = sum(self.counts['PbGenLines'])

        if self.createOutFiles:
            for fileObj in self._outFiles.itervalues():
                try:
                    fileObj.close()
                except Exception:
                    pass
Ejemplo n.º 15
0
 def test_delete_uneven(self):
     list1 = [1, 24, 3, 12, 3, 4, 23]
     list2 = [1, -4, 3, 2]
     list3 = [1, 3, 3, 17]
     result1 = [24, 12, 4]
     result2 = [-4, 2]
     result3 = []
     code = Code()
     assert result1 == code.delete_uneven(list1);
     assert result2 == code.delete_uneven(list2);
     assert result3 == code.delete_uneven(list3);
def save_doc_as_file(code=Code()):
    '''Crée/Enregistre le document sous la forme d'un fichier
    data/uid. Return the file name.
    '''
    uid = code.uid
    if uid is None:
        code = Code()
    with open(f'data/{uid}', 'w') as fd:
        code = str(code)
        print(code)
        fd.write(code)
    return uid
Ejemplo n.º 17
0
    def test_get_average(self):
        code = Code()
        marklist1 = [Mark(mark=18), Mark(mark=12), Mark(mark=14), Mark(mark=16)]
        student1 = Student()
        student1.marklist = marklist1

        marklist2 = [Mark(mark=18), Mark(mark=12), Mark(mark=0)]
        student2 = Student()
        student2.marklist = marklist2

        assert 15 == code.get_average(student1)
        assert 10 == code.get_average(student2)
Ejemplo n.º 18
0
 def secondStep(self):
     p = Parser(self.file)
     outFile = open(self.outputFile, 'w')
     code = Code()
     while p.hasMoreCommands():
         p.advance()
         if p.commandType() == p.A_COMMAND:
             outFile.write(code.A(self.getAddr(p.symbol())) + '\n')
         elif p.commandType() == p.C_COMMAND:
             outFile.write(code.C(p.comp(), p.dest(), p.jump()) + '\n')
         elif p.commandType() == p.L_COMMAND:
             pass
     outFile.close()
Ejemplo n.º 19
0
 def __init__(self, file_name):
     self._parser = Parser()  # Parser object
     self._code = Code()  # Code object
     self._symbol_table = SymbolTable()  # SymbolTable object
     asm_file = open(file_name, 'r')  # open the asm file
     self._instructions = asm_file.read().split(
         '\n')  # initialize a list with the assembly instructions
     asm_file.close()  # close the asm file
     self._hack_file_name = file_name.split(
         '.asm')[0] + '.hack'  # name of the output hack file
     self._machine_code = [
     ]  # initialize a list for the output hack instructions
     self._first_pass()
     self._second_pass()
Ejemplo n.º 20
0
    def SecondPass(self):

        secondPassParser = Parser(self.readfile)
        outfile = open(self.writefile, 'w+')
        code = Code()

        while secondPassParser.hasMoreCommands():

            secondPassParser.advance()
            if secondPassParser.commandType() == 'A_COMMAND':

                if secondPassParser.symbol().isdigit():

                    writeline = '0' + ('{0:b}'.format(
                        int(secondPassParser.symbol())).zfill(15))
                    outfile.write(writeline + '\n')
                elif self.symboltable.contains(secondPassParser.symbol(
                )):  # if symbol is in table write binary to file
                    writeline = '0' + '{0:b}'.format(
                        self.symboltable.GetAddress(secondPassParser.symbol())
                    ).zfill(
                        15
                    )  #makes writeline with 0 (a instruction)+15 bit address of symbol
                    outfile.write(writeline + '\n')

                else:  #if symbol is not in table add to table then write to file in binary

                    self.symboltable.addEntry(secondPassParser.symbol(),
                                              self.NewSymbolAdd)
                    self.NewSymbolAdd += 1
                    writeline2 = '0' + '{0:b}'.format(
                        self.symboltable.GetAddress(
                            secondPassParser.symbol())).zfill(15)
                    outfile.write(writeline2 + '\n')

            if secondPassParser.commandType() == 'C_COMMAND':
                writelineC = '111' + code.comp_conv(
                    secondPassParser.comp()) + code.dest_conv(
                        secondPassParser.dest()) + code.jump_conv(
                            secondPassParser.jump())
                outfile.write(writelineC + '\n')
            '''
            if secondPassParser.commandType()=='L_COMMAND':
                 if self.symboltable.contains(secondPassParser.symbol()):
                    writeline=writeline='0'+('{0:b}'.format(self.symboltable.GetAddress(secondPassParser.symbol())).zfill(15))
                else:
                    continue
                 '''

        outfile.close()
Ejemplo n.º 21
0
def test_Bebop():
    b = Bebop()

    assert isinstance(b, Bebop)
    assert Bebop.__base__ == object

    with pytest.raises(KeyError):
        b.use(Bebop)

    b = Bebop()

    code = Code((b.opcode['swap_top2'], ))
    core = Core(code, stack=[Block.new_integer(19), Block.new_integer(21)])

    assert core.all_right
    assert core.stack[-1].data == 21

    ret, = core

    assert core.all_right
    assert core.stack[-1].data == 19

    assert isinstance(ret, Block)
    assert ret.type == Block.type_integer
    assert ret.data == 19

    core = Core(code)

    ret, = core

    assert core.all_right is False
    assert core.error_msg == 'swap_top2() with less than two'

    assert isinstance(ret, Block)
    assert ret.type == Block.type_error
    assert ret.data == 'swap_top2() with less than two'

    code = Code((b.opcode['get_answer'], ))
    core = Core(code)

    core.register['answer'] = Block.new_integer(37)

    ret, = core

    assert core.all_right
    assert core.stack[-1].data == 37

    assert isinstance(ret, Block)
    assert ret.type == Block.type_integer
    assert ret.data == 37
Ejemplo n.º 22
0
    def test_get_best_mark(self):
        code = Code()
        mark1 = Mark(mark=18)
        marklist1 = [mark1, Mark(mark=12), Mark(mark=14), Mark(mark=16)]
        student1 = Student()
        student1.marklist = marklist1

        mark2 = Mark(mark=12)
        marklist2 = [Mark(mark=8), mark2, Mark(mark=0)]
        student2 = Student()
        student2.marklist = marklist2

        assert mark1 == code.get_best_mark(student1)
        assert mark2 == code.get_best_mark(student2)
Ejemplo n.º 23
0
    def __init__(self, input, output, target, targetConfig):
        self.nn = NeuralNet()
        self.nn.load(input)

        self.output = output
        self.target = target.upper()

        self.targetConfig = JsonCloak()
        self.targetConfig.load(targetConfig)

        #TODO: This should be the name of the
        # code region which is in the neural net json file
        self.code = Code()
        self.gens[self.target](self)
        self.code.toCpp(output, self.nn, self.targetConfig,
                        self.target == 'AVX')
Ejemplo n.º 24
0
 def test_create_student(self):
     code = Code()
     studentid = 3
     studentlastname = "StudentLastname"
     studentfirstname = "StudentFirstname"
     teacherid = 15
     teacherlastname = "TeacherLastname"
     teacherfirstname = "TeacherFirstname"
     
     student = code.create_student(studentid, studentlastname, studentfirstname, teacherid, teacherlastname, teacherfirstname)
     assert studentid == student.peopleid
     assert studentlastname == student.lastname
     assert studentfirstname == student.firstname
     assert teacherid == student.teacher.peopleid
     assert teacherlastname == student.teacher.lastname
     assert teacherfirstname == student.teacher.firstname
Ejemplo n.º 25
0
class Assembler(object):
    '''Assembler
    method: preprocess()
    method: gen()
    '''
    def __init__(self, file):
        self.__infilename = file
        if file.endswith('.asm'):
            self.__outfilename = file[:-3] + 'hack'
        else:
            self.__outfilename = file + '.hack'
        self.__code = Code()
        self.__parser = Parser(file)

    def preprocess(self):
        '''add the label symbol(First pass),
        then add the variable symbol(Second pass)
        raise: SyntaxError if error occurs
        return: self
        '''
        self.__parser.reset()
        while self.__parser.hasnext():
            cmd, token, line = self.__parser.next()
            if cmd == 'L':
                if not self.__code.insert_label(token, line):
                    raise SyntaxError('dupicate definition for label "{}"'.format(token))
        self.__parser.reset()
        while self.__parser.hasnext():
            cmd, token, line = self.__parser.next()
            if cmd == 'A':
                self.__code.insert_var(token)
        return self

    def gen(self):
        '''generate binary code in strings and stores in .hack file
        '''
        bincode = []
        self.__parser.reset()
        while self.__parser.hasnext():
            cmd, token, _ = self.__parser.next()
            if cmd == 'A':
                bincode.append(self.__code.a_instr(token) + '\n')
            elif cmd == 'C':
                bincode.append(self.__code.c_instr(*token) + '\n')
        with open(self.__outfilename, 'w') as outfile:
            outfile.writelines(bincode)
Ejemplo n.º 26
0
def main():
    parser = Parser(sys.argv[1])
    code = Code()
    name = sys.argv[1].split('.')[0] + '.hack'
    symbolTable = SymbolTable()
    out = open(name, 'w')
    lineCount = 0
    address = 16

    #first pass
    while (parser.has_more_commands()):
        parser.advance()
        if parser.command_type() == 'L':
            symbolTable.add_entry(parser.symbol(), to_bin(lineCount))
        else:
            lineCount += 1

    parser = Parser(sys.argv[1])

    #second pass
    while (parser.has_more_commands()):
        parser.advance()
        if parser.command_type() == 'A':
            s = parser.symbol()
            if is_number(s):
                out.write('0' + to_bin(s))
                out.write('\n')
            elif symbolTable.contains(s):
                out.write('0' + symbolTable.get_adress(s))
                out.write('\n')
            else:
                symbolTable.add_entry(s, to_bin(address))
                out.write('0' + to_bin(address))
                out.write('\n')
                address += 1

        elif parser.command_type() == 'C':
            d = parser.dest()
            c = parser.comp()
            j = parser.jump()
            out.write('111' + code.comp(c) + code.dest(d) + code.jump(j))
            out.write('\n')

    parser.close()
    out.close()
Ejemplo n.º 27
0
def publish():
    content = request.form['content']
    uid = request.form['uid']
    language = request.form['language']

    code = Code(uid=uid, content=content, language=language)
    save_doc_as_file(code)

    return jsonify({'ok': True})
def read_doc_as_file(uid):
    '''Lit le document data/uid'''
    try:
        with open(f'data/{uid}') as fd:
            code = ast.literal_eval(fd.read())
            code = Code(**code)
        return code
    except FileNotFoundError:
        return None
Ejemplo n.º 29
0
    def __init__(self, inputFile):

        # transforms file into a list of lines
        with open(inputFile, 'r') as initializedFile:
            self.linesArray = initializedFile.readlines()

        #initializes counters which we'll need later
        self.command = ''
        self.currentLineNumber = 0
        self.code = Code()
Ejemplo n.º 30
0
 def test_is_a_kaprekar_number(self):
     code = Code()
     assert code.is_a_kaprekar_number(1)
     assert code.is_a_kaprekar_number(4879)
     assert code.is_a_kaprekar_number(7777)
     assert code.is_a_kaprekar_number(187110)
     assert code.is_a_kaprekar_number(500500)
     assert not(code.is_a_kaprekar_number(0))
     assert not(code.is_a_kaprekar_number(sys.maxint))
     assert not(code.is_a_kaprekar_number(12))
     assert not(code.is_a_kaprekar_number(4444))
     assert not(code.is_a_kaprekar_number(4444))
Ejemplo n.º 31
0
	def __load_codes(self):
		"""
		Metoda importująca przykładowe kody do algorytmu.
		"""
		self.codes = []
		codes_path = Paths.codes(self.name)
		codes_files = os.listdir(codes_path)
		for code_file in codes_files:
			code_file_path = os.path.join(codes_path, code_file)
			if os.path.isfile(code_file_path) and code_file.split(".")[-1].lower() == "html":
				code = Code.from_file(code_file_path)
				self.codes.append(code)
Ejemplo n.º 32
0
def split(start, stop):
    dif = stop - start
    quarter1 = Code(start) + dif / 4
    mid = Code(quarter1) + dif / 4
    quarter2 = Code(mid) + dif / 4
    return start, quarter1, Code(quarter1) + 1, mid, Code(
        mid) + 1, quarter2, Code(quarter2) + 1, stop
Ejemplo n.º 33
0
 def test_is_a_palindrome(self):
     code = Code()
     assert code.is_a_palindrome("Kayak")
     assert code.is_a_palindrome("Esope reste ici et se repose")
     assert code.is_a_palindrome("Eh ! ça va la vache.")
     assert not(code.is_a_palindrome("Lapin"))
     assert not(code.is_a_palindrome("Kaya"))
Ejemplo n.º 34
0
    def test_sort_mark_list(self):
        code = Code()
        mark1 = Mark(mark=18)
        mark2 = Mark(mark=12)
        mark3 = Mark(mark=14)
        mark4 = Mark(mark=16)
        marklist1 = [mark1, mark2, mark3, mark4]
        student1 = Student()
        student1.marklist = marklist1

        mark21 = Mark(mark=8)
        mark22 = Mark(mark=12)
        mark23 = Mark(mark=0)
        marklist2 = [mark21, mark22, mark23]
        student2 = Student()
        student2.marklist = marklist2
        
        sorted_marklist1 = [mark2, mark3, mark4, mark1]
        sorted_marklist2 = [mark23, mark21, mark22]

        assert sorted_marklist1 == code.sort_mark_list(student1)
        assert sorted_marklist2 == code.sort_mark_list(student2)
Ejemplo n.º 35
0
def main(*args):
    Globals.initialize()  # initialize global variables (symbol table)
    inputFile = str(sys.argv[1])
    outputFile = inputFile[:(len(inputFile) - 4)] + ".hack"

    # first pass through file to add labels to symbol table
    lineNumber = -1
    with open(inputFile, "r") as r:
        for line in r:
            if is_code(line):
                try:
                    # if line contains label, add label to symbol table
                    label = re.findall("(?<=^\()\S*(?=\))", line)[0]
                    Globals.symbolTable.add_label(label, lineNumber + 1)
                except:
                    lineNumber += 1

    # second pass through file to parse lines with instructions
    lineNumber = -1
    with open(inputFile, "r") as r, open(outputFile, "w") as w:
        for line in r:
            if is_code(line):
                try:
                    # pass if line contains label
                    re.findall("(?<=^\()\S*(?=\))", line)[0]
                    pass
                except:
                    # parse line into binary
                    lineNumber += 1
                    line = line.replace('\n', '')
                    line = "".join(line.split(" "))
                    instruction = Parser(line)
                    instruction.parse()
                    code = Code(instruction)
                    code.translate()
                    w.write(code.get_binary() + '\n')
            else:
                pass
Ejemplo n.º 36
0
def network_loop(net):
    while True:
        # print 'going to rec'
        received = net.receive()
        #print 'reced'
        if received == 'bye':
            # print received
            net.close()
            if not os.path.exists('found.txt'):
                open('found.txt', 'w')
                print 'open, not write'
            break
        elif received == 'You are the king':
            #print received
            pass
        else:
            lst = received.split(',')
            lst2 = [x.split(':')[1] for x in lst]
            print lst2
            start = Code(lst2[0])
            stop = Code(lst2[1])
            md5_code = lst2[2]
            start_stop = split(start, stop)
            threads = []
            for i in range(0, 7, 2):
                threads.append(
                    Process(target=crack,
                            args=(
                                start_stop[i],
                                start_stop[i + 1],
                                md5_code,
                            )))
            for t in threads:
                t.start()
            for t in threads:
                t.join()
            send_found(net)
Ejemplo n.º 37
0
def init(vmFile):
    file_loc = vmFile.split('\\')
    file_name = file_loc[-1].split('.')[0]

    with open(vmFile, 'r') as f:
        while True:
            line = f.readline()

            if line.startswith('\n') or line.startswith('//'):
                continue

            if not line:
                break
            # Operation on parser
            parsed_c = Parser(line.replace('\n', '')).get_command()
            Code(parsed_c, file_name, commands).execute_operation()
Ejemplo n.º 38
0
	def compile(self, source):
		"""
		Compiles a Bebop Source object into a Bebop Code object.
		"""
		code_tuple = ()
		for statement in source.data:
			if self.rex_tuple.match(statement):
				try:
					tup = eval(statement)
				except Exception:
					return Block.new_error('Malformed tuple: ' + statement)

				if len(tup) == 1:
					code_tuple = code_tuple + (Block.new_integer(tup[0]),)
				elif len(tup) == 2:
					code_tuple = code_tuple + (Block.new_int_pair(tup),)
				elif len(tup) == 4:
					code_tuple = code_tuple + (Block.new_NESW(tup),)
				else:
					return Block.new_error('Tuple must be (color, int_pair or nesw): ' + statement)

			elif self.rex_picture.match(statement):
				try:
					lol = eval(statement)
				except Exception:
					return Block.new_error('Malformed picture: ' + statement)

				code_tuple = code_tuple + (Block.new_picture(list_of_list=lol),)

			elif self.rex_vector.match(statement):
				try:
					vec = eval(statement)
				except Exception:
					return Block.new_error('Malformed vector: ' + statement)

				code_tuple = code_tuple + (Block.new_vector(vec),)

			else:
				if statement in self.opcode:
					code_tuple = code_tuple + (self.opcode[statement],)
				else:
					return Block.new_error('Unknown opcode: ' + statement)

		if len(code_tuple) == 0:
			return Block.new_error('Empty source')

		return Code(code_tuple)
Ejemplo n.º 39
0
def test_MulticoreErrors():
    eval = CodeEval(Example)

    eval.demo_q = [Block.new_picture(list_of_list=[[1, 2, 3]])]
    eval.demo_a = [Block.new_picture(list_of_list=[[4, 0, 4]])]
    eval.question = []

    eval.multicore_clear()

    ret = eval.multicore_run_all(
        Code((Block.new_integer(1), Failing.failing_zero_division,
              Block.new_integer(0), Failing.failing_zero_division)))

    assert ret.type == Block.type_error
    assert ret.data == 'Try/catch caught an exception'

    eval.multicore_clear()

    ret = eval.multicore_run_all(
        eval.compile(Source(('get_question', 'pic_two_col_reverse'))))

    assert ret.type == Block.type_error
    assert ret.data == 'Only two colors expected'

    eval.multicore_clear()

    ret = eval.multicore_run_all(
        eval.compile(
            Source(('get_question', 'pic_fork_on_v_axis_as_pics',
                    'pics_as_2pic'))))

    assert ret.type == Block.type_no_error

    for pl in eval.multicore_state['pic_lists']:
        assert len(pl) == 1

    ret = eval.multicore_run_all(eval.compile(Source(('(2, 4)', ))))

    assert ret.type == Block.type_error
    assert ret.data == 'Code item does not return a picture'

    ret = eval.multicore_run_all(eval.compile(Source(('(2, 4)', ))),
                                 ignore_ret_type=True)

    assert ret.type == Block.type_no_error
Ejemplo n.º 40
0
    def traduzir(lines):
        codes = []

        pettern = r"(\w+)\s*"
        operacao = re.compile(pettern)

        patterns = {
            "add": r"(add)\s+(\w+)\s*,\s*(\w+)\s*",
            "mov": r"(mov)\s+(.+)\s*,\s*(\w+)\s*",
            "imul": r"(imul)\s+(\w+)\s*,\s*(\w+)\s*,\s*(\w+)\s*",
            "inc": r"(inc)\s+(\w+)\s*",
            "dec": r"(dec)\s+(\w+)\s*",
            "label": r"(label)\s+([^0]\d*)",
            "condicao":
            r"(\w+)\s*(<>|<|>|==|>=|<=)\s*(\w+)\s*[?]\s*(?:jump\s+|)(0|\d+)\s*:\s*(?:jump\s+|)(0|\d+)",
            "end": "end"
        }

        for line in lines:
            instrucao = operacao.match(line).group(1)
            reresult = None
            codetype = None
            if instrucao in patterns:
                reresult = re.match(patterns[instrucao], line)
                if reresult is None:
                    Consts.running = False
                    raise SyntaxError(line)

                reresult = reresult.groups()[1::]
                codetype = Consts.INSTRUCOES[instrucao]
            else:
                reresult = re.match(patterns["condicao"], line)
                if reresult is None:
                    Consts.running = False
                    raise SyntaxError(line)

                reresult = reresult.groups()
                codetype = Consts.INSTRUCOES["condicao"]

            codes.append(Code(codetype, reresult))

            if instrucao == "end":
                break

        return codes
Ejemplo n.º 41
0
def passOne(readFile, writeFile, symbols):
    readFile.seek(0)
    parser = Parser()
    code = Code()
    for line in readFile:
        if not line.strip():
            continue
        elif line[0:2] == "//":
            continue
        elif line[0] == "(":
            continue
        elif line[0] == '@':
            writeLine = AIns(
                line, parser, code,
                symbols)  #TODO Too many object passed by arguments
            writeFile.write(writeLine + "\n")
        else:
            writeLine = CIns(line, parser, code, symbols)
            writeFile.write(writeLine + "\n")
Ejemplo n.º 42
0
 def login(self):
     browser.get(self.login_url)
     try:
         input_name = browser.find_element_by_id('username')
         input_pd = browser.find_element_by_id('password')
         button = browser.find_element_by_id('loginSub')
         time.sleep(1)
         input_name.send_keys(self.username)
         input_pd.send_keys(self.password)
         c = Code(browser)  #调用验证码识别模块
         c.main()
         button.click()
         time.sleep(2)
         #等待页面跳转,如果验证码识别错误,就执行下面的while语句
         while browser.current_url == self.login_url + '#':
             c = Code(browser)
             c.main()
             button.click()
             time.sleep(2)
     except NoSuchElementException:
         self.login()
Ejemplo n.º 43
0
	def assemble(self,fileInput):
		parser = Parser(fileInput);
		code = Code();
		symtab = SymbolTable();

		# Run the first pass to handle labels.
		self.firstPass(parser,symtab);

		# Reset the parser index for the second pass.
		parser.resetParser();

		# Run the second pass to assembly the code, with labels included.
		output = self.secondPass(parser,code,symtab);

		# Write the assembled binary code to a file named [filename].hack
		with open(fileInput[:-3] + "hack",'w') as file:
			for line in output:
				file.write("%s\n" % line);
		return;
Ejemplo n.º 44
0
    def main():

        print("******************************************")
        print("***          FileSet Report            ***")
        print("******************************************")
        print()

        fileORdir = Util.getCommandLineArgument(1)
        level = Util.getCommandLineArgument(2)
        files = FileSet(fileORdir, "hack")
        files.report()

        print()
        print("******************************************")
        print("***         Processing Report          ***")
        print("******************************************")
        print()

        while files.hasMoreFiles():
            inputFileSpec = files.nextFile()
            print("Processing: %s" % inputFileSpec)
            outputFileSpec = os.path.splitext(inputFileSpec)[0]+".dis"
            inputFile = open(inputFileSpec, "rU")
            outputFile = open(outputFileSpec, "w")
            parser = Parser(inputFile)
            while parser.hasMoreInstructions():
                parser.advance()
                if (parser.instructionType() == "A_TYPE"):
                    value = parser.value()
                    inst = Code.a_type(value)
                if (parser.instructionType() == "C_TYPE"):
                    dest = parser.dest()
                    comp = parser.comp()
                    jump = parser.jump()
                    destMnemonic = Code.destMnemonic(dest)
                    compMnemonic = Code.compMnemonic(comp)
                    jumpMnemonic = Code.jumpMnemonic(jump)
                    inst = Code.c_type(destMnemonic, compMnemonic, jumpMnemonic)
                if (parser.instructionType() == "INVALID"):
                    inst = Code.invalid_type()
                inst += Util.repeatedChar(" ", 20-len(inst))
                inst += "// %05i:" % parser.address()
                inst += " [%s]" % parser.hexInstruction()
                inst += " %s\n" % parser.parsedInstruction()
                outputFile.write(inst)
            outputFile.close()
            inputFile.close()

        print()
        print("Processing of file(s) complete.")
Ejemplo n.º 45
0
		def try_push_to_topN(code_item, eval):
			nonlocal top_N
			nonlocal top_min_ev

			ev = eval[IDX_PIC_REACH_MEAN]*(1 - WEIGHT_MIN_IN_EVAL) + eval[IDX_PIC_REACH_MIN]*WEIGHT_MIN_IN_EVAL
			if ev <= top_min_ev:
				return

			code = Code(self.code_in_path_to_node + code_item)

			top = (ev, code, eval, num_walks, time.time() - start_time)

			if len(top_N) == NUM_TOP_SOLUTIONS:
				top_N.pop()

			top_N.append(top)
			top_N = sorted(top_N, key=itemgetter(0), reverse=True)

			if len(top_N) == NUM_TOP_SOLUTIONS:
				top_min_ev = top_N[-1][0]
# ECS 06 - Assembler/base of the software stack
# Class: CSCI 410 - Elements of Computing Systems
# Written in: Python 2.7

import sys, string, os
from Parser import Parser
from Code import Code
from Symbol import Symbol


infile = sys.argv[1]  # Sys.argv is the system argument list object

outfile = infile.replace(".asm", ".hack")
parse = Parser(infile)
outfilecontents = ""
code = Code()
sym = Symbol()
i = 0
numOfNonLabelSymbols = 0
while parse.hasMoreCommands():
    parse.advance()
    parse.output()
    parse.stripwhitespace()
    if len(parse.parsedline) != 0 and parse.parsedline != "\n" and parse.commandType() == 2:
        if not sym.contains(parse.symbol()):
            sym.addEntry(parse.symbol(), str(i))
    if len(parse.parsedline) != 0 and parse.parsedline != "\n" and parse.commandType() != 2:
        i += 1

parse = Parser(infile)
while parse.hasMoreCommands():
Ejemplo n.º 47
0
def main():
    # open an output file
    input_path = sys.argv[FILE_POS]
    if isdir(input_path):
        input_list = [ input_path + "/" +f for f in listdir(input_path) 
            if (isfile(join(input_path, f))) and (f.endswith(".asm")) ]
    else:
        input_list = [input_path]
    
    for input_file in input_list:
        index = input_file.index(".")
        output_file = open(input_file[:index] + ".hack", "w")
        # parse a new line
        code = Code()
        symbol_table = SymbolTable()
        counter_address = FIRST_ADDRESS_RAM
        counter_rom = FIRST_ADDRESS_ROM

        # first pass
        parser_first_pass = Parser(input_file)
        while parser_first_pass.has_more_commands():
            command = parser_first_pass.advance()
            parse_type = parser_first_pass.command_type()
            if parse_type == L_COMMAND:
                if not symbol_table.contains(command[1:-1]):
                    symbol_table.add_entry(command[1:-1], counter_rom)
            else:
               counter_rom+=1

        # second pass
        parser_second_pass = Parser(input_file)
        while parser_second_pass.has_more_commands():
            command = parser_second_pass.advance()
            line_to_hack = ""
            parse_type = parser_second_pass.command_type()

            # translate the line to an A Command
            if parse_type == A_COMMAND:
                if command[1:].isdigit():
                    address = command[1:]
                else:
                    if symbol_table.contains(command[1:]):
                        address = symbol_table.get_address(command[1:])
                    else:
                        symbol_table.add_entry(command[1:], counter_address)
                        address = counter_address
                        
                        counter_address += 1
                binary_repr = str(bin(int(address))[2:].zfill(15))
                line_to_hack = A_PREFIX + binary_repr

            # translate the line to a C Command
            if parse_type == C_COMMAND:
                # C command comp
                comp_type = parser_second_pass.comp()
                code_comp = code.comp(comp_type)
                # C command dest
                dest_type = parser_second_pass.dest()
                code_dest = code.dest(dest_type)
                # C command jump
                jump_type = parser_second_pass.jump()
                code_jump = code.jump(jump_type)
                if ("<" in comp_type) or (">" in comp_type):
                    line_to_hack = C_PREFIX_SPE + code_comp + code_dest + code_jump
                else:
                    line_to_hack = C_PREFIX_REG + code_comp + code_dest + code_jump
                
            if parse_type == L_COMMAND:
                continue

            # write the line to the output file
            output_file.write(line_to_hack + "\n")


        output_file.close()
Ejemplo n.º 48
0
 def test_factoriel(self):
     code = Code()
     assert 40320 == code.factoriel(8)
     assert 1 == code.factoriel(0)
     assert 6 == code.factoriel(3)
Ejemplo n.º 49
0
from Parser         import Parser
from Commands       import Commands
from Data           import Data
from Code           import Code
from Resolver       import Resolver
from Configuration  import Configuration
from Generator      import Generator
from Operators      import Operators

from sys import argv

if __name__ == "__main__":
    operators       = Operators()
    configuration   = Configuration()
    data            = Data(configuration)
    code            = Code(data, configuration, operators)
    commands        = Commands(data, code)
    parser          = Parser(commands)
    parser.parse_file(argv[1])
    # Won't need these after Parsing and Allocation.
    # So let's enforce that for our own discipline.
    # State is carried in Code and Data.
    del parser
    del commands
    print("Parsing and Allocation Done")

    # Dump initial state of code and data
    # immediately after Allocation
    configuration.filedump("LOG.allocate")
    data.filedump("LOG.allocate", append = True)
    code.filedump("LOG.allocate", append = True)
Ejemplo n.º 50
0
class Parser:

    # file read write related
    inputFile = None
    outputArray = []

    # command types
    A_COMMAND = 0
    C_COMMAND = 1
    L_COMMAND = 2

    # intialize code class with codes and methods for calculations, destination and jump
    code = Code()

    # symbol table attribution https://github.com/davidbrenner/nand2tetris/blob/master/06/SymbolTable.py
    symbolTable = {
            'SP': 0, 'LCL':1, 'ARG':2, 'THIS':3, 'THAT':4,
            'R0':0, 'R1':1, 'R2':2, 'R3':3, 'R4':4, 'R5':5, 'R6':6, 'R7':7,
            'R8':8, 'R9':9, 'R10':10, 'R11':11, 'R12':12, 'R13':13, 'R14':14,
            'R15':15, 'SCREEN':16384, 'KBD':24576}

    symbolMemoryAddress = 16

    # Initializer prepares a fresh array
    def __init__(self, inputFile):

        # transforms file into a list of lines
        with open(inputFile, 'r') as initializedFile:
            self.linesArray = initializedFile.readlines()

        #initializes counters which we'll need later
        self.command = ''
        self.currentLineNumber = 0
        self.code = Code()

    # checks if there are more commands to process
    def hasMoreCommands(self):
        if self.currentLineNumber - 1 < len(self.linesArray):
            return True
        else:
            return False

    # Reads the next command from the input and makes it the current
    # command. Should be called only if hasMoreCommands() is true.
    # Initially there is no current command.
    def advance(self):
        # grab a line
        if self.hasMoreCommands():
            command = self.linesArray[self.currentLineNumber]
            self.currentLineNumber += 1

        # make the valid command line a line

    # checks the type of the command
    def commandType(self, line):
        if line.startswith("@"):
            return self.A_COMMAND

        elif line.startswith("(") and line.endswith(")"):
            return self.L_COMMAND

        else:
            return self.C_COMMAND

    def stripLabels(self, cleanArray):
        labelStrippedArray = []
        for line in cleanArray:
            #for label declarations
            if self.commandType(line) == 2:
                label = line[1:-1]
                if label in self.symbolTable:
                    pass
                else:
                    self.symbolTable[label] = self.currentLineNumber

            # if neither of two add to
            else:
                labelStrippedArray.append(line)
                self.currentLineNumber += 1
        return labelStrippedArray
    # for processing and replacing @symbols with correct addresses
    def replaceAtDeclarations(self, labelStrippedArray):
        pureAssembyArray = []
        for line in labelStrippedArray:
            # if an @symbol command
            if self.commandType(line) == 0 and re.search('[A-Za-z_.$:]', line[1]):
                symbol = line.partition("@")[2]
                # for symbols in the table swap symbolic address with numeric address
                if symbol in self.symbolTable:
                    symbolAddress = self.symbolTable[symbol]
                    symbolAddressString = str(symbolAddress)
                    replacedLine = "@" + symbolAddressString
                    pureAssembyArray.append(replacedLine)
                    self.currentLineNumber += 1
                #for symbols not in the table they must be var addresses, address them
                else:
                    self.symbolTable[symbol] = self.symbolMemoryAddress
                    symbolAddressString = str(self.symbolMemoryAddress)
                    self.symbolMemoryAddress += 1
                    replacedLine = "@" + symbolAddressString
                    pureAssembyArray.append(replacedLine)
            else:
                pureAssembyArray.append(line)
        return pureAssembyArray


    # takes a clean array (no labels, no @symbols) and starts translating directly to machine code
    def translateToMachineCode(self, cleanArray):
        # first three litters of CInstruction
        cInstructionStarterString = "111"

        for line in cleanArray:
            if self.commandType(line) == self.A_COMMAND:
                decimalValueStr = line.partition("@")[2]
                decimalValueInt = int(decimalValueStr)
                binaryValue = "{0:015b}".format(decimalValueInt)
                self.outputArray.append("0" + binaryValue)

            elif self.commandType(line) == self.C_COMMAND:
                # straight C command
                if ("=" not in line) and (";" not in line):
                    cBinaryString = self.code.comp(line)
                    destString = self.code.dest("null")
                    jumpString = self.code.jump("null")
                    self.outputArray.append(cInstructionStarterString + \
                                            cBinaryString + destString + jumpString)
                # dest = comp command
                elif ("=" in line) and (";" not in line):
                    parsedOnEqual = line.partition("=")
                    cBinaryString = self.code.comp(parsedOnEqual[2])
                    destString = self.code.dest(parsedOnEqual[0])
                    jumpString = self.code.jump("null")
                    self.outputArray.append(cInstructionStarterString + \
                                            cBinaryString + destString + jumpString)
                # comp;JMP command
                elif ("=" not in line) and (";" in line):
                    parsedOnSemicolon = line.partition(";")
                    cBinaryString = self.code.comp(parsedOnSemicolon[0])
                    destString = self.code.dest("null")
                    jumpString = self.code.jump(parsedOnSemicolon[2])
                    self.outputArray.append(cInstructionStarterString + \
                                            cBinaryString + destString + jumpString)
                # dest = comp; jump
                elif ("=" in line) and (";" in line):
                    equalsIndex = line.index("=")
                    semicolonIndex = line.index(";")
                    cBinaryString = self.code.comp(line[equalsIndex+1:semicolonIndex])
                    destString = self.code.dest(line[0:equalsIndex])
                    jumpString = self.code.jump(line[semicolonIndex+1:len(line)])
                    self.outputArray.append(cInstructionStarterString + \
                                            cBinaryString + destString + jumpString)

            elif self.commandType(line) == self.L_COMMAND:
                pass
        return self.outputArray
 def run(self, edit):
   c = Code(self.view, edit)
   c.find_warnings()
Ejemplo n.º 52
0
 def _survey_start(self, params):
     Code._survey_start(self, params)
     self.counts['PbBinLines'] = [0] * len(self.blockDetectors)
     self._isPblFile = self._currentPath.fileExt.lower() == '.pbl'
     self._outFiles = {}
Ejemplo n.º 53
0
    
    def getHashCopy(self):
        newCode = ''
        for line in self.baseMatrix:
            newCode += 'd' + 500 + int(line.deltaIndent) + ' '
            for bone in line.skel():
                md5 = md5()
                md5.update(bone)
                newCode += md5.hexdigest()[0:4] + ' '
            newCode = newCode[0:-1] + '\n'
        return newCode 
'''

    code = '''def sigsim(ss1,ss2):\n    similar=0\n    for i in range(0,len(ss1)):\n        if(ss1[i] == ss2[i]):\n            similar+=1\n    \n    return float(similar)/float(len(ss1))\n'''
    
    code = '''#===============================================================================\n# Task 5: Implement a function sigsim(ss1, ss2) which calculates the similarity of signatures ss1 and ss2.\n# Note that it doesn't matter if the signatures consist of integers (as in the case of minhashing) or of -1's\n# and +1's (as in the case of sketches) - the procedure is the same.\n#===============================================================================\n\ndef sigsim(ss1,ss2):\n    similar=0\n    for i in range(0,len(ss1)):\n        if(ss1[i] == ss2[i]):\n            similar+=1\n    \n    return float(similar)/float(len(ss1))'''
    code = code
    print code
    print "==================="
    myProgram = Code(code)
    
    print myProgram.getWorkingCopy()
    print "==================="
    print myProgram.getHashCopy()
    
    print "==================="
    fingerprint = myProgram.getWinnow(12)
    print fingerprint