예제 #1
0
def pre_output(argv):
    """
    This function will create new file (.hack file),
    and will output the compiled assembley file to it.
    :param argv: the users input
    :return: None
    """
    BOOT_STRAP = [["call", "Sys.init", "0"]]  # bootstrap initialization
    boot_strap_code = coder.Coder(BOOT_STRAP, "")
    boot_strap_coded_lines = boot_strap_code.get_list()
    for i in range(1, len(argv)):
        # This loop iterates over the user's inputs (or arguments).
        if os.path.isdir(argv[i]):
            if argv[i][-1] != "/":
                dir_name = argv[i].split("/")[-1]
            else:
                dir_name = argv[i].split("/")[-2]
            asm_file = open(argv[i] + "/" + dir_name + ".asm", "w")
            asm_file.writelines(["@256\n", "D=A\n", "@SP\n", "M=D\n"])
            asm_file.writelines(boot_strap_coded_lines[0])
            for file in os.listdir(argv[i]):
                if file.endswith(".vm"):
                    # This if statement verifies that the argument is actually a dir.
                    final_output(argv[i] + "/" + file, asm_file)
            asm_file.close()
        elif argv[i].endswith(".vm"):
            asm_file = open(argv[i][:-2] + "asm", "w")
            asm_file.writelines(["@256\n", "D=A\n", "@SP\n", "M=D\n"])
            asm_file.writelines(boot_strap_coded_lines[0])
            # Enter's if the specific argument is an assembly file only.
            final_output(argv[i], asm_file)
            asm_file.close()
예제 #2
0
 def testCreateTargetImage(self):
     img = Image.open("samples/crop.jpg")
     encoder = coder.Coder()
     # Create a crop and resize it
     layerConf = LayerConfig(img, {"imgwidth": 200, "crop":(0, 0, 300, 300)})
     target = encoder.createTargetImage(img, layerConf)
     target.save("/tmp/target1.webp", "WEBP", quality=95)
예제 #3
0
 def test_most_likely_set(self):
     print("Most likely set test")
     src = source.DiscreteSource(mocks.get_stationary_src_desc())
     coder_ = coder.Coder(src, 1, 0.01, 4)
     most_likely_set = coder_._Coder__create_most_likely_set()
     print("|T| =", len(most_likely_set))
     print("n =", len(most_likely_set[0]))
     print(100 * "=")
예제 #4
0
    def test_coder(self):
        print("Coder test")
        src = source.DiscreteSource(mocks.get_stationary_src_desc())
        coder_ = coder.Coder(src, 1, 0.01, 4)
        code = coder_.get_code()

        for word, word_code in code.items():
            print(word, word_code)
        print(100 * "=")
예제 #5
0
def tree_search(request, omega_id):
    decoder = coder.Coder()
    result = []
    goto_docid = 1

    while goto_docid is not None and goto_docid <= omega_id:
        request.goto(goto_docid)
        (docid, goto_docid) = request.evaluate()
        if docid is not None and docid <= omega_id:
            result.append(docid)

    return result
예제 #6
0
 def encode(self, filename, configname):
     img = Image.open(filename)
     basename=filename.split("/")[1]
     config = json.load(open(configname, "rb"))
     layers = coder.Coder().encode(img, config)
     i = 0
     layers2 = []
     for layer in layers:
         i += 1
         layerFileName = "/tmp/" + basename + "_layer" + str(i) + ".webp"
         layer[0].save(layerFileName, "WEBP", quality=90)
         #layer[0].save(layerFileName+".png", "PNG", quality=95)
         # TODO: Run ssim test to see that the image we got is correct
         layer2 = Image.open(layerFileName)
         layers2.append(layer2)
예제 #7
0
    def __init__(self, val):
        TreeNode.__init__(self, val, term=True)
        decoder = coder.Coder()

        hash_val = mmh3.hash64(val.encode('utf8'))[0]
        offset, count = term_search(hash_val)
        if offset is None or count is None:
            self.docs = []
            self.pos = 0
        else:
            bin_index.seek(offset)
            byte_str = bytearray()
            buf = bin_index.read(count)
            byte_str.extend(buf)
            self.docs = decoder.decode(byte_str)
            self.pos = 0
예제 #8
0
def final_output(file_name, asm_file):
    """
    The input generator
    :param file_name: The VM file to be complied.
    :param asm_file: The asm file to be written on.
    :return: None
    """
    # calling the vm file
    vm_file = open(file_name, "r")
    parsed_file = parser.Parser(vm_file)
    parsed_lines = parsed_file.get_list()
    code = coder.Coder(parsed_lines, file_name.split("/")[-1][:-2])
    coded_lines = code.get_list()
    vm_file.close()
    for command in coded_lines:
        # writing the complied lines into the new file (.hack)
        asm_file.writelines(command)
예제 #9
0
def final_output(file_name):
    """
    This function will create new file (.hack file),
    and will output the compiled assembley file to it.
    :param file_name: the file to be complied
    :return: None
    """
    # calling the asm file
    asm_file = open(file_name, "r")
    parsed_file = parser.Parser(asm_file)
    parsed_lines = parsed_file.get_list()
    code = coder.Coder(parsed_lines)
    coded_lines = code.get_list()
    asm_file.close()
    # writing the complied lines into the new file (.hack)
    new_file = open(file_name[:-3] + "hack", "w")
    new_file.writelines(coded_lines)
    new_file.close()
예제 #10
0
import iodeux as IODeux
import lib as Lib
import coder as Coder

if __name__ == '__main__':
    io = IODeux.IODeux()
    coder = Coder.Coder()

    stringRead = io.readFile(Lib.FILENAME_READ)

    encodedVectors = coder.encode(stringRead)
    print("ENCODED VECTORS:")
    print(encodedVectors)

    decodedTuple = coder.decode(encodedVectors)
    decodedString = decodedTuple[1]
    print("DECODED STRING:")
    print(decodedString)

    if (decodedTuple[0]):
        io.writeFile(Lib.FILENAME_WRITE, decodedString)

        print("Same string? - " + repr(stringRead == decodedString))
    else:
        print(decodedTuple[1])
예제 #11
0
파일: main.py 프로젝트: Bangys/Practise
def run():
    path = os.getcwd()
    filename = "/test.asm"
    # c-command tuple in list, format: (comp, dest, jump)
    code = []
    # program counter
    pc = -1
    first = True
    RAM = 16

    # load each line to a list
    f = open(path + filename, 'r')
    f_data = f.read()

    def is_in_dict(symbols):
        if t.get(symbols) is None:
            t.update({symbols: RAM})
            return False
        else:
            return True

    # two-pass: 1. process symbol table
    #           2. generate binary code
    for i in range(2):
        p = parser.Parser(copy.deepcopy(f_data))

        while p.has_more_commands():
            current = p.advance()
            command_type = p.command_type(current)

            if command_type == "A_COMMAND":
                if first:
                    symbols_a = current[1:]
                    if p.is_symbol(
                            symbols_a) and is_in_dict(symbols_a) is False:
                        RAM += 1
                    pc += 1
                else:
                    code.append(p.symbol(current))

            if command_type == "L_COMMAND":
                if first:
                    # pseudo-command processing
                    symbols_l = current[1:-1]
                    if is_in_dict(symbols_l) is False:
                        RAM += 1
                    t.update({symbols_l: pc + 1})
                else:
                    code.append(p.symbol(current))

            if command_type == "C_COMMAND":
                comp, dest, jump = "", "", ""
                if "=" in current:
                    part = current.split("=")
                    dest = p.dest(part[0])
                    if ";" in part[-1]:
                        comp = p.comp(part[1:].split(";")[0])
                        jump = p.jump(part[1:].split(";")[-1])
                    else:
                        comp = p.comp(part[-1])
                elif ";" in current:
                    part2 = current.split(";")
                    comp = p.comp(part2[0])
                    jump = p.comp(part2[-1])
                if first:
                    pc += 1
                else:
                    code.append(tuple([comp, dest, jump]))

        first = False
        if first is False:
            logg("pass {} ....".format(i + 1))

        # translate to binary
        if len(code) > 0:
            logg(t)
            logg("".join([str(x) + "\n" for x in code]))
            bcode = coder.Coder(code)

    logg(pc)