Exemplo n.º 1
0
def compile_pascal(source, dest, is_debug = False, is_interpret = False, out_stream = sys.stdout, output_tokens = False, output_bytecodes = False, lib = ['.'], in_stream = sys.stdin):
  '''
  DID YOU KNOW that compile() is a built in function?
  '''
  set_debug(is_debug)
  debug("Compiling %s into %s" % (source, dest))
  scanner = Scanner(source)
  tokens = scanner.scan()
  if output_tokens:
    write(tokens, source + "_tokenized")
  debug('scanning complete')
  parser = Parser(tokens, source, lib = lib)
  bytecodes, success = parser.parse()
  if output_bytecodes:
    if is_debug:
      write(prettify(bytecodes), source + "_unassembled")
    else:
      write(bytecodes, source + "_unassembled")
  if not success:
    print 'Parsing error'
    return
  debug('parsing complete')
  assembler = Assembler(bytecodes)
  assembled = assembler.assemble()
  if is_debug:
    write(prettify(assembled), dest + '_debug')
  write(assembled, dest)
  debug('assembly complete.' )
  if is_interpret:
    interp = Interpreter(out_stream, in_stream, code = assembled)
    interp.interpret()
  else:
    debug('run program now with `python interpreter.py %s`' % dest)
Exemplo n.º 2
0
def test_add():
    asm = ADD_Operation().resolve()
    print(asm)
    expected = ASM('''
      // MACRO=LOAD_SP
      @SP
      A=M
      // MACRO_END
      // pop y into D
      A=A-1
      D=M
      // pop x into M
      A=A-1
      // do the operation
      M=M+D
      // MACRO=DEC_SP
      @SP
      M=M-1
      // MACRO_END
        ''')
    assert str(asm) == str(expected)

    # make sure it output valid assembly
    assembler = Assembler()
    assembler.assemble(str(asm))
Exemplo n.º 3
0
def deobfuscate(codestring):
    # Instructions are stored as a string, we need
    # to convert it to an array of the raw bytes
    insBytes = bytearray(codestring)

    oep = find_oep(insBytes)
    logger.info('Original code entrypoint at {}'.format(oep))

    logger.info('Starting control flow analysis...')
    disasm = Disassembler(insBytes, oep)
    disasm.find_leaders()
    disasm.construct_basic_blocks()
    disasm.build_bb_edges()
    logger.info('Control flow analysis completed.')
    logger.info('Starting simplication of basic blocks...')
    render_graph(disasm.bb_graph, 'before.svg')
    simplifier = Simplifier(disasm.bb_graph)
    simplifier.eliminate_forwarders()
    render_graph(simplifier.bb_graph, 'after_forwarder.svg')
    simplifier.merge_basic_blocks()
    logger.info('Simplification of basic blocks completed.')
    simplified_graph = simplifier.bb_graph
    render_graph(simplified_graph, 'after.svg')
    logger.info('Beginning verification of simplified basic block graph...')

    if not verify_graph(simplified_graph):
        logger.error('Verification failed.')
        raise SystemExit

    logger.info('Verification succeeded.')
    logger.info('Assembling basic blocks...')
    asm = Assembler(simplified_graph)
    codestring = asm.assemble()
    logger.info('Successfully assembled. ')
    return codestring
Exemplo n.º 4
0
def main():
    if len(sys.argv) < 6:
        print >>sys.stderr, "Usage: %s <instmem.mif> <instmem_size in byte> <datamem.mif> <datamem_size in byte> <xxx.S> [xxx.S] ..." % (sys.argv[0])
        sys.exit(1)
    if sys.argv[1] != '-':
        instmif = MifFile(sys.argv[1])
        instmif.init(int(sys.argv[2]), 1)
    else:
        instmif = None
    if sys.argv[3] != '-':
        datamif = MifFile(sys.argv[3])
        datamif.init(int(sys.argv[4]), 4)
    else:
        datamif = None
    assembler = Assembler()
    for filename in sys.argv[5:]:
        assembler.compile(filename)
    assembler.relocate()
    if instmif != None:
        if assembler.instmem.get_size() > instmif.memory.size:
            print "Inst mem too small, need %dB" % (assembler.instmem.get_size())
            sys.exit(1)
        assembler.instmem.fill(instmif.memory)
        instmif.write_back()
    if datamif != None:
        if assembler.datamem.get_size() > datamif.memory.size:
            print "Data mem too small, need %dB" % (assembler.datamem.get_size())
            sys.exit(1)
        assembler.datamem.fill(datamif.memory)
        datamif.write_back()
Exemplo n.º 5
0
 def test_determine_order(self):
     from assembler import Assembler
     assbl = Assembler(sequences, identifiers)
     c = map_top_bottom
     d = map_bottom_top
     o = assbl._determine_order(c, d)
     self.assertEqual(o, order)
Exemplo n.º 6
0
 def test_assemble(self):
     from assembler import Assembler
     assbl = Assembler(sequences, identifiers)
     assbl._find_matching_pairs = MagicMock(return_value=(map_top_bottom,
                                                          map_bottom_top))
     assbl._determine_order = MagicMock(return_value=order)
     self.assertEqual(assbl.assemble(), assembled_seq)
Exemplo n.º 7
0
    def test_assemble_ipform(self):
        # =====================================================================
        # Test 7: Assemble Kernel
        # =====================================================================
        mesh = Mesh1D(resolution=(10, ))

        Q1 = QuadFE(1, 'DQ1')
        dofhandler = DofHandler(mesh, Q1)
        dofhandler.distribute_dofs()

        phi = Basis(dofhandler, 'u')

        k = Explicit(lambda x, y: x * y, n_variables=2, dim=1)
        kernel = Kernel(k)
        form = IPForm(kernel, test=phi, trial=phi)

        assembler = Assembler(form, mesh)
        assembler.assemble()

        #af = assembler.af[0]['bilinear']
        M = assembler.get_matrix().toarray()

        u = Nodal(lambda x: x, basis=phi)
        v = Nodal(lambda x: 1 - x, basis=phi)

        u_vec = u.data()
        v_vec = v.data()

        I = v_vec.T.dot(M.dot(u_vec))
        self.assertAlmostEqual(I[0, 0], 1 / 18)
Exemplo n.º 8
0
 def evaluate(self, st):
     try:
         input_value = int(input("Input: "))
         Assembler.write_line("MOV EBX, {}".format(input_value))
         return (input_value, "INT")
     except:
         raise ValueError("AST Error (Input): Only INT is a valid input type")
Exemplo n.º 9
0
    def start(self):
        print("Starting MRI_FID_Widget")

        # send 1 as signal to start MRI_FID_Widget
        gsocket.write(struct.pack('<I', 1))

        # enable/disable GUI elements
        self.startButton.setEnabled(False)
        self.stopButton.setEnabled(True)
        self.applyFreqButton.setEnabled(True)
        self.gradOffset_x.setEnabled(True)
        self.gradOffset_y.setEnabled(True)
        self.gradOffset_z.setEnabled(True)
        self.gradOffset_z2.setEnabled(True)
        self.acquireButton.setEnabled(True)
        self.saveShimButton.setEnabled(True)
        self.loadShimButton.setEnabled(True)
        self.zeroShimButton.setEnabled(True)
        self.openFlipangletoolBtn.setEnabled(True)

        # setup global socket for receive data
        gsocket.setReadBufferSize(8 * self.size)
        gsocket.readyRead.connect(self.read_data)

        # send the sequence to the backend
        ass = Assembler()
        seq_byte_array = ass.assemble(self.seq_filename)
        print(len(seq_byte_array))
        gsocket.write(struct.pack('<I', len(seq_byte_array)))
        gsocket.write(seq_byte_array)

        self.load_shim()
        self.idle = False
Exemplo n.º 10
0
    def start(self):
        print("Starting MRI_SE_Widget")

        # send 2 as signal to start MRI_SE_Widget
        gsocket.write(struct.pack('<I', 2))

        # enable/disable GUI elements
        self.startButton.setEnabled(False)
        self.stopButton.setEnabled(True)
        self.gradOffset_x.setEnabled(True)
        self.gradOffset_y.setEnabled(True)
        self.gradOffset_z.setEnabled(True)
        self.gradOffset_z2.setEnabled(True)
        self.acquireButton.setEnabled(True)
        self.saveShimButton.setEnabled(True)
        self.loadShimButton.setEnabled(True)
        self.zeroShimButton.setEnabled(True)
        self.zoomCheckBox.setEnabled(True)
        self.peakWindowCheckBox.setEnabled(True)

        self.cycAcqBtn.setEnabled(False)
        self.cyclesValue.setEnabled(False)

        # setup global socket for receive data
        gsocket.readyRead.connect(self.read_data)

        # send the sequence to the backend
        ass = Assembler()
        seq_byte_array = ass.assemble(self.seq_filename)
        print(len(seq_byte_array))
        gsocket.write(struct.pack('<I', len(seq_byte_array)))
        gsocket.write(seq_byte_array)

        self.load_shim()
        self.idle = False
Exemplo n.º 11
0
def experiment01():
    """
    Compute the quantity of interest, it's expectation and variance
    """
    #
    # FE Discretization
    #

    # Computational mesh
    mesh = Mesh1D(resolution=(64, ))

    # Element
    element = QuadFE(mesh.dim(), 'DQ0')
    dofhandler = DofHandler(mesh, element)
    dofhandler.distribute_dofs()

    # Linear Functional
    mesh.mark_region('integrate',
                     lambda x: x > 0.75,
                     entity_type='cell',
                     strict_containment=False)
    phi = Basis(dofhandler)
    assembler = Assembler(Form(1, test=phi, flag='integrate'))
    assembler.assemble()
    L = assembler.get_vector()
Exemplo n.º 12
0
    def test_assemble_iiform(self):

        mesh = Mesh1D(resolution=(1, ))

        Q1 = QuadFE(1, 'DQ1')
        dofhandler = DofHandler(mesh, Q1)
        dofhandler.distribute_dofs()

        phi = Basis(dofhandler, 'u')

        k = Explicit(lambda x, y: x * y, n_variables=2, dim=1)
        kernel = Kernel(k)

        form = IIForm(kernel, test=phi, trial=phi)

        assembler = Assembler(form, mesh)
        assembler.assemble()
        Ku = Nodal(lambda x: 1 / 3 * x, basis=phi)

        #af = assembler.af[0]['bilinear']
        M = assembler.get_matrix().toarray()

        u = Nodal(lambda x: x, basis=phi)
        u_vec = u.data()
        self.assertTrue(np.allclose(M.dot(u_vec), Ku.data()))
Exemplo n.º 13
0
    def set_IR(
        self,
        TI=15
    ):  #, REC=1000): # Function to modify SE -- call whenever acquiring a SE

        params.ti = TI
        self.change_IR(params.ti, self.seq_ir)  #, REC)

        self.assembler = Assembler()
        byte_array = self.assembler.assemble(self.seq_ir)

        # Implement new concept:
        # com.set_sequence(byte_array)

        socket.write(struct.pack('<I', 4 << 28))
        socket.write(byte_array)

        while (True):  # Wait until bytes written
            if not socket.waitForBytesWritten(): break

        socket.setReadBufferSize(8 * self.size)
        self.ir_flag = True
        self.se_flag = False
        self.fid_flag = False
        print("\nIR sequence uploaded with TI = ", TI,
              " ms.")  #" and REC = ", REC, " ms.")
Exemplo n.º 14
0
    def reset(self):
        ###
        #self.generate_routefile_two_intersections()
        self.generate_routefile()
        traci.load([
            "-c", "one_lane/one_lane4.sumocfg", "--collision.check-junctions",
            "1", "--start", '--no-step-log', 'true'
        ])

        ###
        #traci.load(["-c", "one_intersection_w_priority/one_intersection_w_priority.sumocfg", "--collision.check-junctions", "1", "--start"])

        run = Assembler(self.carID)

        terminate = False
        while terminate == False:

            num_vec = traci.vehicle.getIDList()
            for i in range(len(num_vec)):
                if num_vec[i] != 'ego':
                    traci.vehicle.setLaneChangeMode(num_vec[i], 512)
                    self.output = run.getTensor()
                    if self.output is not None:
                        terminate = True
            traci.simulationStep()

        return self.getObservation()
Exemplo n.º 15
0
 def lade_datei(self, datei):
     if (self.rechner!=None):
         asm = Assembler(self.rechner)
         asm.parse_datei(datei)
         self.rechner.lade_programm(asm.programm)
         return asm.tipps
     else:
         raise RuntimeError("Rechner muss erzeugt werden bevor Programm geladen wird")        
Exemplo n.º 16
0
    def test_assembler_translate(self):
        assembler = Assembler(asm_path=self.ADD_ASM_FILE)
        assembler._translate()

        result_file = open(assembler.hack_path, 'r')
        for result, expect in zip(result_file, HACK_CONTENT):
            with self.subTest(result=result, expect=expect):
                self.assertEqual(result.strip(), expect)
Exemplo n.º 17
0
def touch(f):
    click.echo(click.format_filename(f))
    fasta_parser = FASTAparser(f)
    parsed_sequences = fasta_parser.parse()
    assembler = Assembler(parsed_sequences)
    result = assembler.assemble()
    with open("result_assembled_sequence.txt", "w") as text_file:
        text_file.write(result)
Exemplo n.º 18
0
 def test_find_matching_pairs(self):
     from assembler import Assembler
     assbl = Assembler(sequences)
     a, b, c, d = assbl._find_matching_pairs()
     self.assertEqual(c, top_ranges_dict)
     self.assertEqual(d, bottom_ranges_dict)
     self.assertEqual(a, top_seq_dict)
     self.assertEqual(b, bottom_seq_dict)
Exemplo n.º 19
0
 def test_determine_order(self):
     from assembler import Assembler
     assbl = Assembler(sequences)
     c = top_ranges_dict
     d = bottom_ranges_dict
     a = top_seq_dict
     b = bottom_seq_dict
     o = assbl._determine_order(a,b,c,d)
     self.assertEqual(o, order)
Exemplo n.º 20
0
def test_pop_static():
    translator = VM2ASM(annotate=True, no_init=True)
    asm = translator.translate('pop static 1').dumps()
    Assembler().assemble(asm)
    print('pop static 1\n', asm)

    translator = VM2ASM(annotate=True, no_init=True)
    asm = translator.translate('pop static 0').dumps()
    Assembler().assemble(asm)
    print('pop static 0\n', asm)
Exemplo n.º 21
0
 def send_pulse(self, inp_file):
     ''' Sends the pulse sequence to the server '''
     # write a 3 to signal that the button has been pushed
     gsocket.write(struct.pack('<I', 3 << 28))
     ass = Assembler()
     btye_array = ass.assemble(inp_file)
     print("Byte array = {}".format(btye_array))
     print("Length of byte array = {}".format(len(btye_array)))
     gsocket.write(btye_array)
     print("Sent byte array")
Exemplo n.º 22
0
def touch(fasta_file, output_file, show):
    click.echo(click.format_filename(fasta_file))
    fasta_parser = FastaParser(fasta_file)
    fragments, fragment_ids = fasta_parser.parse()
    assembler = Assembler(fragments,
                          fragment_ids,
                          print_fragment_id_order=show)
    assembled = assembler.assemble()
    with open(output_file, "w") as text_file:
        text_file.write(assembled)
Exemplo n.º 23
0
def sample_qoi(q, dofhandler):
    """
    Sample total energy of output for a given sample of q's 
    """
    # 
    # Set up weak form 
    # 
    
    # Basis 
    phi   = Basis(dofhandler, 'v')
    phi_x = Basis(dofhandler, 'vx')
       
    # Elliptic problem
    problems = [[Form(q, test=phi_x, trial=phi_x), Form(1, test=phi)],
                [Form(1, test=phi, trial=phi)]]
    
    # Assemble
    assembler = Assembler(problems, mesh)
    assembler.assemble()
    
    # System matrices
    A = assembler.af[0]['bilinear'].get_matrix()
    b = assembler.af[0]['linear'].get_matrix()
    M = assembler.af[1]['bilinear'].get_matrix()
    
    # Define linear system
    system = LS(phi)
    system.add_dirichlet_constraint('left',1)
    system.add_dirichlet_constraint('right',0)
    
    n_samples = q.n_samples()
    y_smpl = []
    QoI_smpl = []
    for i in range(n_samples):
        # Sample system 
        if n_samples > 1:
            Ai = A[i]
        else:
            Ai = A
        system.set_matrix(Ai)
        system.set_rhs(b.copy())
        
        # Solve system
        system.solve_system()
        
        # Record solution and qoi
        y = system.get_solution(as_function=False)
        y_smpl.append(y)
        QoI_smpl.append(y.T.dot(M.dot(y)))
    
    # Convert to numpy array    
    y_smpl = np.concatenate(y_smpl,axis=1)
    QoI = np.concatenate(QoI_smpl, axis=1).ravel()
    
    return y_smpl, QoI
Exemplo n.º 24
0
    def ensamblar(self):

        if not self.fileOpener(): return

        ens = Assembler(self.filename)
        ens.leerArchivo()

        try:
            ens.first_pass()
            ens.Second_pass()
            ens.print_tabla()
        except Exception as ex:
            self.newWindow = tk.Toplevel(self.master)
            self.pop = PopUP(self.newWindow)
            self.pop.addMessage("Error", str(ex))
            return

        fileOut = open(self.directory + "out.obj", "w+")
        for line in ens.CO:
            fileOut.write(line + "\n")
        fileOut.close()

        self.newWindow = tk.Toplevel(self.master)
        self.pop = PopUP(self.newWindow)
        self.pop.addMessage("Información",
                            "Archivo .obj creado en: \n" + self.directory)
Exemplo n.º 25
0
def content():
    data = request.form['data']
    ass = Assembler(data)
    ass.gen_bin_instructions()
    c = Computer()
    program_start, end = ass.load(c.ram)
    c.run(program_start)
    return jsonify({
        'assembler': ass.show_ins_table(),
        'run': c.ram.show_relevant(program_start, end),
        'storage': show_bin_rep(data)
    })
Exemplo n.º 26
0
    def execute(self, action):
        #traci.vehicle.setSpeedMode('ego', 0)
        #print(action)
        run = Assembler(self.carID)

        # self.output = tensor.executeTensor()
        self.output = run.getTensor()
        # print(self.output)
        if self.output is None:
            term = True
            return self.getObservation(), term, 0
        # rew = Reward('ego', self.output)
        rew = Reward('ego')

        coll, term = rew.collision()
        if term is True:
            cost = coll
            return self.getObservation(), term, cost

        traci.vehicle.setSpeedMode('ego', 0)
        num_vec = traci.vehicle.getIDList()
        for i in range(len(num_vec)):
            if num_vec[i] != 'ego':
                traci.vehicle.setLaneChangeMode(num_vec[i], 512)
        # print(action)
        carID = 'ego'
        act = Action(carID)
        if action == 0:
            pass
            #act.decelerate()
            #print('dec')
        elif action == 1:
            pass
            #act.accelerate()
            #print('acc')
        else:
            pass
            #act.remain()
            #print('rem')
        traci.simulationStep()

        #net = sumolib.net.readNet('huge_crossing/huge_crossing.net.xml')
        #tensor = Tensor('ego', net, self.conflictory_list[0], self.connection_list[0])
        #self.output = tensor.executeTensor()
        #rew = Reward('ego', self.output)

        win = rew.target()
        cost = rew.optimum_speed_deviation() + win
        # + brake
        traci.simulationStep()

        return self.getObservation(), term, cost
Exemplo n.º 27
0
class InputBuilder(object):

    def __init__(self, biodb_selector, fam_path, index_col= "Name", calculation_type="sum"):
        self.biodb_selector= biodb_selector
        self.abundance_frame= read_csv(fam_path, sep= '\t', index_col=index_col)
        self.abundance= self.abundance_frame.T.mean()
        self.assembler= Assembler(biodb_selector, self.abundance, calculation_type)
        self.assembler.assemble_ideograms()
        self.io_worker= IOWorker(self.assembler)

    def build_circos_inputs_and_run(self, plots=None, links=None, highlights=None):
        """
            pathway names will be added
        """

        self.io_worker.build_links(links)
        self.io_worker.build_highlights(highlights)
        self.io_worker.edit_plots_config(plots)

        self.io_worker.build_karyotype()
        self.io_worker.build_text()
        self.io_worker.build_pathway_names()
        self.io_worker.build_data()
        
        self.save_settings(plots, links, highlights)
        self.run_circos()

    def save_settings(self, plots, links, highlights):
        plots.dump()
        links.dump()
        highlights.dump()

    def run_circos(self):
        circos_file= file_provider['output']['circos_png']
        config= file_provider['circos_config']['conf']
        out_dir = os.path.dirname(circos_file)
        out_file= os.path.basename(circos_file)

        circos_bin= file_provider['circos']['bin']
        cmd_args= ['perl', circos_bin,'--conf',  config,' --outputdir', out_dir,  '--outputfile', out_file]
        cmd= ' '.join(cmd_args)
        print "Running circos...", cmd
        p= subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr= subprocess.PIPE)
        #p= subprocess.Popen(cmd_args)
        output, err= p.communicate()
        print output
        print "#####"
        print err
        return output

    def build_optionals(self):
        pass
Exemplo n.º 28
0
def test_compat():
    ASM.set_compat(True)
    asm = EQ_Operation(compat=True).resolve()
    Assembler(compat=True).assemble(str(asm))

    try:
        ASM.set_compat(False)
        asm = EQ_Operation().resolve()
        Assembler(compat=True).assemble(str(asm))
    except:
        pass
    else:
        assert False, 'Should have failed'
Exemplo n.º 29
0
 def _reset(self, mpu_type, getc_addr=0xF004, putc_addr=0xF001):
     self._mpu = mpu_type(memory=self.memory)
     self.addrWidth = self._mpu.ADDR_WIDTH
     self.byteWidth = self._mpu.BYTE_WIDTH
     self.addrFmt = self._mpu.ADDR_FORMAT
     self.byteFmt = self._mpu.BYTE_FORMAT
     self.addrMask = self._mpu.addrMask
     self.byteMask = self._mpu.byteMask
     if getc_addr and putc_addr:
         self._install_mpu_observers(getc_addr, putc_addr)
     self._address_parser = AddressParser()
     self._disassembler = Disassembler(self._mpu, self._address_parser)
     self._assembler = Assembler(self._mpu, self._address_parser)
Exemplo n.º 30
0
def main():
    try:
        filename = sys.argv[1]  #"test_file.vbs"
    except IndexError:
        print("This program needs an input .vbs file to continue. Exiting...")
        sys.exit(1)

    with open(filename, 'r') as file:
        code = file.read()
    Parser.run(code)
    Assembler.write_file()

    os.system("nasm -f elf32 -F dwarf -g program.asm ")
    os.system("ld -m elf_i386 -o program program.o")
    os.system("./program")
Exemplo n.º 31
0
    def set_2dSE(
        self
    ):  # Function to init and set FID -- only acquire call is necessary afterwards

        self.assembler = Assembler()
        byte_array = self.assembler.assemble(self.seq_2dSE)
        socket.write(struct.pack('<I', 4 << 28))
        socket.write(byte_array)

        while (True):  # Wait until bytes written
            if not socket.waitForBytesWritten():
                break

        socket.setReadBufferSize(8 * self.size)
        print("\n2D SE sequence uploaded.")
Exemplo n.º 32
0
    def set_SIR(self, TI=15):

        params.ti = TI
        #self.change_SIR(params.ti, self.seq_sir)
        self.assembler = Assembler()
        byte_array = self.assembler.assemble(self.seq_sir)
        socket.write(struct.pack('<I', 4 << 28))
        socket.write(byte_array)

        while (True):  # Wait until bytes written
            if not socket.waitForBytesWritten(): break

        socket.setReadBufferSize(8 * self.size)
        print("\nSIR sequence uploaded with TI = ", TI,
              " ms.")  #" and REC = ", REC, " ms.")
Exemplo n.º 33
0
    def execute(self, action):
        run = Assembler(self.carID)

        self.output = run.getTensor()
        #print(run.getTensor())

        if self.output is None:
            term = True
            return self.getObservation(), term, 0

        rew = Reward('ego', run.getTraffic(), self.output)

        coll, term = rew.collision()
        if term is True:
            cost = coll
            return self.getObservation(), term, cost

        traci.vehicle.setSpeedMode('ego', 0)
        num_vec = traci.vehicle.getIDList()
        for i in range(len(num_vec)):
            if num_vec[i] != 'ego':
                traci.vehicle.setLaneChangeMode(num_vec[i], 512)

            ###
            #if i % 2 == 0:
            #traci.vehicle.setSpeedMode(num_vec[i], 23)

        carID = 'ego'
        act = Action(carID)
        if action == 0:
            act.decelerate()
            # print('dec')
        elif action == 1:
            act.accelerate()
            # print('acc')
        else:
            act.remain()
            # print('rem')
        gap, term = rew.emergency_gap()
        wary = rew.wary_before_intersection()

        #win = rew.target()
        brake = rew.emergency_brake()
        cost = rew.optimum_speed_deviation() + brake + gap + wary
        traci.simulationStep()
        #print(self.output)

        return self.getObservation(), term, cost
Exemplo n.º 34
0
 def upload_seq(self):
     ''' Takes an input text file, compiles it to machine code '''
     dialog = QFileDialog()  # open a Dialog box to take the file
     fname = dialog.getOpenFileName(None, "Import Pulse Sequence", "",
                                    "Text files (*.txt)")
     # returns a tuple, fname[0] is filename(including path), fname[1] is file type
     inp_file = fname[0]
     print("Uploading sequence to server")
     try:
         ass = Assembler()
         self.upload_seq_byte_array = ass.assemble(inp_file)
         self.uploadSeq.setText(inp_file)
     except IOError as e:
         print("Error: required txt file doesn't exist")
         return
     print("Uploaded successfully to server")
Exemplo n.º 35
0
 def __init__(self, biodb_selector, fam_path, index_col= "Name", calculation_type="sum"):
     self.biodb_selector= biodb_selector
     self.abundance_frame= read_csv(fam_path, sep= '\t', index_col=index_col)
     self.abundance= self.abundance_frame.T.mean()
     self.assembler= Assembler(biodb_selector, self.abundance, calculation_type)
     self.assembler.assemble_ideograms()
     self.io_worker= IOWorker(self.assembler)
Exemplo n.º 36
0
    def set_uploaded_seq(self, seq):
        print("Set uploaded Sequence.")
        self.assembler = Assembler()
        byte_array = self.assembler.assemble(seq)
        socket.write(struct.pack('<I', 4 << 28))
        socket.write(byte_array)

        while (True):  # Wait until bytes written
            if not socket.waitForBytesWritten():
                break

        # Multiple function calls
        socket.setReadBufferSize(8 * self.size)
        print(byte_array)
        print("Sequence uploaded to server.")
        self.uploaded.emit(True)
Exemplo n.º 37
0
 def runTest(self):
     self.assembler = Assembler()
     self.test_reg_to_binary()
     self.test_int_to_binary()
     self.test_twos_complement()
     self.test_binary_to_hex()
     self.test_command()
     self.test_command2()
Exemplo n.º 38
0
def main(args):
   if len(args) != 2:
      print "USAGE:", args[0], "program.asm"
      print "\tprogram.asm is the source asm file"
      print "\tA hack file will be created from the source file."
      print "\tThe output file will use the same prefix as the source, but"
      print "\tthe extension will be .hack"
      sys.exit(1)

   # the source filename
   source_filename = args[1]

   # create the assembler and assemble the code
   try:
      assembler = Assembler(source_filename)
      assembler.assemble()
   except IOError:
      print "ERROR: Could not open source file or error writing to destination"
Exemplo n.º 39
0
class Streamer:
	#Global variables
	fo = open('authentication.txt')
	lines = [str(line.rstrip('\n')) for line in fo]
	consumer_key = lines[0]
	consumer_secret = lines[1]
	access_token = lines[2]
	access_token_secret = lines[3]
	fo.close()

	# OAuth process, using the keys and tokens
	auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
	auth.set_access_token(access_token, access_token_secret)

	# Creation of the actual interface, using authentication
	api = tweepy.API(auth)

	def __init__(self):
		self.assembler = Assembler()
		self.wrapper = Wrapper()
	
	def priceupdate(self, base, mid, quote):
		timestamp = datetime.fromtimestamp(time.time())
		rates = self.assembler.assemble(base, mid, quote)
		base_per_mid, mid_per_quote = rates[0], rates[1]
		last_update = self.wrapper.c.execute("SELECT * FROM Prices ORDER BY year DESC, month DESC, day DESC, hour DESC, minute DESC").fetchone()
		new_price = base_per_mid*mid_per_quote
		last_price = last_update[5]*last_update[6]
		delta = new_price/last_price - 1
		self.wrapper.update_price_db(timestamp, base_per_mid, mid_per_quote)
		if delta >= 0:
			return '[%s CST]: The average #dogecoin price is now $%.6f, +%.1f%% growth wow (%.2f bits)' \
			% (timestamp.strftime('%m-%d %H:%M'), new_price, delta*100, base_per_mid*(1000000))
		else:
			return '[%s CST]: The average #dogecoin price is now $%.6f, %.1f%% decline (%.2f bits)' \
			% (timestamp.strftime('%m-%d %H:%M'), new_price, delta*100, base_per_mid*(1000000))	
		
		#return '[%s CST]: The average #dogecoin price is now $%.6f (%.2f bits)' \
		#% (timestamp.strftime('%m-%d %H:%M'), new_price, base_per_mid*(1000000))
		#return '[%s CST]: The average dogecoin price is now %.2f bits ($%.6f).\n$1 = Ð%.2f\n1BTC = Ð%d' % (datetime.fromtimestamp(time.time()).strftime('%m-%d %H:%M:%S'), dogebtcprice, dogeusdprice, 1/dogeusdprice, dogebtcprice*100000)

	#Continuous price stream
	def stream(self):
		print 'Initiating Dogecoin Price Stream --------------------------'
		while True:
			try:
				tweet = self.priceupdate('DOGE', 'BTC', 'USD')
				self.api.update_status(tweet)
				print tweet
				print 'Tweeted successfully'
			except Exception, e:
				print str(e)
			time.sleep(3570)
Exemplo n.º 40
0
class AssemblerTest(unittest.TestCase):

    def runTest(self):
        self.assembler = Assembler()
        self.test_reg_to_binary()
        self.test_int_to_binary()
        self.test_twos_complement()
        self.test_binary_to_hex()
        self.test_command()
        self.test_command2()

    # Tests the register to binary method
    def test_reg_to_binary(self):
        input = "r3"
        expected = "0011"
        result = self.assembler.reg_to_binary(input, 4)
        self.assertEqual(expected, result)

    # Tests the integer to binary method
    def test_int_to_binary(self):
        input = 15
        expected = "1111"
        result = self.assembler.int_to_binary(input, 4)
        self.assertEqual(expected, result)

    # Tests the two's complement method
    def test_twos_complement(self):
        input = "0000010001110001"
        expected = "1111101110001111"
        result = self.assembler.twos_complement(input, 16)
        self.assertEqual(expected, result)

    # Tests the binary to hexadecimal method
    def test_binary_to_hex(self):
        input = "000101100001111100111110"
        expected = "161f3e"
        result = self.assembler.binary_to_hex(input)
        self.assertEqual(expected, result)

    # Tests a compare command
    def test_command(self):
        input = Command(["cmp", "r2", "r3"], 10, "0010")
        expected = "\t10\t\t\t:\t32012e;"
        result = self.assembler.r_type(input)
        self.assertEqual(expected, result)

    # Tests a load immediate command
    def test_command2(self):
        input = Command(["li", "r3", "31"], 10, "0000")
        expected = "\t10\t\t\t:\t3001f2;"
        result = self.assembler.j_type(input)
        self.assertEqual(expected, result)
Exemplo n.º 41
0
 def on_start_button_clicked(self, widget):
     finalfile = self.x[0].split('.')[0] + '.8085'
     info = self.shell_ui.get_object("start_info_label")
     # str1 = ''
     # str1 += 'Interpreting...........\nRunning Assembler \n'
     # info.set_text(str1)
     self.assembler_instance = Assembler(self.shell_ui)
     self.assembler_instance.test(self.x)
     # str1 = str1 + 'Assembler Completed \n' + 'Running Linker \n'
     # info.set_text(str1)
     self.linker_instance = Linker(self.shell_ui, self.assembler_instance.symTable,
                                   self.assembler_instance.globTable,
                                   self.assembler_instance.filelen)
     self.linker_instance.linker(self.x)
     # str1 = str1 + 'Linker Completed \n' + 'Set offset and run loader\n'
     # info.set_text(str1)
     self.loader_instance = Loader(self.shell_ui)
     self.loader_instance.loader(self.x)
Exemplo n.º 42
0
from assembler import Assembler

# Runs the assembler. First it prompts the user for
# input and output file names. The input file should
# be .s or .asm. The output files should be .mif.
# Then it runs the assembler. If an exception is
# raised, it is caught and the error message is
# printed.

program = Assembler()

filename = input("\nEnter the input file name: ")
file_out = input("Enter the output file name: ")

ascii = [
    "Assembling...\n\n"
    "	   .-\"\"-.",
    "	  /[] _ _\\",
    "	 _|_o_LII|_",
    "	/ | ==== | \\ 	BEEP BOOP",
    "	|_| ==== |_|	BLOP BLEEP",
    "	 ||  ||  ||	BOOP!",
    "	 ||LI  o ||",
    "	 ||'----'||",
    "	/__|    |__\\"
]

try:
    file = open(filename)
    code = file.readlines()
    output = program.compile(code)
Exemplo n.º 43
0
#!/usr/bin/python2.6

from assembler import Assembler
from sys import argv

#only care about the first argument.
if(None == argv[1]):
    print("No input file specified.")
    exit(255)

file = argv[1]
assembler = Assembler(file)
#assembler.symbol_less_assembly()
assembler.two_pass_assembly()
Exemplo n.º 44
0
class Converter:
	#Global variables
	fo = open('authentication.txt')
	lines = [str(line.rstrip('\n')) for line in fo]
	consumer_key = lines[0]
	consumer_secret = lines[1]
	access_token = lines[2]
	access_token_secret = lines[3]
	fo.close()

	# OAuth process, using the keys and tokens
	auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
	auth.set_access_token(access_token, access_token_secret)

	# Creation of the actual interface, using authentication
	api = tweepy.API(auth)

	#All 168 foreign currencies able to be converted via bitcoinaverage
	#Bypasses openexchangerates.org
	currency_codes = ['AED' , 'AFN' , 'ALL' , 'AMD' , 'ANG' , 'AOA' , 'ARS' , 'AUD' , 'AWG' ,\
				      'AZN' , 'BAM' , 'BBD' , 'BDT' , 'BGN' , 'BHD' , 'BIF' , 'BMD' , 'BND' ,\
				      'BOB' , 'BRL' , 'BSD' , 'BTC' , 'BTN' , 'BWP' , 'BYR' , 'BZD' , 'CAD' ,\
				      'CDF' , 'CHF' , 'CLF' , 'CLP' , 'CNY' , 'COP' , 'CRC' , 'CUP' , 'CVE' ,\
				      'CZK' , 'DJF' , 'DKK' , 'DOP' , 'DZD' , 'EEK' , 'EGP' , 'ERN' , 'ETB' ,\
				      'EUR' , 'FJD' , 'FKP' , 'GBP' , 'GEL' , 'GGP' , 'GHS' , 'GIP' , 'GMD' ,\
				      'GNF' , 'GTQ' , 'GYD' , 'HKD' , 'HNL' , 'HRK' , 'HTG' , 'HUF' , 'IDR' ,\
				      'ILS' , 'IMP' , 'INR' , 'IQD' , 'IRR' , 'ISK' , 'JEP' , 'JMD' , 'JOD' ,\
				      'JPY' , 'KES' , 'KGS' , 'KHR' , 'KMF' , 'KPW' , 'KRW' , 'KWD' , 'KYD' ,\
				      'KZT' , 'LAK' , 'LBP' , 'LKR' , 'LRD' , 'LSL' , 'LTL' , 'LVL' , 'LYD' ,\
				      'MAD' , 'MDL' , 'MGA' , 'MKD' , 'MMK' , 'MNT' , 'MOP' , 'MRO' , 'MTL' ,\
				      'MUR' , 'MVR' , 'MWK' , 'MXN' , 'MYR' , 'MZN' , 'NAD' , 'NGN' , 'NIO' ,\
				      'NOK' , 'NPR' , 'NZD' , 'OMR' , 'PAB' , 'PEN' , 'PGK' , 'PHP' , 'PKR' ,\
				      'PLN' , 'PYG' , 'QAR' , 'RON' , 'RSD' , 'RUB' , 'RWF' , 'SAR' , 'SBD' ,\
				      'SCR' , 'SDG' , 'SEK' , 'SGD' , 'SHP' , 'SLL' , 'SOS' , 'SRD' , 'STD' ,\
				      'SVC' , 'SYP' , 'SZL' , 'THB' , 'TJS' , 'TMT' , 'TND' , 'TOP' , 'TRY' ,\
				      'TTD' , 'TWD' , 'TZS' , 'UAH' , 'UGX' , 'USD' , 'UYU' , 'UZS' , 'VEF' ,\
				      'VND' , 'VUV' , 'WST' , 'XAF' , 'XAG' , 'XAU' , 'XCD' , 'XDR' , 'XOF' ,\
				      'XPF' , 'YER' , 'ZAR' , 'ZMK' , 'ZMW' , 'ZWL']

	#Expanding to other cryptocurrencies in v1.7
	cryptocurrency_codes = []

	def __init__(self):
		self.assembler = Assembler()
		self.wrapper = Wrapper()

	def populate_db(self):
		for mention in self.api.mentions_timeline():
			self.wrapper.update_mentions_db(mention.user.screen_name, mention.id, mention.text)
	
	#Return True if mention is a duplicate, False otherwise
	def no_duplicates(self, mention):
		command = "SELECT * FROM Mentions WHERE id = %d" % (mention.id)
		duplicates = self.wrapper.c.execute(command).fetchall()
		if len(duplicates) == 0:
			return True
		return False

	def insert_into_db(self, mention):
		self.wrapper.update_mentions_db(mention.user.screen_name, mention.id, mention.text)

	def convert(self, mention):
		if self.no_duplicates(mention):
			user = mention.user.screen_name
			#Textual trigger
			if '@dogepricebot convert' in mention.text.lower():
				print "Found conversion request"
				print user+" : "+mention.text
				words = mention.text.lower().split(" ")
				command_start = words.index('@dogepricebot')
				amount, base, quote = float(words[command_start+2]), words[command_start+3], words[command_start+5]
				if base.lower() == "dogecoin" or base.lower() == "doge":
					rates = self.assembler.assemble(quote.upper())
					rate = rates[0]*rates[1]
					tweet = '@%s wow such convert: %.1f #dogecoin = %.2f %s' % (user, amount, amount*rate, quote.upper())
					print tweet
					self.api.update_status(tweet)
				else:
					rates = self.assembler.assemble(base.upper())
					rate = rates[0]*rates[1]
					tweet = '@%s wow such convert: %.1f %s = %.2f #dogecoin' % (user, amount, base.upper(), amount/rate)
					print tweet
					self.api.update_status(tweet)
			self.insert_into_db(mention)
		else:
			print "duplicate"

	#Continuous price stream
	def listen(self):
		print 'Listening for @dogepricebot convert requests --------------------------'
		while True:
			for mention in self.api.mentions_timeline(count=10):
				try:
					self.convert(mention)
				except Exception, e:
					print "In exception"
					print str(e)
			time.sleep(300)
Exemplo n.º 45
0
def main(fname):
    a = Assembler()
    p = a.parse(fname)
    with open(fname.split('.')[0], 'wb') as f:
        f.write(bytearray(p))
Exemplo n.º 46
0
	def __init__(self):
		self.assembler = Assembler()
		self.wrapper = Wrapper()
Exemplo n.º 47
0
class AssemblerTest(unittest.TestCase):
    def setUp(self):
        self.assembler = Assembler()

    def test_instance(self):
        thing = object()
        self.assembler.instance('thing', thing)
        result = self.assembler.assemble('thing')
        self.assertEqual(thing, result)

    def test_factory(self):
        def thing_maker():
            return object()
        self.assembler.factory('thing', thing_maker)
        result1 = self.assembler.assemble('thing')
        self.assertTrue(isinstance(result1, object))
        result2 = self.assembler.assemble('thing')
        self.assertTrue(isinstance(result2, object))
        self.assertNotEqual(result1, result2)

    def test_assemble_with_args(self):
        def thing_maker(one, two):
            return [one, two]
        self.assembler.factory('thing', thing_maker)
        result = self.assembler.assemble('thing', 'one', 'two')
        self.assertEqual(['one', 'two'], result)

    def test_assemble_with_kwargs(self):
        def thing_maker(one, two):
            return [one, two]
        self.assembler.factory('thing', thing_maker)
        result = self.assembler.assemble('thing', two='one', one='two')
        self.assertEqual(['two', 'one'], result)

    def test_assemble_with_args_and_kwargs(self):
        def thing_maker(one, two, a=None, b=None):
            return [one, two, (a, b)]
        self.assembler.factory('thing', thing_maker)
        result = self.assembler.assemble('thing', 'one', 'two', b='b', a='a')
        self.assertEqual(['one', 'two', ('a', 'b')], result)

    def test_assemble_with_defaults(self):
        def thing_maker(one='one', two='two', a='a', b='b'):
            return [one, two, (a, b)]
        self.assembler.factory('thing', thing_maker)
        result = self.assembler.assemble('thing')
        self.assertEqual(['one', 'two', ('a', 'b')], result)

    def test_recursive_assemble(self):
        def thing1_maker(thing2):
            return thing2

        def thing2_maker():
            return 'instance of thing2'
        self.assembler.factory('thing1', thing1_maker)
        self.assembler.factory('thing2', thing2_maker)
        result = self.assembler.assemble('thing1')
        self.assertEqual('instance of thing2', result)

    def test_class_constructors(self):
        class A(object):
            def __init__(self, b, c):
                self.b = b
                self.c = c

        class B(object):
            def __init__(self):
                pass

        class C(object):
            def __init__(self, d):
                self.d = d

        class D(object):
            def __init__(self):
                pass
        self.assembler.factory('a', A)
        self.assembler.factory('b', B)
        self.assembler.factory('c', C)
        self.assembler.factory('d', D)
        a = self.assembler.assemble('a')
        self.assertTrue(isinstance(a, A))
        self.assertTrue(hasattr(a, 'b'))
        self.assertNotEqual(None, a.b)
        self.assertTrue(isinstance(a.b, B))
        self.assertTrue(hasattr(a, 'c'))
        self.assertNotEqual(None, a.c)
        self.assertTrue(isinstance(a.c, C))
        self.assertTrue(hasattr(a.c, 'd'))
        self.assertNotEqual(None, a.c.d)
        self.assertTrue(isinstance(a.c.d, D))
Exemplo n.º 48
0
 def setUp(self):
     self.assembler = Assembler()
Exemplo n.º 49
0
def main(argv):
    if parse_args(argv):
        asm = Assembler(options)
        asm.run()
Exemplo n.º 50
0
#!/usr/bin/env python
import os
from assembler import Assembler
from optionresolver import OptionResolver
from patchers import PatchManager, PatchPatcher

# Get the user supplied options
options = OptionResolver()

# Assemble the source code
assembler = Assembler(options.manifest()["projects"], options.destination(), options.extra_parameters())
assembler.assemble()

# Apply any patches
patchmanager = PatchManager(options.manifest()["patches"], options.destination())
patch_base = os.path.dirname(options.manifest_location())
patchmanager.add_patcher("patch_file", PatchPatcher(patch_base))
patchmanager.patch()
Exemplo n.º 51
0
        self.pc = 2

        while self.pc < end and program[self.pc] != opset.HALT:
            instruction = program[self.pc]
            self.pc += 1
            if opset.nullary(instruction):
                self.debug("%02d %s", self.pc, opset.byte2name[instruction])
                self.nullary[instruction]()
            elif opset.unary(instruction):
                argument = program[self.pc]
                self.pc += 1
                self.debug("%02d %s %s", self.pc, opset.byte2name[instruction], argument)
                self.unary[instruction - opset.LIT](argument)

if __name__ == "__main__":
    from sys import argv
    from assembler import Assembler
    from argparser import parseArgs

    # Grab command line arguments
    args = parseArgs()

    try:
        asm = Assembler(args.debug)
        vm = VirtualMachine(args.debug)
        vm.run(asm.assemble(open(args.filename)))
    except Exception as e:
        print(e)

# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
Exemplo n.º 52
0
class AllApp(Gtk.Application):
    # constructor of the Gtk Application

    def __init__(self):
        Gtk.Application.__init__(self)
        self.shell_ui = Gtk.Builder()
        self.shell_ui.add_from_file("shell.glade")
        self.handler_dict = {
            "on_start_file_chooser_button_clicked": self.on_start_file_chooser_button_clicked,
            "on_start_button_clicked": self.on_start_button_clicked,
            "on_simulator_open_file_button_clicked": self.on_simulator_open_file_button_clicked,
            "on_simulate_pass_button_clicked": self.on_simulate_pass_button_clicked,
            "on_run_button_clicked": self.on_run_button_clicked,
            "on_quit_image_menu_item_activate": self.on_quit_activate,
            "on_offset_button_clicked": self.on_offset_button_clicked
        }
        self.shell_ui.connect_signals(self.handler_dict)
        self.x = []
        self.z = []
        self.assembler_instance = None
        self.loader_instance = None
        self.linker_instance = None
        self.simulator_instance = None
        # self.simulator=Simulator()

    def on_offset_button_clicked(self, widget):
        self.loader_instance.loader2(self.x)

    def do_activate(self):
        window = self.shell_ui.get_object("all_window")
        self.add_window(window)
        window.show_all()

    def on_start_file_chooser_button_clicked(self, widget):
        window = self.shell_ui.get_object("all_window")
        dialog = Gtk.FileChooserDialog(title="Please choose a file", parent=window, action=Gtk.FileChooserAction.OPEN,
                                       buttons=(
                                           Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
                                           Gtk.ResponseType.OK))
        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            selected_file_path = dialog.get_filename()
            relative_path = os.path.basename(selected_file_path)
            inputfile = open(relative_path, "r")
            code = inputfile.read()
            lines = code.split('\n')
            finalfile = lines[0].split('.')[0] + '.8085'
            print(lines[0].split('.')[0])
            print(finalfile)

            entries_box = self.shell_ui.get_object("start_entries_box")
            wids = entries_box.get_children()
            for widget in wids:
                widget.destroy()
            i = 0
            print (lines)
            for line in lines:
                if line != '':
                    self.z.append(line)
                    label = Gtk.Label("Code" + str(i))
                    tv = Gtk.TextView()
                    tb = tv.get_buffer()
                    entries_box.add(label)
                    entries_box.add(tv)
                    i += 1
                    with open(line, "r") as file:
                        s = file.read()
                        tb.set_text(s)
                        print(s)
            self.shell_ui.get_object("start_entry_number_entry").set_text(str(i))
            entries_box.show_all()
            self.x = preprocess(self.z)
            processed_box = self.shell_ui.get_object("processed_box")
            i = 0
            for file_name in self.x:
                if file_name != '':
                    label = Gtk.Label("Code" + str(i))
                    tv = Gtk.TextView()
                    tb = tv.get_buffer()
                    processed_box.add(label)
                    processed_box.add(tv)
                    i += 1
                    with open(file_name, "r") as file:
                        s = file.read()
                        tb.set_text(s)
                        print(s)
            processed_box.show_all()
        elif response == Gtk.ResponseType.CANCEL:
            print("Cancel clicked")
        dialog.destroy()

    def on_start_button_clicked(self, widget):
        finalfile = self.x[0].split('.')[0] + '.8085'
        info = self.shell_ui.get_object("start_info_label")
        # str1 = ''
        # str1 += 'Interpreting...........\nRunning Assembler \n'
        # info.set_text(str1)
        self.assembler_instance = Assembler(self.shell_ui)
        self.assembler_instance.test(self.x)
        # str1 = str1 + 'Assembler Completed \n' + 'Running Linker \n'
        # info.set_text(str1)
        self.linker_instance = Linker(self.shell_ui, self.assembler_instance.symTable,
                                      self.assembler_instance.globTable,
                                      self.assembler_instance.filelen)
        self.linker_instance.linker(self.x)
        # str1 = str1 + 'Linker Completed \n' + 'Set offset and run loader\n'
        # info.set_text(str1)
        self.loader_instance = Loader(self.shell_ui)
        self.loader_instance.loader(self.x)
        # str1 = str1 + 'Loading Complete \n' + '\t\tFile ready to simulate.\n' + '\t\tFile name is : ' + finalfile + '\n'
        # info.set_text(str1)

    def on_simulator_open_file_button_clicked(self, widget):
        pass

    def on_simulate_pass_button_clicked(self, widget):
        finalfile = self.x[0].split('.')[0] + '.8085'
        self.simulator_instance = Simulator(self.shell_ui, self.shell_ui.get_object("all_window"))
        self.simulator_instance.load(finalfile)

    def on_run_button_clicked(self, widget):
        self.simulator_instance.callbackf()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def on_quit_activate(self, menu_item):
        sys.exit()
Exemplo n.º 53
0
def main():
    totalTime = 0.0
    startTime = time.time()

    parser = OptionParser("usage: %prog [options] src_file [src_file...]")
    parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Verbose output.")
    parser.add_option("-l", "--log", dest="logLevel", default=0, help="Print detailed log information.")
    parser.add_option("-t", "--test", action="store_true", dest="test", default=False, help="Run assembler test code.")
    parser.add_option("-d", "--debug", action="store_true", dest="debug", default=False, help="Turn on assembler debugging code.")
    parser.add_option("-s", "--syntax-only", action="store_true", dest="syntaxOnly", default=False, help="Exit after checking syntax.")
    (options, args) = parser.parse_args()

    if len(args) < 1:
        parser.error("At least one source file must be supplied!")
        sys.exit(1)

    sources = []
    for arg in args:
        sources.append(arg)
        if not os.path.isfile(arg):
            parser.error("File \"%s\" does not exist" % arg)
            sys.exit(1)

    buildname = os.path.basename(os.getcwd())
    
    firstfile = args[0]
    firstfilename = args[0].split('.')[0]
    
    listfile = open(firstfile + ".lst", 'w')
    symtabfile = open(firstfile + ".symtab", 'w')
    binfile = open(firstfile + ".bin", 'wb')
    logfile = None
    if options.logLevel > 0:
        logfile = open(firstfilename + ".log", 'w')

    context = Context(Architecture.AGC4_B2, listfile, binfile, options, int(options.logLevel), logfile)
    assembler = Assembler(context)
    context.assembler = assembler

    if options.debug:
        print "Build:", buildname 
        endTime = time.time()
        delta = endTime - startTime
        totalTime += delta
        print "Initialisation: %3.2f seconds" % delta

    assembler.info("Simple AGC Assembler, v0.1", source=False)
    assembler.info("", source=False)

    startTime = time.time()
    for arg in args:
        try:
            assembler.assemble(arg)
        except:
            print >>sys.stderr
            print >>sys.stderr, "EXCEPTION:"
            traceback.print_exc(file=sys.stderr)
            print >>sys.stderr, "Context:"
            print >>sys.stderr, context
            raise
    if options.debug:
        endTime = time.time()
        delta = endTime - startTime
        totalTime += delta
        print "Pass 1: %3.2f seconds" % delta

    context.saveCurrentBank()

    if options.syntaxOnly == False and context.errors == 0:
        assembler.info("Resolving symbols...", source=False)
        startTime = time.time()
        try:
            assembler.resolve()
        except:
            assembler.log(1, "EXCEPTION:\n%s" % context)
            raise
        if options.debug:
            endTime = time.time()
            delta = endTime - startTime
            totalTime += delta

    for record in assembler.context.records:
        record.printMessages()

    assembler.info("Writing listing...", source=False)
    startTime = time.time()
    print >>listfile
    print >>listfile, "Listing"
    print >>listfile, "-------"
    for record in assembler.context.records:
        print >>listfile, record
    if options.debug:
        endTime = time.time()
        delta = endTime - startTime
        totalTime += delta
        print "Write listing: %3.2f seconds" % delta

    if not options.syntaxOnly:
        assembler.info("Writing symbol table listing...", source=False)
        startTime = time.time()
        print >>listfile
        print >>listfile, "Symbol Table"
        print >>listfile, "------------"
        assembler.context.symtab.printTable(listfile)
        if options.debug:
            endTime = time.time()
            delta = endTime - startTime
            totalTime += delta
            print "Write symbol table listing: %3.2f seconds" % delta

    if not options.syntaxOnly and context.errors == 0:
        assembler.info("Writing symbol table...", source=False)
        startTime = time.time()
        assembler.context.symtab.write(symtabfile)
        if options.debug:
            endTime = time.time()
            delta = endTime - startTime
            totalTime += delta
            print "Write symbol table: %3.2f seconds" % delta

    if context.errors == 1:
        msg = "1 error, "
    else:
        msg = "%d errors, " % (context.errors)
    if context.warnings == 1:
        msg += "1 warning, "
    else:
        msg += "%d warnings, " % (context.warnings)
    assembler.info(msg, source=False)
    print msg

    if not options.syntaxOnly:
        if options.test:
            startTime = time.time()

            # FIXME: Temporary hack
            # Check generated symbols against the symtab generated by yaYUL.

            assembler.info("Checking symbol table against yaYUL version...", source=False)
            from artemis072_symbols import ARTEMIS_SYMBOLS
            from memory import MemoryType

            nsyms = assembler.context.symtab.getNumSymbols()
            check_nsyms = len(ARTEMIS_SYMBOLS.keys())
            assembler.info("Number of symbols: yaYUL=%d pyagc=%d" % (check_nsyms, nsyms), source=False)

            my_syms = []
            other_syms = []
            common_syms = []

            for sym in assembler.context.symtab.keys():
                if sym in ARTEMIS_SYMBOLS.keys():
                    common_syms.append(sym)
                else:
                    if sym != "FIXED":
                        my_syms.append(sym)

            for sym in ARTEMIS_SYMBOLS.keys():
                if sym not in assembler.context.symtab.keys():
                    if not sym.startswith('$') and sym != "'":
                        other_syms.append(sym)

            if len(my_syms) != 0 or len(other_syms) != 0:
                assembler.error("incorrect number of symbols, expected %d, got %d" % (check_nsyms, nsyms), source=False)

            if len(my_syms) > 0:
                assembler.error("symbols defined that should not be defined: %s" % my_syms, source=False)

            if len(other_syms) > 0:
                assembler.error("symbols not defined that should be defined: %s" % other_syms, source=False)

            errcount = 0
            bad_syms = {}

            for sym in common_syms:
                entry = assembler.context.symtab.lookup(sym)
                if entry == None:
                    assembler.error("symbol %-8s not defined" % entry, source=False)
                pa = entry.value
                aval = ARTEMIS_SYMBOLS[sym]
                if ',' in aval:
                    bank = aval.split(',')[0]
                    type = MemoryType.FIXED
                    if bank.startswith('E'):
                        bank = bank[1:]
                        type = MemoryType.ERASABLE
                    bank = int(bank, 8)
                    offset = int(aval.split(',')[1], 8)
                    check_pa = context.memmap.segmentedToPseudo(type, bank, offset, absolute=True)
                else:
                    check_pa = int(aval, 8)
                if pa != check_pa:
                    errcount += 1
                    bad_syms[pa] = (sym, check_pa)

            if errcount > 0:
                bad_addrs = bad_syms.keys()
                bad_addrs.sort()
                for pa in bad_addrs:
                    sym = bad_syms[pa][0]
                    check_pa = bad_syms[pa][1]
                    assembler.error("symbol %-8s defined as %06o %s, expected %06o %s" % (sym, pa, context.memmap.pseudoToSegmentedString(pa), check_pa, context.memmap.pseudoToSegmentedString(check_pa)), source=False)
                assembler.error("%d/%d symbols incorrectly defined" % (errcount, len(common_syms)), source=False)

            if options.debug:
                endTime = time.time()
                delta = endTime - startTime
                totalTime += delta
                print "Symbol checking: %3.2f seconds" % delta

            # FIXME: End of temporary hack

    if not options.syntaxOnly and context.errors == 0:
        assembler.info("Writing binary output...", source=False)
        startTime = time.time()
        ocode = ObjectCode(context)
        ocode.generateBuggers()
        ocode.write(binfile)
        if options.debug:
            endTime = time.time()
            delta = endTime - startTime
            totalTime += delta
            print "Binary generation: %3.2f seconds" % delta

        assembler.info("Writing rope usage...", source=False)
        startTime = time.time()
        print >>listfile
        print >>listfile
        print >>listfile, "Bank Usage"
        print >>listfile, "----------"
        print >>listfile
        ocode.writeUsage(listfile)
        if options.debug:
            endTime = time.time()
            delta = endTime - startTime
            totalTime += delta
            print "Rope usage: %3.2f seconds" % delta

        assembler.info("Writing rope image listing...", source=False)
        startTime = time.time()
        print >>listfile
        print >>listfile
        print >>listfile, "Rope Image Listing"
        print >>listfile, "------------------"
        print >>listfile
        ocode.writeListing(listfile)
        if options.debug:
            endTime = time.time()
            delta = endTime - startTime
            totalTime += delta
            print "Rope image listing: %3.2f seconds" % delta

    assembler.info("Done.", source=False)
    listfile.close()
    symtabfile.close()
    binfile.close()
    if logfile:
        logfile.close()

    if options.debug:
        print "Total time: %3.2f seconds" % totalTime

    print "Done."