def main(): try: while True: global estado global sac ## Initial State if estado == 0: sac = db.get_estadoI() db.update_estado(sac, 1) time.sleep(60) #ficheros.sobrescribir("sacNumero.txt",str(sac)) #ficheros.sobrescribir("estadoActual.txt",str(estado)) estado = db.get_estadoA(sac) ## Reading Relation of the unit with the codes if estado == 1: relacion = db.get_relationcodes(sac) db.update_estado(sac, 2) time.sleep(60) #ficheros.sobrescribir("sacNumero.txt",str(sac)) #ficheros.sobrescribir("estadoActual.txt",str(estado)) estado = db.get_estadoA(sac) ## Saving codes of the unit with the codes if estado == 2: for rela in relacion: name, codes = db.get_codes(rela) ficheros.sobrescribir(name, codes) db.update_estado(sac, 3) time.sleep(60) #ficheros.sobrescribir("sacNumero.txt",str(sac)) #ficheros.sobrescribir("estadoActual.txt",str(estado)) estado = db.get_estadoA(sac) importlib.reload(code) #importlib.reload(sql_connection)#solo si se altera time.sleep(60) ## Executing the specific function if estado == 3: code.code().doit(sac) time.sleep(1) #ficheros.sobrescribir("sacNumero.txt",str(sac)) #ficheros.sobrescribir("estadoActual.txt",str(estado)) estado = db.get_estadoA(sac) ## Reconfiguring the unit if estado == 4: estado = 0 sac = 0 #ficheros.sobrescribir("sacNumero.txt",str(sac)) #ficheros.sobrescribir("estadoActual.txt",str(estado)) db.update_estado(sac, 5) #Ending the unit activity ## Reset by pressing CTRL + C except KeyboardInterrupt: print("Measurement stopped by User") GPIO.cleanup() except: print("Error Inesperado: ", sys.exc_info()[0]) time.sleep(15)
def run(first_pass=True, st=None): if first_pass: st = symbol_table.symbol_table() input_file = sys.argv[1] output_file = sys.argv[2] #should be optional output_file = open(output_file, 'w') with open(input_file, 'r') as f: for line in f: if first_pass: current_line = parser.parse(line, st, first_pass) else: #parse line parsed_object = parser.parse(line, first_pass) #Look up corresponding code if not isinstance(parsed_object, commands.Comment): #Write to the file coded_instruction = code.code(parsed_object, st) output_file.write(coded_instruction + '\n') output_file.close() if first_pass: run(first_pass=False, st=st)
def __init__(self, file_name): ''' Opens the input file/stream and gets ready to parse it. ''' self.file_name = file_name self.symbol = symbol() self.current_command = "" self.file_ref = open(file_name, 'r+') self.code = code()
def test_code(): code.src_path = '..' # relative path for src subdir code.CODE = 'Python' computed = code.code(filename='apb') expected = '@@@CODE src/py/apb.py' assert computed == expected computed = code.code(filename='apb', from_regex='a =', to_regex='a + b') expected = '@@@CODE src/py/apb.py fromto: a =@a + b' assert computed == expected code.CODE = 'C++' computed = code.code(filename='apb') expected = '@@@CODE src/cpp/apb.cpp' assert computed == expected computed = code.code(filename='apb', from_regex='a =', to_regex='a + b') expected = '@@@CODE src/cpp/apb.cpp fromto: a =@a + b' assert computed == expected computed = code.code(filename='demo', language='C++') text = """ #include <iostream> using namespace std; int main() { a = 1; b = 2; cout << a + b; return 0; } """ computed = code.code(language='C++', code=text) expected = '!bc cppcod\n%s\n!ec' % text.strip() assert computed == expected
def codeimg(): codeobj = code() res = make_response(codeobj.output()) session["code"] = codeobj.str.lower() res.headers["content-type"] = "image/png" return res
def pushcode(self,c): if not self.code: self.code = code.code() self.code.push(c)
return binary.zfill(16) #Set Assembly File Here file_name="Add" file_data=open("Sample/"+file_name+".asm","r") #Read File line=file_data.readline() lines="" #Read Document and Blank Line, and Put Them onto List lines=file_data.read().strip().split("\n") file_data.close #Make Instances for parse, code, and symbolTable parser=pa.parser(lines) code=co.code() symboltable=st.symbolTable() #Address n=16 #Number of Sentense sen=1 #New Binary Hack File new_file=open("Results/"+file_name+".hack","wt") this_binary="0000000000000000" #Routine Until the Last Sentense while parser.hasMoreCommands(): #Read the Next Sentences parser.advance()
def testCode2(self): self.assertEqual(code.code(2), 4)
def testCode1(self): self.assertEqual(code.code(1), 2)
#!/usr/bin/env python # coding: UTF-8 from parser import parser from code import code from symtbl import symtbl import sys, re files = sys.argv[1:] while len(files): filename = files.pop(0) p = parser(filename) c = code() s = symtbl() nextVarAddress = 16 instAddress = 0 # create symbol-table while p.hasMoreCommands(): p.advance() if p.commandType() == 'L_COMMAND': if s.contains(p.symbol()): print "Error : contained label" else: s.addEntry(p.symbol(), instAddress) #print p.symbol(), instAddress elif p.commandType() == 'A_COMMAND': instAddress += 1 else: instAddress += 1 # create romdata
def code(self, request, context): response = code_pb2.Number() response.value = code.code(request.value) return response
def create_instance(c_instance): return code(c_instance)
def __init__(self, data_cursor): self.Cursor = cursor(data_cursor) self.CodeToExecute = code() self.GCodeToExecute = [] self.Tool = tools_point()
import greetingfile greetingfile.greeting() import code code.code() import mymodule a=mymodule.person1['age'] print(a) import mymodule as mx a=mx.person1['age'] print(a)
default=None, help="Message for coding." ) args = parser.parse_args() if args.generate: if args.r and args.n and args.probability: return args, 1 else: exit("There is '-g' flag but no parameters.") if args.code: if args.file and args.message: return args, 2 else: exit("There is '-c' flag but no parameters.") if args.decode: if args.file and args.y: return args, 3 else: exit("There is '-d' flag but no parameters.") exit("There is no mode flag.") if __name__ == "__main__": args, mode = parse_init() if mode == 1: gen(args.r, args.n, args.probability) elif mode == 2: code(args.file, args.message, args.error) elif mode == 3: decode(args.file, args.y)
#!/usr/bin/env python # coding: UTF-8 from parser import parser from code import code from symtbl import symtbl import sys, re files = sys.argv[1:] while len(files): filename = files.pop(0) p = parser(filename) c = code() s = symtbl() nextVarAddress = 16 instAddress = 0 # create symbol-table while p.hasMoreCommands(): p.advance() if p.commandType() == 'L_COMMAND': if s.contains(p.symbol()): print "Error : contained label" else: s.addEntry(p.symbol(), instAddress) #print p.symbol(), instAddress elif p.commandType() == 'A_COMMAND': instAddress += 1 else: instAddress += 1 # create romdata p.fileopen(filename)
def main(): sys.setrecursionlimit(10000) parser = optparse.OptionParser() parser.add_option('-o', '--origin', help='Binary start address', default='0x8000') parser.add_option('-e', '--entries', help='Program entry point', default=None) parser.add_option('-i', '--io-ranges', help='MMIO address ranges', default=None) parser.add_option('-d', '--debug', help='Debug types enabled', default='all') parser.add_option('-v', '--debug-level', help='Debug verbosity level', default='0') parser.add_option('-f', '--debug-file', help='Debug output file name', default=None) options, args = parser.parse_args() try: debug.debug_level = int(options.debug_level) except ValueError: raise UserError('invalid debug level') if options.debug_file != None: debug.debugout = open(options.debug_file, 'w') debug.enable(options.debug.split(',')) try: bin = args[0] text = bytearray(open(bin, 'rb').read()) except Exception as e: raise UserError('failed to open code file: ' + str(args[0])) try: org = int(options.origin, 16) except ValueError: raise UserError('invalid origin address') if options.entries != None: try: entries = [int(x, 16) for x in options.entries.split(',')] except ValueError: raise UserError('invalid entry point(s) specified') else: if len(text) + org >= 0x10000: entries = [ text[0xfffc - org] + (text[0xfffd - org] << 8), text[0xfffa - org] + (text[0xfffb - org] << 8) ] else: entries = [org] try: if options.io_ranges != None: iomap = [] ranges = options.io_ranges.split(',') for i in ranges: if '-' in i: iomap += [tuple([int(x, 16) for x in i.split('-')])] else: iomap += [int(i, 16)] else: iomap = [(0x2000, 0x4017)] except ValueError: raise UserError('invalid MMIO ranges specified') debug.debug(debug.MAIN, 1, 'iomap', iomap) mcg = insn.MCodeGraph() ins = mcg.traceall(text, org, entries) ssa_funs = [] for k, v in mcg.symbols.items(): debug.debug(debug.MAIN, 2, '=== OSSIFY', v.address, v.name, v.insn) ssag = ssa.ssaify(v.insn, v.name, iomap) ssa_funs += [ssag] debug.debug(debug.MAIN, 3, 'callers', ssag.callers_graphs) debug.debug(debug.MAIN, 3, 'callsts', ssag.callers_st) #break ssa.identifyreturns(ssa_funs) for i in ssa_funs: # depropagation must be done after DCE, i.e. after identifyreturns() i.depropagate() i.dessa() bb = block.blockify(i) debug.debug(debug.MAIN, 3, '-- PREDESSA') block.dump(3, bb) debug.debug(debug.MAIN, 3, '-- PRESTRUCT') block.dump(3, bb) (bb, found) = block.structure(bb) debug.debug(debug.MAIN, 3, '-- POSTSTRUCT') while found: debug.debug(debug.MAIN, 3, 'retrying', bb) (bb, found) = block.structure(bb) debug.debug(debug.MAIN, 2, '-- POSTPOSTSTRUCT') block.dump(2, bb) if debug.debug_level >= 4: block.graphviz(bb) i.blocks = bb for i in ssa_funs: print(code.code(i.blocks, i.symbol, symbols=mcg.symbols, graphs=ssa_funs, graph=i), end='') print('=' * 78)
def testCode3(self): self.assertEqual(code.code(3), 6)
def testCode4(self): self.assertEqual(code.code(4), 8)
#!/usr/bin/env python3 import sys from parser import parser from symbols import symbols from code import code in_file = sys.argv[1] out_file = sys.argv[2] with open( f'/home/nick/PycharmProjects/coursera/nand2tetris/assembler/{in_file}', 'r') as f: clean_program = parser(f) symbols_program = symbols(clean_program) value = code(symbols_program) with open(f'{out_file}', 'w') as r: for item in value: r.write("%s\n" % item)