def compile(s=None, **options): # Update arguments from the argument cache, and vice versa global SavedTest, SavedOptions, CallNo if s is None: try: s = SavedTest except NameError: raise "The first call to compile must specify a source string." options_ = globals().get('SavedOptions', {}) options_.update(options) options = options_ if s: SavedTest = s if options: SavedOptions = options reloadSystem() from Compiler import Compiler c = Compiler(**options) from org.openlaszlo.sc.parser import ParseException try: CallNo += 1 #bytes = c.compile(('#file "interactive input %d"\n#line 1\n' % CallNo) + s) bytes = c.compile(s) except ParseException, e: raise `e`
def runCompilerDriver(self): print("Generating {0} point code for {1} target with sfType={2}, consSF={3} and bitlen={4}.".format(self.args.version, self.args.target, self.args.sfType, self.args.consSF, self.args.bitlen)) if self.args.disableAllOpti: print("Running with all optimizations disabled.") elif self.args.disableRMO: print("Running with Relu-Maxpool optimization disabled.") elif self.args.disableLivenessOpti: print("Running with liveness optimization disabled.") elif self.args.disableTruncOpti: print("Running with truncation placement optimization disabled.") obj = Compiler(self.args.version, self.args.target, self.args.sfType, self.args.astFile, self.args.printAST, self.args.consSF, self.args.bitlen, self.args.outputFileName, self.args.disableRMO, self.args.disableLivenessOpti, self.args.disableTruncOpti, self.args.disableAllOpti, self.args.debugVar ) obj.run()
def stop_server_in_a_thread(self): print "Trying to close the PHP process on %s" % ( self.program_php_server_thread.php_server_process.pid) if Compiler.is_linux() or Compiler.is_mac(): os.killpg(self.program_php_server_thread.php_server_process.pid, signal.SIGTERM) else: os.system('taskkill /f /im php.exe')
class TestCompiler(unittest.TestCase): def setUp(self): self.fp = 'test/test_doc_rubble' self.reporter = ReporterStreamConsole(1, 1) self.cpl = Compiler(self.reporter, BuilderAPIX64()) def test_parse(self): lxr = Lexer(FileSource(self.fp), FileIteratorTracking(self.fp), self.reporter) self.cpl.parse(lxr)
def start_server(self): command = '{0} -S localhost:{1} -t {2}'.format(self.php_path, self.port, self.webroot) if Compiler.is_linux() or Compiler.is_mac(): self.php_server_process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid) elif Compiler.is_windows(): self.php_server_process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
def evaluate(self, ind, **kwargs): fitness = 0 guess = ind.phenotype compiler = Compiler() program = compiler.compile(guess) initial_board = Board(self.path, "init") final_board = Board(self.path, "end") lift = Lift(self.path) game = GameOperations(initial_board, final_board, program, lift) game.runProgram() fitness += 0 if game.checkVictory( ) else self.check_difference_with_neighborhood(game.finalBoard, game.board) fitness += 20 if lift.liftedBlock != 0 else 0 return fitness
def test(keys=undefined, index=undefined, **options): """Run the tests.""" reloadSystem() tests = collectTests(keys, index, saveArguments=true) from Compiler import Compiler runConstraintTests() for test in tests: c = Compiler(**options) try: from jarray import array bytes = c.compile(test) array(bytes, 'b') except: print "During compilation of %r" % test raise
def click_run(self): self.console.setText("") if self.select == 'c': try: self.code['c'] = self.editor.get_text() self.code['asm'] = Compiler().parse(self.code['c']) self.code['coe'] = Assembler().parse(self.code['asm']) self.code['debug'] = self.get_debug_code() if str(self.console.toPlainText()) == "": print 'successful complie c code!' else: print 'failed complie c code!!!' except: print traceback.format_exc() print 'failed complie c code!!!' elif self.select == 'asm': try: self.code['asm'] = self.editor.get_text() self.code['coe'] = Assembler().parse(self.code['asm']) self.code['debug'] = self.get_debug_code() if str(self.console.toPlainText()) == "": print 'successful complie asm code!' else: print 'failed complie asm code!!!' except: print traceback.format_exc() print 'failed complie asm code!!!'
def Jack_to_xml(path): paths = retrive_files(path) out_dirpath = os.path.join(path, 'Xmlresult') for path in paths: outfile = os.path.basename(path).replace('.jack', '.xml') outpath = os.path.join(out_dirpath, outfile) compiler = Compiler(path, outpath)
def __init__(self, pathToMain): #Get path on mac if platform.system() == 'Darwin': # logging.debug('self.pathToMain'); # logging.debug(self.pathToMain); # logging.debug('PWD='); # logging.debug(os.environ.get('PWD')); #logging.debug('PYTHONPATH='); #logging.debug(os.environ.get('PYTHONPATH')); # logging.debug('ENVIRON='); # logging.debug(os.environ); if os.environ.get('PYTHONPATH') != None: self.pathToMain = os.environ.get('PYTHONPATH') else: self.pathToMain = pathToMain elif platform.system() == 'Windows' or platform.system() == 'Linux': self.pathToMain = pathToMain if platform.system() == 'Linux': self.pathToSketchbook = expanduser("~").decode('latin1')+'/Arduino' elif platform.system() == 'Windows' or platform.system() == 'Darwin': self.pathToSketchbook = expanduser("~").decode('latin1')+'/Documents/Arduino' self.pathToSketchbook = self.pathToSketchbook.decode('latin1') self.pathToArduinoDir = pathToMain+'/res/arduino/' self.uploader = Uploader(pathToMain) self.compiler = Compiler(pathToMain) self.boardSettings = defaultdict(BoardConfig) self.parseBoardSettings(self.pathToMain+"/res/boards.txt") self.board = 'uno' self.port = None
def __init__(self, pathToMain): self.pathToSketchbook = "" # Get path on mac if platform.system() == "Darwin": # logging.debug('self.pathToMain'); # logging.debug(self.pathToMain); # logging.debug('PWD='); # logging.debug(os.environ.get('PWD')); # logging.debug('PYTHONPATH='); # logging.debug(os.environ.get('PYTHONPATH')); # logging.debug('ENVIRON='); # logging.debug(os.environ); if os.environ.get("PYTHONPATH") != None: self.pathToMain = os.environ.get("PYTHONPATH") else: self.pathToMain = pathToMain elif platform.system() == "Windows" or platform.system() == "Linux": self.pathToMain = pathToMain if platform.system() == "Linux": self.pathToSketchbook = expanduser("~").decode("latin1") + "/Arduino" elif platform.system() == "Darwin": self.pathToSketchbook = base.sys_path.get_document_path() + "/Arduino" elif platform.system() == "Windows": self.pathToSketchbook = ( os.path.dirname(os.path.dirname(os.path.dirname(base.sys_path.get_tmp_path()))) + "/Documents/Arduino" ) self.pathToArduinoDir = pathToMain + "/res/arduino/" self.uploader = Uploader(pathToMain) self.compiler = Compiler(pathToMain) self.boardSettings = defaultdict(BoardConfig) self.parseBoardSettings(self.pathToMain + "/res/boards.txt") self.board = "uno" self.port = None
def __test(self): mode, initText, dataText = self.__convertToASM() if mode == "failed": self.__loader.fileDialogs.displayError("waveError", "waveErrorMessage", None, None) else: toTest = self.__formToData(mode, initText, dataText) from Compiler import Compiler Compiler(self.__loader, "common", "testWav", [toTest, self.__lockNum.get(), self.__title.get()])
def testCompileVariable(self): (code, errors) = Compiler().compile("def x = 12") # assert that no error occured self.assertEqual(errors, []) # assert correct parsing self.assertEqual(code.strip().splitlines(), ["z_x :: Int", "z_x = 12"])
def __testAllThread(self): from Compiler import Compiler Compiler(self.__loader, self.__loader.virtualMemory.kernel, "testScreenElements", [ self.__codeData[self.__activePart][self.getBankNum()][2], "NTSC", self.__activeBank ])
def __init__(self): self.hadError = False self.tokens = [] # saved tokens from previous uncompleted lines self.interp = Interpreter( ) # for retain inner statements when runPrompt() self.resolver = Resolver() self.compiler = Compiler() self.vm = StackVM()
def main(argv): """ Source: https://www.tutorialspoint.com/python/python_command_line_arguments.htm :param argv: :return: """ inputFileName = '' outputFileName = '' try: opts, args = getopt.getopt(argv, "hi:o:", ["ifile=", "ofile="]) except getopt.GetoptError: print('test.py -i <inputfile> -o <outputfile>') sys.exit(2) for opt, arg in opts: if opt == '-h': print('test.py -i <inputfile> -o <outputfile>') sys.exit() elif opt in ("-i", "--ifile"): inputFileName = arg elif opt in ("-o", "--ofile"): outputFileName = arg inputFile = open(inputFileName, "r") sourceCode = inputFile.read() compiler = Compiler(sourceCode) compiler.parse() compiler.compile() code = compiler.build() print(code)
def testCompileFunction(self): (code, errors) = Compiler().compile("def f(x) = x") # assert that no error occured self.assertEqual(errors, []) # assert correct parsing self.assertEqual(code.strip().splitlines(), ["z_f :: a -> a", "z_f (z_x) = z_x"])
def testCompileList(self): (code, errors) = Compiler().compile("def l = [1, 2, 3]") # assert that no error occured self.assertEqual(errors, []) # assert correct parsing self.assertEqual(code.strip().splitlines(), ["z_l :: [Int]", "z_l = [1, 2, 3]"])
def testCompileLambda(self): (code, errors) = Compiler().compile("def f(x) = lambda(y) x") # assert that no error occured self.assertEqual(errors, []) # assert correct parsing self.assertEqual(code.strip().splitlines(), ["z_f :: a -> b -> a", "z_f (z_x) = \\(z_y) -> z_x"])
def describeJunctionTree(bn, jt, target): '''String describing key elements of the junction tree like the components of every cliques, the edges, the main clique chosen by Compiler''' res = "" for i in jt.ids(): res += str(i) + "---------\n" for j in jt.clique(i): res += bn.variable(j).name() + "\n" res += "\n" + str(list(jt.edges())) res += "\nClique racine : " + str(Compiler.mainClique(bn, jt, target)) return res
def describeJunctionTree(bn, jt, target): '''String describing key elements of the junction tree like the components of every cliques, the edges, the main clique chosen by Compiler''' res = "" for i in jt.ids(): res += str(i)+"---------\n" for j in jt.clique(i): res += bn.variable(j).name()+"\n" res += "\n"+str(list(jt.edges())) res += "\nClique racine : "+str(Compiler.mainClique(bn, jt, target)) return res
def _run(self): if os.path.exists(self._submission_id_path): shutil.rmtree(self._submission_id_path) compiler = Compiler(compile_config=self._language_config["compile"], src=self._src, submission_id=self._submission_id) try: compiler._run() except CompilerException as e: return {"error": e.message, "reason": e.reason} try: self._get_latest_test_case() self._test_case_id_info = self._generate_test_case_info() except JudgeServiceException as e: return {"error": e.message, "reason": e.reason} try: if self._is_spj: cmd = "timeout 10 /usr/bin/g++ -std=c++11 {} -o {} 2> {}".format( self._spj_path, os.path.join(self._submission_id_path, "spj"), os.path.join(self._submission_id_path, 'spj_error.log')) code = os.system(cmd) if code: with open( os.path.join(self._submission_id_path, "spj_error.log"), "r") as error: error_content = error.read() error_content = error_content.replace( self._submission_id_path, "") raise JudgeServiceException("Spj Compile error", error_content) self._spj_exe = os.path.join(self._submission_id_path, 'spj') except JudgeServiceException as e: return {"error": e.message, "reason": e.reason} tmp_result = [] result = {} for i in range(self._test_case_id_info["test_case_number"]): tmp_result.append(self._pool.apply_async(run, (self, i))) self._pool.close() self._pool.join() for item in tmp_result: result[item.get()['test_case_name']] = item.get() return result
def __init__(self, pathToMain): self.pathToMain = pathToMain self.pathToSketchbook = expanduser("~")+'/sketchbook' self.pathToArduinoDir = pathToMain+'/res/arduino/' self.uploader = Uploader(pathToMain) self.compiler = Compiler(pathToMain) self.boardSettings = defaultdict(BoardConfig) self.parseBoardSettings(self.pathToMain+"/res/boards.txt") self.board = 'uno' self.port = None
def __testing(self): from Compiler import Compiler c = Compiler(self.__loader, None, "kernelTest", [ self.__loader.io.loadWholeText(self.__openKernelFrame.getValue()), self.__loader.io.loadWholeText(self.__openEnter.getValue()), self.__loader.io.loadWholeText(self.__openOverscan.getValue()), self.__loader.io.loadWholeText(self.__openScreenTopData.getValue()), self.__loader.io.loadWholeText(self.__openKernelData.getValue()) ])
def testCompileTuple(self): (code, errors) = Compiler().compile("def t = (true, lambda(x) x, 9)") # assert that no error occured self.assertEqual(errors, []) # assert correct parsing self.assertEqual(code.strip().splitlines(), [ "z_t :: (Bool, a -> a, Int)", "z_t = (z_true, \\(z_x) -> z_x, 9)" ])
def __init__(self): self.compiler = Compiler.getInstance() self.s3 = boto3.client( 's3', aws_access_key_id=os.getenv('AWS_IAM_KEY'), aws_secret_access_key=os.getenv('AWS_IAM_SECRET') ) # connect to socket server self.sio = socketio.Client() self.sio.connect(os.getenv("APP_SERVER"))
class Background(): def __init__(self,half_width,half_height,filename): self.compiler=Compiler() self.background_t = Texture(TEXDIR+filename) self.background_geom=self.compiler.quad(half_width,half_height) def draw(self): glPushMatrix() glBindTexture(GL_TEXTURE_2D,self.background_t.texID) glCallList(self.background_geom) glPopMatrix()
def addDefinition(self, line): (code, errors) = Compiler().compile(line, self.env) # check for errors if len(errors) > 0: for error in errors: print(error) return code = ":{\nlet\n" + code.strip() + "\n:}\n" self.ghci.execute(code)
class Wikix(object): def __init__(self, wikix_sheet_json, get_page_id, does_page_exist): self.sheet_json = wikix_sheet_json self.sheet = Compiler().compile( self.sheet_json ) self.get_page_id = get_page_id self.does_page_exist = does_page_exist def transform_syntax( self, text, link_collector = dict() ): return self.sheet.transform_syntax( text, { 'links': link_collector, 'page_exists': lambda href,context: self.page_exists(href,context) } ) def transform_xhtml( self, xhtml ): return self.sheet.transform_xhtml( xhtml ) def page_exists( self, href, context ): page_id = self.get_page_id(href) context['links'][page_id] = 1 return self.does_page_exist( page_id )
def buildOneProj(self, proj): print 'building \033[93m%s\033[0m, type \033[92m%s\033[0m' % (proj['Name'],proj['BuildType']) build_type = proj['BuildType'] obj_dir = '/'.join([self.projDir, proj['ObjDir']]) bin_dir = '/'.join([self.projDir, proj['BinDir']]) if 'SharedLib' == build_type: bin_path = ('/'.join([self.projDir, proj['BinDir'], proj['Name']+'.so'])) else: bin_path = ('/'.join([self.projDir, proj['BinDir'], proj['Name']+'.exe'])) if not os.path.exists(obj_dir): os.makedirs(obj_dir) if not os.path.exists(bin_dir): os.makedirs(bin_dir) if BuildTool=='clang': cmd_gen = ClangCommandGenerator() elif BuildTool=='msvc': cmd_gen = MSVCCommandGenerator() elif BuildTool=='ndk': cmd_gen = NDKCommandGenerator() compiler = Compiler(cmd_gen) linker = Linker(cmd_gen) objs = [] src_path = '' for src in proj['Source']: src_path = self.projDir+'/'+src obj_path = '/'.join([self.projDir, proj['ObjDir'], src+'.obj']) compiler.compile(obj_path, src_path, proj['CXX_FLAGS'], proj['C_FLAGS']) objs.append(obj_path) print '\033[92mLink Stage ...\033[0m' if 'SharedLib' == build_type: linker.link('-shared', bin_path, objs, proj['LINK_FLAGS']) else: linker.link('', bin_path, objs, proj['LINK_FLAGS'])
def write(): """Write the test source to tests.as, and the swf to sc.swf. The intent is that Flash compiles tests.as -> flash.swf, and the flasms of sc.swf and flash.swf can be compared.""" tests = collectTests(None, flashOnly=true) reloadSystem() # put the functions first, since Flash will compile them first def isFn(s): return s.startswith('function') def insertFunctionComment(s): pos = s.find('{') return s[:pos+1] + 'src = %r;' %s + s[pos+1:] tests = [insertFunctionComment(s) for s in tests if isFn(s)] + \ ['src = %r\n%s' % (s,s) for s in tests if not isFn(s)] text = '\n'.join(tests) + '\n' f = open('tests.as', 'w') f.write(text) f.close() from Compiler import Compiler c = Compiler(flashCompilerCompatability=true) bytes = c.compile(text) writeMovie(bytes, 'sc.swf')
def compile(self, source=None, file=None, moduleName=None, mainMethodName='respond'): """Compile the template. This method is automatically called by __init__ when __init__ is fed a file or source string.""" from Compiler import Compiler if file and type(file) in StringTypes and not moduleName and \ re.match(r'[a-zA-Z_][a-zA-Z_0-9]*$', file): moduleName = os.path.splitext(os.path.split(file)[1])[0] elif not moduleName: moduleName='GenTemplate' self._fileMtime = None self._fileDirName = None self._fileBaseName = None if file and type(file) in StringTypes: file = self.serverSidePath(file) self._fileMtime = os.path.getmtime(file) self._fileDirName, self._fileBaseName = os.path.split(file) self._filePath = file compiler = Compiler(source, file, moduleName=moduleName, mainMethodName=mainMethodName, templateObj=self, settings=self._compilerSettings, ) compiler.compile() self._generatedModuleCode = str(compiler) self._generatedClassCode = str(compiler._finishedClassIndex[moduleName]) compiler._templateObj = None compiler.__dict__ = {} del compiler
def loadModule(self, path): module = open(path, "r") (code, errors) = Compiler().compile(module.read(), self.env) module.close() # check for errors if len(errors) > 0: for error in errors: print(error) return out = "" for definition in code.strip().split("\n\n"): out += ":{\nlet\n" + definition.strip() + "\n:}\n" self.ghci.execute(out)
def __init__(self, width, height, *args, **kwds): wx.Frame.__init__(self, *args, **kwds) sizer = wx.BoxSizer(wx.VERTICAL) self.browser = wx.html2.WebView.New(self) sizer.Add(self.browser, 1, wx.EXPAND, 10) self.SetSizer(sizer) self.SetSize((width, height)) if Compiler.is_linux(): self.icon = wx.Icon("./icon.png", wx.BITMAP_TYPE_PNG) self.SetIcon(self.icon) self.Bind(wx.EVT_CLOSE, self.event_browser_closed) self.Bind(wx.EVT_CHAR_HOOK, self.handle_keystrokes) self.Bind(wx.html2.EVT_WEBVIEW_TITLE_CHANGED, self.title_changed, self.browser)
def compile_file(input_file, output_file, run, minify_file): print("Compiling file '%s'..." % input_file) with open(input_file, "rb") as f: code = f.read().decode("utf8") brainfuck_code = Compiler.compile(code) brainfuck_code += "\n" if minify_file: brainfuck_code = Minify.minify(brainfuck_code) with open(output_file, "wt") as f: f.write(brainfuck_code) print("Compiled successfully to '%s'" % output_file) if run: print("Running compiled code...") Interpreter.brainfuck(brainfuck_code)
def __init__(self, code, debug=False): """Load a program and prepare to run it. The debug flag enables writing output to files for examination. """ self.comp = Compiler(code, debug) # Load program memory with the bytecode. self.prog_memory = str(self.comp).split("\n") # Create an empty space for data memory. self.data_memory = [] # Initialize registers. self.ac = 0 # Accumulator self.ecx = 0 # Loop count self.pc = 0 # Program counter self.ir = 0 # Instruction register # Set debug flag for this instance. self.debug = debug
def __init__(self, instream): self.currToken = "" self.curritr = -1 self.filename = instream self.filecont = [] self.stream = open(instream, mode = 'r') self.commentFlag = False for line in self.stream: line = line.split("//")[0] if(line.find("/**") != -1): if(line.find("*/") != -1): tempLine = line tempLine = tempLine.split("*/")[-1] line = line.split("/**")[0] + tempLine else: line = line.split("/**")[0] self.commentFlag = True if(line.find("*/") != -1): self.commentFlag = False line = line.split("*/")[-1] if(self.commentFlag and (line.find("*") != -1)): line = "" if(line.find("\"") != -1): tempLine = line line = [] i = 0 j = 0 i = tempLine.find("\"", 0) j = tempLine.find("\"", i+1) line += tempLine[0:i].split() line.append(tempLine[i:(j+1)]) line += tempLine[(j+1):].split() else: line = line.split() for char in line: sym_split = "{|}|\(|\)|\[|\]|\.|,|;|\+|-|\*|/|&|\||<|>|=|~" self.filecont += re.split("(" + sym_split + ")", char) self.filecont = [word for word in self.filecont if word not in ["",'']] print self.filecont compname = self.filename.replace(".jack", ".xml") self.compile = Compiler(compname, self)
def printCall(self, line): (code, errors) = Compiler().compile("def v = " + line, self.env) # check for errors if len(errors) > 0: for error in errors: print(error) return if "v" in self.env.elements: (type, node, local) = self.env.get("v") if self.printString and str(type) == "[Int]": code = ":{\nlet\n" + code.strip( ) + "\n:}\nmap (\\x -> chr x) z_v\n" else: code = ":{\nlet\n" + code.strip() + "\n:}\nz_v\n" if self.ghci.evaluate(code): print(" :: " + str(type)) else: print("Abort. Evaluation took to long")
def compile(self, source=None, file=None, moduleName=None, mainMethodName='respond'): """Compile the template. This method is automatically called by __init__ when __init__ is fed a file or source string.""" from Compiler import Compiler if file and type(file) in StringTypes and not moduleName and \ re.match(r'[a-zA-Z_][a-zA-Z_0-9]*$', file): moduleName = os.path.splitext(os.path.split(file)[1])[0] elif not moduleName: moduleName = 'GenTemplate' self._fileMtime = None self._fileDirName = None self._fileBaseName = None if file and type(file) in StringTypes: file = self.serverSidePath(file) self._fileMtime = os.path.getmtime(file) self._fileDirName, self._fileBaseName = os.path.split(file) self._filePath = file compiler = Compiler( source, file, moduleName=moduleName, mainMethodName=mainMethodName, templateObj=self, settings=self._compilerSettings, ) compiler.compile() self._generatedModuleCode = str(compiler) self._generatedClassCode = str( compiler._finishedClassIndex[moduleName]) compiler._templateObj = None compiler.__dict__ = {} del compiler
def testStaticCoverage(): import Compiler Compiler.testStaticCoverage()
class ArduinoCompilerUploader: def __init__(self, pathToMain): self.pathToSketchbook = "" # Get path on mac if platform.system() == "Darwin": # logging.debug('self.pathToMain'); # logging.debug(self.pathToMain); # logging.debug('PWD='); # logging.debug(os.environ.get('PWD')); # logging.debug('PYTHONPATH='); # logging.debug(os.environ.get('PYTHONPATH')); # logging.debug('ENVIRON='); # logging.debug(os.environ); if os.environ.get("PYTHONPATH") != None: self.pathToMain = os.environ.get("PYTHONPATH") else: self.pathToMain = pathToMain elif platform.system() == "Windows" or platform.system() == "Linux": self.pathToMain = pathToMain if platform.system() == "Linux": self.pathToSketchbook = expanduser("~").decode("latin1") + "/Arduino" elif platform.system() == "Darwin": self.pathToSketchbook = base.sys_path.get_document_path() + "/Arduino" elif platform.system() == "Windows": self.pathToSketchbook = ( os.path.dirname(os.path.dirname(os.path.dirname(base.sys_path.get_tmp_path()))) + "/Documents/Arduino" ) self.pathToArduinoDir = pathToMain + "/res/arduino/" self.uploader = Uploader(pathToMain) self.compiler = Compiler(pathToMain) self.boardSettings = defaultdict(BoardConfig) self.parseBoardSettings(self.pathToMain + "/res/boards.txt") self.board = "uno" self.port = None def setBoard(self, board): self.board = board return self.searchPort() def setPort(self, port=""): self.port = port def getPort(self): return self.port def getBoard(self): return self.board def getBoardBaudRate(self): return self.boardSettings[self.board].getBaudRate() def getBoardMCU(self): return self.boardSettings[self.board].getMCU() def getBoardFCPU(self): return self.boardSettings[self.board].getFCPU() def parseBoardSettings(self, path): file = open(path, "r") # Split the file using the separator in boards.txt to separate the config of the different boards a = file.read().split("\n\n##############################################################\n\n") a.pop(0) # Remove first element which is only a url for line in a: boardName = line.split(".")[0] boardConfig = line.split("\n") boardConfig = [i.split("=") for i in boardConfig] boardConfig.pop(0) # Remove empty first element self.boardSettings[boardName] = BoardConfig(boardConfig) def getAvailablePorts(self): availablePorts = [] if platform.system() == "Windows": from serial.tools.list_ports import comports comPorts = list(comports()) for port in comPorts: if not "Bluetooth" in port[1]: # discard bluetooth ports availablePorts.append(port[0]) elif platform.system() == "Darwin": darwinPorts = glob.glob("/dev/tty.*") for port in darwinPorts: if not "Bluetooth" in port: # discard bluetooth ports availablePorts.append(port) elif platform.system() == "Linux": availablePorts = glob.glob("/dev/ttyACM*") availablePorts += glob.glob("/dev/ttyUSB*") return availablePorts def searchPort(self): availablePorts = self.getAvailablePorts() if len(availablePorts) <= 0: return [] ports = [] for port in availablePorts: args = "-P " + port + " -p " + self.getBoardMCU() + " -b " + self.getBoardBaudRate() + " -c arduino" output, err = callAvrdude(args) if "Device signature =" in output or "Device signature =" in err: ports.append(port) if len(ports) == 1: self.setPort(ports[0]) return ports def compile(self, code): return self.compiler.compile( code, self.getBoard() or "uno", self.pathToArduinoDir, self.pathToSketchbook, self.getBoardMCU(), self.getBoardFCPU(), ) def upload(self, code): compilationErrorReport = self.compile(code) if compilationErrorReport["status"] == "OK": uploadErrorReport = self.uploader.upload( code, self.getPort(), self.getBoard(), self.getBoardMCU(), self.getBoardBaudRate(), self.pathToMain, self.pathToSketchbook, ) return uploadErrorReport else: return compilationErrorReport
def stop_server_in_a_thread(self): print "Trying to close the PHP process on %s" % (self.program_php_server_thread.php_server_process.pid) if Compiler.is_linux() or Compiler.is_mac(): os.killpg(self.program_php_server_thread.php_server_process.pid, signal.SIGTERM) else: os.system('taskkill /f /im php.exe')
from Module.Entity.Entity import Atributo # Entity (MVC) # Adaptador de Banco de Dados adapter = Adapter('localhost', 'testebd', 'root', '') # Modulo Core core = Module('Core') core.addFiles(adapter) # Modulo Carros entCarro = Entity('Carro') entCarro.addAtributos( Atributo('id', Atributo.TYPE_INT, None, True, True, True, False), Atributo('nome', Atributo.TYPE_VARCHAR, 180), Atributo('modelo', Atributo.TYPE_VARCHAR, 100), Atributo('marca', Atributo.TYPE_VARCHAR, 100), Atributo('placa', Atributo.TYPE_VARCHAR, 100), Atributo('cor', Atributo.TYPE_VARCHAR, 100) ) entCarro.createModel() entCarro.generateCreateTable() modCarros = Module('Carros') modCarros.addFiles(entCarro) # Compila o resultado compilador = Compiler('teste_compilador') compilador.addModules(core, modCarros) compilador.generate() print("Compilado")
from Compiler import Compiler from Paths import testScriptPath if __name__ == '__main__': c = Compiler(testScriptPath) c.compile()
class ArduinoCompilerUploader: def __init__(self, pathToMain): #Get path on mac if platform.system() == 'Darwin': # logging.debug('self.pathToMain'); # logging.debug(self.pathToMain); # logging.debug('PWD='); # logging.debug(os.environ.get('PWD')); #logging.debug('PYTHONPATH='); #logging.debug(os.environ.get('PYTHONPATH')); # logging.debug('ENVIRON='); # logging.debug(os.environ); if os.environ.get('PYTHONPATH') != None: self.pathToMain = os.environ.get('PYTHONPATH') else: self.pathToMain = pathToMain elif platform.system() == 'Windows' or platform.system() == 'Linux': self.pathToMain = pathToMain if platform.system() == 'Linux': self.pathToSketchbook = expanduser("~").decode('latin1')+'/Arduino' elif platform.system() == 'Windows' or platform.system() == 'Darwin': self.pathToSketchbook = expanduser("~").decode('latin1')+'/Documents/Arduino' self.pathToSketchbook = self.pathToSketchbook.decode('latin1') self.pathToArduinoDir = pathToMain+'/res/arduino/' self.uploader = Uploader(pathToMain) self.compiler = Compiler(pathToMain) self.boardSettings = defaultdict(BoardConfig) self.parseBoardSettings(self.pathToMain+"/res/boards.txt") self.board = 'uno' self.port = None def setBoard (self, board): self.board = board return self.searchPort() def setPort (self,port=''): self.port = port def getPort (self): return self.port def getBoard(self): return self.board def getBoardBaudRate(self): return self.boardSettings[self.board].getBaudRate() def getBoardMCU(self): return self.boardSettings[self.board].getMCU() def getBoardFCPU(self): return self.boardSettings[self.board].getFCPU() def parseBoardSettings (self, path): file=open(path,'r') #Split the file using the separator in boards.txt to separate the config of the different boards a = file.read().split('\n\n##############################################################\n\n'); a.pop(0) #Remove first element which is only a url for line in a: boardName = line.split('.')[0] boardConfig = line.split('\n') boardConfig= [i.split('=')for i in boardConfig] boardConfig.pop(0) #Remove empty first element self.boardSettings[boardName]=BoardConfig(boardConfig) def getAvailablePorts (self): if platform.system() =='Windows': from serial.tools.list_ports import comports comPorts = list(comports()) availablePorts = [] for port in comPorts: if not 'Bluetooth' in port[1]: #discard bluetooth ports availablePorts.append(port[0]) elif platform.system() =='Darwin': if self.board == 'uno': availablePorts = glob.glob('/dev/tty.usbmodem*') elif self.board == 'bt328': availablePorts = glob.glob('/dev/tty.usbserial-*') else: availablePorts = glob.glob('/dev/tty*') elif platform.system() =='Linux': if self.board == 'uno': availablePorts = glob.glob('/dev/ttyACM*') elif self.board == 'bt328': availablePorts = glob.glob('/dev/ttyUSB*') else: availablePorts = glob.glob('/dev/tty*') return availablePorts def searchPort (self): availablePorts = self.getAvailablePorts() if len(availablePorts) <=0: return [] ports = [] for port in availablePorts: args = "-P "+port+" -p "+ self.getBoardMCU() +" -b "+ self.getBoardBaudRate()+" -c arduino" output, err = callAvrdude(args); if 'Device signature =' in output or 'Device signature =' in err: ports.append(port) if len(ports)==1: self.setPort(ports[0]) return ports def compile (self, code): return self.compiler.compile( code, self.getBoard() or 'uno', self.pathToArduinoDir, self.pathToSketchbook, self.getBoardMCU(), self.getBoardFCPU()) def upload (self, code): compilationErrorReport = self.compile(code) if compilationErrorReport['status'] == 'OK': uploadErrorReport = self.uploader.upload(code, self.getPort(), self.getBoard(), self.getBoardMCU(), self.getBoardBaudRate(), self.pathToMain, self.pathToSketchbook) return uploadErrorReport else: return compilationErrorReport
target.write('Evidences : '+str(evs)+'\nTargets : '+str(targets)+'\n') target.write('\n\nJunction Tree description : \n'+describeJunctionTree(bn, jt, targets)) target.close() while(countNOBN < NUMBER_OF_NETWORKS and error): #bn = gum.loadBN("/home/ubuntu/metaGenBayes/BNs/insurance.bif") bn = gum.BNGenerator().generate() bn.saveBIF('tester.bif') while(countNOET < NUMBER_OF_EVIDENCES_TESTED): evs = randomEvidenceGenerator(bn,2) targets = targetSelecter(bn, evs) comp = Compiler.compil(bn, targets[:], evs) '''pyAgrum reference version''' resPyAgrumRef= {} ie=gum.LazyPropagation(bn) ie.setEvidence(evs) ie.makeInference() jt = ie.junctionTree() for t in targets: resPyAgrumRef[t] = list(ie.posterior(bn.idFromName(t))) '''pyAgrum generated version''' resPyAgrumGen.clear() generator= Generator.pyAgrumGenerator.pyAgrumGenerator() generator.genere(bn, targets, evs, comp, "pyAgrumGenerated____test.py", "getValue", header) importOrReload('pyAgrumGenerated____test', 'getValue')