def __init__(self, scr, args): self.scr = scr self.args = args self.y_size = 15 self.x_size = 59 self.y_value = None self.x_value = None self.y_pos, self.x_pos = 0, 0 self.difficulty = 3 self.difficulty_map = {1: 0.11, 2: 0.14, 3: 0.17, 4: 0.20, 5: 0.23} self.max_mine_digit = 2 self.small = False self.fullscreen = False self.m_win = curses.newwin(self.y_size, self.x_size, self.y_pos, self.x_pos) self.s_win = curses.newwin(2, self.x_size, self.y_size, self.x_pos) self.p_win = curses.newwin(6, 13, self.y_pos, self.x_pos) self.o_win = curses.newwin(5, 16, self.y_pos, self.x_pos) self.d_win = curses.newwin(8, 13, self.y_pos, self.x_pos) self.v_win = curses.newwin(6, 14, (self.y_size // 2) - 4, (self.x_size // 2) - 6) self.so_win = curses.newwin(6, 6, self.y_pos, self.x_pos) self.logic = MinefieldLogic(self.y_size, self.x_size, self.difficulty_map[self.difficulty], self.max_mine_digit) self.context = Context(self.logic, (self.y_value, self.x_value), self.difficulty, self.difficulty_map, self.fullscreen, self.small, (self.y_size, self.x_size))
def checkSVC(): # clf = svm.SVC() clf = svm.SVC() # parameter_space = [{'kernel': ['linear'], 'gamma': [1e-3, 1e-4], # 'C': [1, 10, 100, 1000]}, # {'kernel': ['linear'], 'C': [1, 10, 100, 1000]}] parameter_space = { 'C': [0.1, 1, 10, 100, 1000], 'gamma': [1, 0.1, 0.01, 0.001, 0.0001], 'kernel': ['linear', 'rbf', 'sigmoid'] } model = Context( FrameWorkSVM(clf, 'trainData1.csv', 'testData1.csv', param=parameter_space)) # model.strategy.x_train = SelectKBest(chi2, k=7).fit_transform(model.strategy.x_train, model.strategy.y_train) # model.strategy.x_train = pd.DataFrame(model.strategy.x_train) # model.strategy.x_test = SelectKBest(chi2, k=7).fit_transform(model.strategy.x_test, model.strategy.y_test) # model.strategy.x_test = pd.DataFrame(model.strategy.x_test) model.strategy.grid_search() accurancy_model = model.run_model() # print(model.strategy.model.best_params_) data = model.strategy.getCsvData() model.strategy.insertDataToCSV(data, "4")
def __init__(self, gameObject, parent=None, rect=sf.Rectangle(),\ alignment = pyguiml.Position.Center, spacing=sf.Vector2(0, 5), \ autoDefineSize = True, select=False, active=False, \ alwaysUpdateSelection=True, alwaysUpdateActivation=True, \ permanentSelection=True, permanentActivation=True, \ changeRight = sf.Keyboard.RIGHT, changeLeft = sf.Keyboard.LEFT,\ changeTop = sf.Keyboard.UP, changeBottom = sf.Keyboard.DOWN): Context.__init__(self, gameObject, parent) pyguiml.SelectionMenu.__init__(self, parent, rect, alignment, spacing, autoDefineSize, select, \ active, alwaysUpdateSelection, alwaysUpdateSelection, permanentSelection, \ permanentActivation, changeRight, changeLeft, changeTop, changeBottom) self.addWidget(pyguiml.Button(self, pyguiml.Label(None, "Start Game",\ characterSize=24, font=sf.Font.from_file("DejaVuSans.ttf"))), sf.Vector2(0, 0)) self.addNameOnWidget(self.child[-1], "StartGame") self.addWidget(pyguiml.Button(self, pyguiml.Label(None, "Option",\ characterSize=24, font=sf.Font.from_file("DejaVuSans.ttf"))), sf.Vector2(0, 1)) self.addNameOnWidget(self.child[-1], "Option") self.addWidget(pyguiml.Button(self, pyguiml.Label(None, "Crédit",\ characterSize=24, font=sf.Font.from_file("DejaVuSans.ttf"))), sf.Vector2(0, 2)) self.addNameOnWidget(self.child[-1], "Credit") self.addWidget(pyguiml.Button(self, pyguiml.Label(None, "Quitter",\ characterSize=24, font=sf.Font.from_file("DejaVuSans.ttf"))), sf.Vector2(0, 3), name="Quit") self.posOrigin = pyguiml.Position.Center self.pos = (gameObject.size)/2 self.setAllActiveMouseKeyboard(sf.Keyboard.RETURN, sf.Mouse.LEFT) self._background = pyguiml.Image(None, "Ressources/Images/FirstMenu.jpg", delTextureCreated = False) gameObject.backgroundImage = self._background
def test_successful_end_to_end(): f = Field(Example) assert f.from_kind == Question assert f.to_kind == Answer assert 'get_question' in f.opcode assert 'tests_verify_answer' in f.opcode assert '2pat_merge_as_pic' in f.opcode source = Source(('get_question', 'pic_all_as_pat', 'pat_flip_up_down', 'get_question', 'pic_all_as_pat', '2pat_merge_as_pic', 'tests_verify_answer')) code = f.compile(source) assert isinstance(code, Code) assert len(code.data) == len(source.data) ctx = Context('data') prb = ctx.get_problem_startswith('496994bd') for example in prb: ret = f.run(code, example, peek_answer=True) assert isinstance(ret, Block) assert ret.type == Block.type_integer assert isinstance(ret.data, int) assert ret.data == 1
def calculateFrequenciesFromXML(self): input_file = open(sys.argv[1], "r") lines = input_file.readlines() num_lines_parsed = 0 # Set up the first context current_context = Context(self.extractTimestamp(lines[0])) for line in lines: line_timestamp = self.extractTimestamp(line) # Handles malformed timestamps if line_timestamp is None: continue # Extract other components of message line_message = line[line.find("<msg>")+5:line.find("</msg>")] # If we hit a new second, that is the two timestamps differ by more than the context duration if line_timestamp - current_context.timestamp > timedelta(seconds=Globals.CONTEXT_DURATION-1): self.writeContextToFile(current_context) self.context_history.append(current_context) current_context = Context(line_timestamp) # Else, we're in the same second, so update the current context else: current_context.addMessageToContext(line_message) num_lines_parsed += 1 if num_lines_parsed % 1000000 == 0: print("Finished: " + str(num_lines_parsed)) # Add the latest context self.context_history.append(current_context) self.writeContextToFile(current_context) self.output_file.close()
def gen_callgraphlets(self): # for src callgraphlets self.src_graphlets = {} test_context_path = self.srcdir + self.srcname + '.graphlets' src_callgraph = self.src_db['callgraph'] type_ = self.src_db['type'] depth = self.src_db['depth'] i = 0 for node in src_callgraph: print str(i * 1.0 / len(src_callgraph)) i += 1 src_context = Context(node, src_callgraph, depth, type_) self.src_graphlets[node] = src_context pickle.dump(self.src_graphlets, open(test_context_path, 'wb')) self.dst_graphlets = {} test_context_path = self.dstdir + self.dstname + '.contextls' dst_callgraph = self.dst_db['callgraph'] i = 0 for node in dst_callgraph: print str(i * 1.0 / len(src_callgraph)) i += 1 dst_context = Context(node, dst_callgraph, depth, type_) self.dst_graphlets[node] = dst_context pickle.dump(self.dst_graphlets, open(test_context_path, 'wb'))
def menu(): """ The menu function. """ l = LinkedList() context = None while True: help_message = get_help_message() task = input(help_message) if task == "1": context = Context(FirstStrategy()) elif task == "2": context = Context(SecondStrategy()) elif task == "3": generate_list(l, context) elif task == "4": del_index(l) elif task == "5": del_between_indexes(l) elif task == "6": l.listMethod() elif task == "7": print(l) elif task == "8": print("GOODBYE!") break else: print("WRONG INPUT!") continue print()
def __init__(self, src, actor=None): Component.__init__(self, actor) # TODO Include a mesh name (e.g. 'Dragon') as ID as well as src (e.g. '../res/models/Dragon.obj') self.src = src self.filepath = Context.getInstance().getResourcePath('models', src) # OpenGL version-dependent code (NOTE assumes major version = 3) self.vao = None if Context.getInstance().GL_version_minor > 0: # 3.1 (or greater?) self.vao = glGenVertexArrays(1) else: # 3.0 (or less?) self.vao = GLuint(0) glGenVertexArrays(1, self.vao) glBindVertexArray(self.vao) self.loadModel(self.filepath) self.vbo = VBO(self.meshData, GL_STATIC_DRAW) self.vbo.bind() glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * 4, self.vbo + 0) glEnableVertexAttribArray(1) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * 4, self.vbo + 12) self.ebo = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.ebo) glBufferData(GL_ELEMENT_ARRAY_BUFFER, len(self.elements) * 4, self.elements, GL_STATIC_DRAW)
def __init__(self, gameObject, parent=None): Context.__init__(self, gameObject, parent) label = pyguiml.Label(None, source="Ce jeu vous a été présenté par Gaulois94, grâce à la SFML. \n\n\n\n\n\n\n\n\n\n\n\n\n Il a pour but de montrer l'efficacité de la SFML, et sert surtout de test pour PYGUIML : une lib faites pour la SFML en python. Ce jeu est tout simplement un petit shootem up, assez simple", font=sf.Font.from_file("DejaVuSans.ttf")) self.addChild(pyguiml.TextArray(self, sizeX=gameObject.view.size.x, label=label, cutStyle=pyguiml.Cut.Word), name="Text") self["Text"].posOrigin = pyguiml.Position.Center self["Text"].pos = gameObject.view.size/2
def test_calling(): ctx = Context('data') prob = ctx.get_problem_startswith('496994bd') assert isinstance(prob, Problem) assert isinstance(prob.data[0], Example) q, a, is_test = prob.data[0].data assert isinstance(q, Question) assert isinstance(a, Answer) assert isinstance(is_test, bool) bop_fun = BopForward.bopforward_pic_all_as_pat assert isinstance(bop_fun, Function) assert isinstance(bop_fun.arg_types, list) assert bop_fun.ret_type == Block.type_pattern ff = bop_fun.data assert callable(ff) ret = ff(q) assert isinstance(ret, Block) assert ret.type == Block.type_pattern assert isinstance(ret.data, tuple) assert len(ret.data) == 2
def __init__(self, src, actor=None): Component.__init__(self, actor) # TODO Include a mesh name (e.g. 'Dragon') as ID as well as src (e.g. '../res/models/Dragon.obj') self.src = src self.filepath = Context.getInstance().getResourcePath('models', src) # OpenGL version-dependent code (NOTE assumes major version = 3) self.vao = None if Context.getInstance().GL_version_minor > 0: # 3.1 (or greater?) self.vao = glGenVertexArrays(1) else: # 3.0 (or less?) self.vao = GLuint(0) glGenVertexArrays(1, self.vao) glBindVertexArray(self.vao) self.loadModel(self.filepath) self.vbo = VBO(self.meshData, GL_STATIC_DRAW) self.vbo.bind() glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6*4, self.vbo+0) glEnableVertexAttribArray(1) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6*4, self.vbo+12) self.ebo = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.ebo) glBufferData(GL_ELEMENT_ARRAY_BUFFER, len(self.elements)*4, self.elements, GL_STATIC_DRAW)
def checkANN(): ''' define model define model parameters optional: run grid search run train model get measurs of the model preditions ''' #define model parameters activation = 'relu' solver = 'adam' alpha = 0.05 learning_rate = 'constant' max_iter = 500 #init model clf = MLPClassifier(activation=activation, solver=solver, alpha=alpha, learning_rate=learning_rate, max_iter=max_iter) parameter_space = { # 'hidden_layer_sizes': [(5,10,5),(15,),(5,5,5),(8,8),(100,5,100)], 'activation': ['tanh', 'relu'], 'solver': ['sgd', 'adam'], 'alpha': [0.0001, 0.5], 'learning_rate': ['constant', 'invscaling', 'adaptive'], 'max_iter': [50, 500] } model = Context( FrameWorkANN(clf, "trainData1.csv", "TestData1.csv", param=parameter_space)) #define parameters model.strategy.activation = activation model.strategy.solver = solver model.strategy.alpha = alpha model.strategy.learning_rate = learning_rate model.strategy.max_iter = max_iter #define number of features model.strategy.x_train = SelectKBest(chi2, k=14).fit_transform( model.strategy.x_train, model.strategy.y_train) model.strategy.x_train = pd.DataFrame(model.strategy.x_train) model.strategy.x_test = SelectKBest(chi2, k=14).fit_transform( model.strategy.x_test, model.strategy.y_test) model.strategy.x_test = pd.DataFrame(model.strategy.x_test) #run gridSearch # model.strategy.grid_search() #run model model.run_model() #csv data plots data = model.strategy.getCsvData() model.strategy.insertDataToCSV(data, "decreseRows")
def main(): context = Context() startState = StartState() startState.doAction(context) print(context.getState().toString()) stopState = StopState() stopState.doAction(context) print(context.getState().toString())
def parse(self, context: Context) -> None: from CommandNode import CommandNode while True: if context.currentToken() == None: raise ParseException("Missing 'end'") elif context.currentToken() == "end": context.skipToken("end") break else: commandNode = CommandNode() commandNode.parse(context) self.__list.append(commandNode)
def main(): context = Context(OperationAdd()) print("10 + 5 = " + str(context.executeStrategy(10,5))) context = Context(OperationSubstract()) print("10 - 5 = " + str(context.executeStrategy(10,5))) context = Context(OperationMultiply()) print("10 * 5 = " + str(context.executeStrategy(10,5)))
def __init__(self, vertexFileName, fragmentFileName): #Read in the vertex shader from file with open(vertexFileName, "r") as f: vertexSource = f.read() f.close() #Read in the fragment shader from file with open(fragmentFileName, "r") as f: fragmentSource = f.read() f.close() # OpenGL version-dependent code (NOTE shader source must be version 150) if Context.getInstance().GLSL_version_string != "150": print "Shader.__init__(): Changing shader source version to {}".format( Context.getInstance().GLSL_version_string) vertexSource = vertexSource.replace( "150", Context.getInstance().GLSL_version_string, 1) fragmentSource = fragmentSource.replace( "150", Context.getInstance().GLSL_version_string, 1) # TODO put special version placeholder in shader source files instead of "150" #Create and compile the vertex shader vertexShader = glCreateShader(GL_VERTEX_SHADER) glShaderSource(vertexShader, vertexSource) glCompileShader(vertexShader) self.printShaderInfoLog(vertexShader) #Create and compile the fragment shader fragmentShader = glCreateShader(GL_FRAGMENT_SHADER) glShaderSource(fragmentShader, fragmentSource) glCompileShader(fragmentShader) self.printShaderInfoLog(fragmentShader) #Link the vertex and fragment shader into a shader program self.shaderProgram = glCreateProgram() glAttachShader(self.shaderProgram, vertexShader) glAttachShader(self.shaderProgram, fragmentShader) glBindAttribLocation(self.shaderProgram, 0, "position") glBindAttribLocation(self.shaderProgram, 1, "normal") glBindFragDataLocation(self.shaderProgram, 0, "outColor") glLinkProgram(self.shaderProgram) self.printProgramInfoLog(self.shaderProgram) glUseProgram(self.shaderProgram) #Flag the vertex and fragment shaders for deletion when not in use glDeleteShader(vertexShader) glDeleteShader(fragmentShader)
def import_context_from_file(self, file): """Import context values from a file. Read line by line the file to create J, M and I sets. Keyword arguments: file_path -- the file path """ # print('Generate the context \'' + file.stem + '\' from \'' + str(file) + '\'') context = Context(file.stem) with file.open() as csv_file: lecteur = csv.reader(csv_file, delimiter='\t', quotechar='|') M_list = next(lecteur) for m in M_list: context.add_m(m) l = 1 for line in lecteur: c = 0 j = 'o' + str(l) context.add_j(j) for colonne in line: if (colonne != '') and (colonne != '0'): context.add_i(j, M_list[c]) c += 1 l += 1 return context
def __init__(self, parameters, context, code, change_code): self.parameters = [] self.context = Context(context) self.code = code + " " self.applied = [] if change_code: for i in range(len(parameters)): self.parameters.append("__" + str(i)) pattern = re.compile("\W" + parameters[i] + "\W") results = pattern.findall(self.code) for res in results: self.code = self.code.replace( res, res.replace(parameters[i], "__" + str(i))) else: self.parameters = parameters
def run(fname, text): lexer = Lexer(fname, text) tokens, error = lexer.genTok() if error: return None, error parser = Parser(tokens) bTree = parser.parse() if bTree.error: return None, bTree.error interpreter = Interpreter() context = Context('<program>') context.symbTable = GlobalSymTable result = interpreter.visit(bTree.node, context) return result.value, result.error
def test_run_all(): context = Context('data') Search.build_code_base('./code_base/basis_code.jcb', context) cg = CodeGen('./code_base/basis_code.jcb', None, Example) cg.build_reward_training_data('./code_base/basis_code.evd', context) cg = CodeGen(None, './code_base/basis_code.evd', Example) assert isinstance(cg.xgb, XGBClassifier) with open('./code_base/basis_code.evd', 'r') as f: txt = f.read().splitlines() lol = [] for s in txt: if s[0] != '.': lol.append([float(x) for x in s.split(', ')]) test = np.array(lol) pred = cg.predict_rewards(test[:, range(1, LENGTH_CODE_EVAL + 1)]) assert sum(1 * (pred > 0.5) == test[:, 0]) / test.shape[0] > 0.8
def run (file,text): lexer = Lexer(file,text) tokens,error = lexer.make_tokens() if error: return None,error #abstract syntax tree parser = Parser(tokens) abstract_st = parser.parse() if abstract_st.error: return None,abstract_st.error #run program interpreter = Interpreter() context = Context('<basic context>') context.symbol_table=global_symbol_table result = interpreter.visit(abstract_st.node,context) return result.value,result.error
def set_timer(bot, update, args, job_queue, chat_data): """Add a job to the queue.""" chat_id = update.message.chat_id if chat_id in chat_data: update.message.reply_text( 'You already have an active timer. Use /unset to remove.') return try: # args[0] should contain a valid time initial = get_seconds(args[0]) logger.info('Seconds diff "%d"', initial) # args[1] should contain a positive integer indicating the interval between messages n = int(args[1]) if n < 0: update.message.reply_text('Interval must be positive') return # Add job to queue job = job_queue.run_repeating(alarm, n, first=initial, context=Context(chat_id, int(args[2]))) chat_data[chat_id] = job update.message.reply_text('Timer successfully set!') except (IndexError, ValueError): update.message.reply_text( 'Usage: /set <time> <interval> <initial_count>')
def addContext(self, name: str, createDir: bool = True) -> Context: ''' Add a context ''' self.logger.debug("S: Adding context " + name) if(name in self.contexts): self.logger.debug("S: Context " + name + " already loaded") return self.contexts[name] # Create a Path object saneName = format_filename(name) # Create the directory dirPath = self.storagePath / saneName # Flag if this is not writable if not self.writable: self.logger.debug("S: " + str(dirPath) + " is not writable") if createDir is True: if not dirPath.exists(): dirPath.mkdir() else: self.logger.error("S: Context directory already exists") # TODO Should we fail here? # Add to the dictionary self.contexts[name] = Context(name, dirPath, self) return self.contexts[name]
def __init__(self, tableName="document", copy=True): from contextionaryDatabase import Table from Context import Context self.tableName = tableName self.copy = copy if self.copy == True: self.tableName = tableName + '_temp' context = Context() self.defaultColumns = { "document_id": "serial", "document_title": "varchar(255)", "context_id": "bigint", "document_content": "text", "document_path": "text" } self.defaultPrimaryKeys = ["document_id"] self.defaultUnique = ["document_path"] self.defaultForeignKeys = { "context_id": (context.tableName, "context_id") } self.getTriggerFunction = None self.Table = Table(self.tableName)
def parse(self, context: Context): if context.currentToken() == "repeat": self.__node = RepeatCommandNode() self.__node.parse(context) else: self.__node = PrimitiveCommandNode() self.__node.parse(context)
def __init__(self, rule, context=None): self.rule = rule if context is None: self._context = Context(set([self])) else: self._context = context context.addTarget(self)
def __init__(self, code: List[CodeLine]): self._code = code self._cur_line_id = 0 self._stack = [] self._contexts = [Context(0)] self._halted = False self.__run()
def __init__(self): self.root = tk.Tk() self.context = Context() self.view = View(self.root, self.context) open('gui.main.log', 'w').close() #Clear the log file logging.basicConfig(filename='gui.main.log', level=logging.INFO)
def __init__(self, name, cmdWords, allowNoChoice=True, ruleType=RuleType.TERMINAL): if type(cmdWords) in (unicode, str): self.cmdWords = [cmdWords] else: self.cmdWords = cmdWords self.name = name self.ruleType = ruleType self.allowNoChoice = allowNoChoice getLoop().subscribeEvent(ConnectedEvent, self._sendWords) self.actionRule = None self.wordRule = None self.rule = None # self.words is a list of lists of sets where: # self.words[phraseLength][wordIndex] = set() of words # So if "foo bar" is a valid phrase, then it contains: # self.words[2][0] == "foo" # self.words[2][1] == "bar" self.words = [] # self.selectionMap is a list of tuples where the first element # is a list of words in order that map to the second element in # the tuple. self.selectionMap = [] self.activated = False self.context = Context(set([self])) self._buildRule()
def __init__(self, vertexFileName, fragmentFileName): #Read in the vertex shader from file with open (vertexFileName, "r") as f: vertexSource = f.read() f.close() #Read in the fragment shader from file with open (fragmentFileName, "r") as f: fragmentSource = f.read() f.close() # OpenGL version-dependent code (NOTE shader source must be version 150) if Context.getInstance().GLSL_version_string != "150": print "Shader.__init__(): Changing shader source version to {}".format(Context.getInstance().GLSL_version_string) vertexSource = vertexSource.replace("150", Context.getInstance().GLSL_version_string, 1) fragmentSource = fragmentSource.replace("150", Context.getInstance().GLSL_version_string, 1) # TODO put special version placeholder in shader source files instead of "150" #Create and compile the vertex shader vertexShader = glCreateShader(GL_VERTEX_SHADER) glShaderSource(vertexShader, vertexSource) glCompileShader(vertexShader) self.printShaderInfoLog( vertexShader ) #Create and compile the fragment shader fragmentShader = glCreateShader(GL_FRAGMENT_SHADER) glShaderSource(fragmentShader, fragmentSource) glCompileShader(fragmentShader) self.printShaderInfoLog( fragmentShader ) #Link the vertex and fragment shader into a shader program self.shaderProgram = glCreateProgram() glAttachShader(self.shaderProgram, vertexShader) glAttachShader(self.shaderProgram, fragmentShader) glBindAttribLocation( self.shaderProgram, 0, "position") glBindAttribLocation( self.shaderProgram, 1, "normal") glBindFragDataLocation(self.shaderProgram, 0, "outColor") glLinkProgram(self.shaderProgram) self.printProgramInfoLog(self.shaderProgram) glUseProgram(self.shaderProgram) #Flag the vertex and fragment shaders for deletion when not in use glDeleteShader(vertexShader); glDeleteShader(fragmentShader);
def parse_leaf(node: Leaf, data: dict, context: Context) -> EvalObject: if node.typ == 'SIGNATURE': sig, params = node.value[:-1].split("(") sig_types, tuples = data.get(sig) params = params.split(",") if params == ['']: params = [] if len(sig_types) != len(params): #print(sig_types, params) raise RuntimeError("Node " + node.to_str() + " does not match signature ") if not params: if tuples == [[False]]: return Bool(False) else: return Bool(True) else: for i, param in enumerate(params): if sig_types[i] == 'INT': try: const = int(param) for k, e in enumerate(tuples): if e[i] != const: tuples.pop(k) params[i] = context.get_var_name() except ValueError: pass elif sig_types[i] == 'VARCHAR': if param[0] == "\"" and param[-1] == "\"": const = param[1:-1] for k, e in enumerate(tuples): if e[i] != const: tuples.pop(k) params[i] = context.get_var_name() fv = list(zip(params, sig_types)) #print("here ", end="") #print(fv, tuples) return Table(table_from_tuples(fv, tuples, context), set(fv), False) else: raise RuntimeError("Unhandled type for Leaf outside condition: " + node.typ)
def transform_to_extended_context(self, context): """Generate the extended version of current context It'll create one j for each node on the graph """ # print('Generate the extended context of \''+context.context_name+'\'') if context.mode == Context.extended: return context extended_context = Context(context.context_name) extended_context.J.update(context.J) extended_context.M.update(context.M) extended_context.I.update(context.I) # print('Debug - extended - start') # extended_context.display() extended_context.extend_j() # print('Debug - extended - j') # extended_context.display() extended_context.extend_m() # print('Debug - extended - m') # extended_context.display() extended_context.mode = Context.extended return extended_context
def transform_to_distributive_context(self, context): """Generate distributive context from current Can add relations I(j,m) but can't destroy one """ # print('Generate the distributive context \''+context.context_name+'_d\' of the context \''+context.context_name+'\'') if context.mode == Context.distributive: return context distributive_context = Context(context.context_name + '_d') distributive_context.J = copy(context.J) for j in distributive_context.J: j_prime = context.get_j_prime(j) j_filters = set() X = set() for k in distributive_context.J: i_prime = context.get_j_prime(k) if j_prime >= i_prime: j_filters.add(k) else: X.add(k) mj = 'm_' + j distributive_context.add_m(mj) for x in X: distributive_context.add_i(x, mj) return distributive_context
def __init__(self): """ Initialize task-specific variables, load scene fragments, find tools. Derived classes must call through to Task.__init__(self). NOTE: Context must be initialized at this point. """ self.context = Context.getInstance() self.logger = logging.getLogger(__name__) self.active = False
def prepare_testset(self): testcontextls = {} test_context_path = self.testdir + self.testset['casename'] + '.contextls' pdb.set_trace() for testname in self.testset['data']: test_context = Context(testname, self.testcallgraph, self.depth, self.type) testcontextls[testname] = test_context pdb.set_trace() pickle.dump(testcontextls, open(test_context_path, 'wb'))
def __init__(self): self.context = Context.getInstance() # NOTE must contain renderer assert hasattr(self.context, 'renderer') and isinstance(self.context.renderer, Renderer), "Context does not contain renderer of correct type" self.logger = logging.getLogger(__name__) self.hideCube = False self.transform = hm.identity() self.light = Light(self.context.renderer) self.actorFactory = ActorFactory(self.context.renderer) self.actors = [] self.actorsById = dict()
def __init__(self, path_rendered, context, process, link): Context.__init__(self, context) Ccoder.__init__(self, context, process, link) self.path_rendered = path_rendered ##map_ts_obs self.map_ts_obs = {} for x in link['observed']: for ts in x['time_series_id']: self.map_ts_obs[ts] = x['id'] ########################## ##sort context ########################## #tbs: to be sorted tbs = zip(self.ts_id, self._repeated_name_stream, self._repeated_name_ts) #sort by data_stream tbs.sort(key=lambda x: x[1]) #sort by name_ts (in python, sorts are guaranteed to be stable) tbs.sort(key=lambda x: x[2]) #sort by obs_var (in python, sorts are guaranteed to be stable) tbs.sort(key=lambda x: self.obs_var.index(self.map_ts_obs[ x[0] ])) #we need to sort ts_id, _repeated_name_ts, _repeated_name_stream, _repeated_obs_type, data and all the par_fixed involved in the obs_model ind_sorted = [ self.ts_id.index(x[0]) for x in tbs ] self.ts_id = [ self.ts_id[x] for x in ind_sorted ] self._repeated_name_ts = [self._repeated_name_ts[x] for x in ind_sorted] self._repeated_name_stream = [self._repeated_name_stream[x] for x in ind_sorted] self._repeated_obs_type = [self._repeated_obs_type[x] for x in ind_sorted] #data if self.data: self.data = [ [ y[x] for x in ind_sorted ] for y in self.data ]
def __init__(self, gameObject, parent=None): Context.__init__(self, gameObject, parent) self.addChild(pyguiml.SelectionMenu(None, spacing=sf.Vector2(30, 15), \ autoDefineSize = True, alignment=pyguiml.Position.TopLeft, \ permanentActivation=True, permanentSelection=True), name="Layout Menu") self["Layout Menu"].addWidget(pyguiml.Label(None, "Difficulté",\ characterSize=24, font=sf.Font.from_file("DejaVuSans.ttf")), sf.Vector2(0, 0)) self["Layout Menu"].addWidget(\ pyguiml.Button(self, pyguiml.Label(None, "Facile", characterSize=24, \ font=sf.Font.from_file("DejaVuSans.ttf"), color=sf.Color.GREEN)),\ sf.Vector2(1, 0), name="Easy") self["Layout Menu"].addWidget(\ pyguiml.Button(self, pyguiml.Label(None, "Normale", characterSize=24, \ font=sf.Font.from_file("DejaVuSans.ttf"), color=sf.Color.GREEN)),\ sf.Vector2(2, 0), name="Medium") self["Layout Menu"].addWidget(\ pyguiml.Button(self, pyguiml.Label(None, "Difficile", characterSize=24, \ font=sf.Font.from_file("DejaVuSans.ttf"), color=sf.Color.GREEN)),\ sf.Vector2(3, 0), name="Hard") self["Layout Menu"].addWidget(pyguiml.Label(None, "Nombre de vie",\ characterSize=24, font=sf.Font.from_file("DejaVuSans.ttf")), sf.Vector2(0, 1)) self["Layout Menu"].addWidget(pyguiml.Label(None, "Volume",\ characterSize=24, font=sf.Font.from_file("DejaVuSans.ttf")), sf.Vector2(0, 2)) self["Layout Menu"].addWidget(pyguiml.Button(None, pyguiml.Label(None, "Terminer",\ characterSize=24, font=sf.Font.from_file("DejaVuSans.ttf")), \ pyguiml.Image(None, "Ressources/Images/FinishButton.jpg"), \ sf.Rectangle(sf.Vector2(0, 0), sf.Vector2(100, 50))),\ sf.Vector2(0, 3), name="Finish") self["Layout Menu"].addWidget(pyguiml.Slide(None, rect=sf.Rectangle(sf.Vector2(), \ sf.Vector2(500, 25)), step=5, inStep=1, values=sf.Vector2(0, 100)),\ sf.Vector2(1, 2), sf.Vector2(3, 1), name="Volume Value") self._background = pyguiml.Image(None, "Ressources/Images/image.jpg", delTextureCreated = False) self["Layout Menu"].setAllActiveMouseKeyboard(sf.Keyboard.RETURN, sf.Mouse.LEFT) self["Layout Menu"].getChild("Volume Value").howActiveKeyboard = [sf.Keyboard.LEFT, sf.Keyboard.RIGHT]
def readFrequencyFile(self): input_frequencies_file = open(sys.argv[2], "r") lines = input_frequencies_file.readlines() count = 0 for line in lines: row = line.split(",") timestamp = datetime.strptime(row[0], "%Y-%m-%d %H:%M:%S") c = Context(timestamp) button_freq_list = [] mode_freq_list = [] for i in range(1,9): button_freq_list.append(float(row[i])) mode_freq_list.append(float(row[9])) mode_freq_list.append(float(row[10])) c.populateFromFile(button_freq_list, mode_freq_list, int(row[11]), float(row[12])) self.context_history.append(c) count += 1 if count % 10000 == 0: print("Finished Reading Frequency: " + str(count) + " / 270000")
def __init__(self, parameters, context, code, change_code): self.parameters = [] self.context = Context(context) self.code = code + " " self.applied = [] if change_code: for i in range(len(parameters)): self.parameters.append("__" + str(i)) pattern = re.compile("\W" + parameters[i] + "\W") results = pattern.findall(self.code) for res in results: self.code = self.code.replace(res, res.replace(parameters[i], "__" + str(i))) else: self.parameters = parameters
def __init__(self): self.context = Context.getInstance() # NOTE must be initialized self.logger = logging.getLogger(__name__) self.windowWidth = 640 self.windowHeight = 480 self.initialize() self.colorShader = Shader(self.context.getResourcePath('shaders', 'ADS.vert'), self.context.getResourcePath('shaders', 'ADS.frag')) self.proj = hm.perspective(hm.identity(), 35, float(self.windowWidth) / self.windowHeight, 1.0, 1000.0) self.view = hm.lookat(hm.identity(), np.array([0.0, 0.0, 0.0, 1.0], dtype = np.float32), np.array([0.0, 0.0, 1.0, 1.0], dtype = np.float32), np.array([0.0, -1.0, 0.0, 1.0], dtype = np.float32)) self.cameraMatrix = np.dot(self.proj, self.view) self.setCameraMatrix(self.cameraMatrix)
def __init__(self): self.context = Context.getInstance() # NOTE must contain scene self.timer = time.clock() # self.wheelPosition = glfw.GetMouseWheel() self.oldMouseX, self.oldMouseY = glfw.GetMousePos() self.curMouseX = self.oldMouseX self.curMouseY = self.oldMouseY self.leftPressed = False self.rightPressed = False self.manualControl = False self.doQuit = False # flag to signal stop condition self.quitting = False # to prevent multiple key-presses
def get(self): self.context = Context(self.get_parent_context()) if len(self.parameters) < len(self.applied): raise Exception("Invalid Not All Parameters Applied.") for i in range(len(self.applied)): if isinstance(self.applied[i], Var): self.context.setValueForVar(self.parameters[i], self.applied[i].get()) else: self.context.setValueForVar(self.parameters[i], self.applied[i]) if len(self.parameters) != len(self.applied): result = Function(self.parameters[len(self.applied):], self.context, self.code, False) from Parser.StandardParser import StandardParser parser = StandardParser(self.code, self.context) parsed = parser.parse() if parsed is None: return Nil() self.applied = [] return parsed
def __init__(self, name, cmd, eventType, interval=1): self.cmd = cmd self.interval = 1 self.inFrame = True self.allowError = False self.logging = False self.lastOutput = None self.eventType = eventType self.toggle = Toggle() self.toggle.enable() self.context = Context(set([self])) self.context.addRequirement(IsEmacs) self.context.addRequirement(self.toggle) self.context.addRequirement(EmacsEventGenerator.clsToggle) _mapping = { "toggle " + name + " generator" : self.toggleEnabled, "toggle " + name + " logging" : self.toggleLogging, } self.toggleRule = makeContextualRule(name + "ToggleRule", _mapping) self.toggleRule.activate() # always on
def __init__(self, socket, address, service_con): """ 主要是完成一些基本的初始化,创建context上下文 一开始mainService的controller使用全局唯一的那个 而对于room部分,则等到匹配成功之后创建了再设置, 最后还要调用一下当前main环境的on_connection方法,用于通知main环境的服务, 当前有客户端连上来了 :type address: :param socket: gevent的socket类型 :param address: 客户端连接远程地址 :type service_con: Service.MainServiceControllerService :return: """ object.__init__(self) self._sock = socket self._address = address self._closed = False # 用于标记当前连接是否已经关闭了 self._context = Context(self) self._need_late_close = False self._now_con = service_con # 解析出来的body数据交给它来处理 self._now_con.on_connection(self, self._context) # 调用服务的on_connection方法 self._dic_connect_listener = set() # 注册的断线监听器将会保存在这里
class FSocket(object): def __init__(self, socket, address, service_con): """ 主要是完成一些基本的初始化,创建context上下文 一开始mainService的controller使用全局唯一的那个 而对于room部分,则等到匹配成功之后创建了再设置, 最后还要调用一下当前main环境的on_connection方法,用于通知main环境的服务, 当前有客户端连上来了 :type address: :param socket: gevent的socket类型 :param address: 客户端连接远程地址 :type service_con: Service.MainServiceControllerService :return: """ object.__init__(self) self._sock = socket self._address = address self._closed = False # 用于标记当前连接是否已经关闭了 self._context = Context(self) self._need_late_close = False self._now_con = service_con # 解析出来的body数据交给它来处理 self._now_con.on_connection(self, self._context) # 调用服务的on_connection方法 self._dic_connect_listener = set() # 注册的断线监听器将会保存在这里 @property def context(self): """ :rtype: Context.Context """ return self._context @property def sock(self): """ 返回gevent类型的socket """ return self._sock def need_close(self): """ 通过这个标志位让在发送完了一次数据之后关闭当前的socket 这个主要是为了切换socket用,将socket传给另外一个进程 防止当前进程读取下一个进程应该要读取的数据 """ self._need_late_close = True def add_disconnect_listener(self, fn): """ 添加断线监听器 """ self._dic_connect_listener.add(fn) def process(self): """ 经过测试,这种比较的直接的处理方法在响应时间方面具有优势,而且吞吐量好像也差不多 (1)读取4个字节长度的头部,用于标记body的长度 (2)通过获取的body的长度,读取相应长度的body数据,然后交给上层来处理 """ now_data = "" status = 1 body_len = 0 # 用于记录body数据的长度 while not self._closed: try: data = self._sock.recv(2048) except: # 一些紧急rest 关闭,会导致这里出现异常 break if not data: break # 这里其实是连接已经断开了 now_data += data if status == 1: # 当前为接收header的状态 if len(now_data) >= HEAD_LEN: body_len_data = now_data[0:HEAD_LEN] # 获取4个字节长度的头部 body_len, = struct.unpack("i", body_len_data) now_data = now_data[HEAD_LEN:] # 将4个字节的头部从数据中移除 status = 2 # 更改状态标志 if status == 2: # 当前为接收body的状态 if len(now_data) >= body_len: input_data = now_data # 这个就是客户端发送过来的数据 now_data = "" # 清空data status = 1 # 恢复状态标志为 try: out = self._now_con.service(self._context, input_data) except: # 这里这里在处理的过程中出现了异常,那么关闭,结束 logging.error("服务处理错误") logging.error(traceback.format_exc()) break self.write(out) # 这个字段都是在service里面调用的,表示服务返回的数据发送完成之后,需要将 # 这个socket关闭 if self._need_late_close: self.close() self.close() def close(self): """ 这里主要是关闭当前的链接,然后调用当前服务controller的on_disconnect方法 通知上层的代码当前这个链接已经断开了 通过closed标志位来保证关闭逻辑只执行一次 分别调用main和room环境的on_disconnect方法 注意:只有当前在main环境下,客户端关闭才会顺带将context释放掉,如果是在room环境下 那么将不会调用context的release方法,他会在整个战场结束之后才调用release方法 这里主要是为以后实现重连接准备的 注意: 因为这里context与sock对象形成了循环引用,所以这里将_context设置为None来取消循环引用 :return: """ if not self._closed: self._closed = True self._now_con.on_disconnect(self, self._context) self._sock.close() self._context.release() self._context = None self._now_con = None for fn in self._dic_connect_listener: run_task(fn) # 因为当前的执行环境是在主协程上面,所以这里将其派发到协程池中运行 self._dic_connect_listener = None # 将断线监听的引用都释放 def write(self, data): """ 这里完成的事情是将服务层叫发送的数据加上头部,然后通过底层发送出去 注意:这个方法不是协程安全的,所以不能在协程环境下并发调用 注意:这里还要注意data是None的情况,这一般都是服务没有返回数据,所以就直接发送长度为0的标志数据 这里注意了data为None的情况,这个时候返回给客户端的是头部为0的数据 :param data: :return: """ if self._closed: logging.error("write data on close socket") return length = len(data) if data else 0 out_data = struct.pack("i", length) if data: out_data += data try: self._sock.sendall(out_data) except: self.close()
class Function(Expr): def __init__(self, parameters, context, code, change_code): self.parameters = [] self.context = Context(context) self.code = code + " " self.applied = [] if change_code: for i in range(len(parameters)): self.parameters.append("__" + str(i)) pattern = re.compile("\W" + parameters[i] + "\W") results = pattern.findall(self.code) for res in results: self.code = self.code.replace(res, res.replace(parameters[i], "__" + str(i))) else: self.parameters = parameters def get_parent_context(self): return self.context.parent_context def apply(self, params): self.applied = params def get(self): self.context = Context(self.get_parent_context()) if len(self.parameters) < len(self.applied): raise Exception("Invalid Not All Parameters Applied.") for i in range(len(self.applied)): if isinstance(self.applied[i], Var): self.context.setValueForVar(self.parameters[i], self.applied[i].get()) else: self.context.setValueForVar(self.parameters[i], self.applied[i]) if len(self.parameters) != len(self.applied): result = Function(self.parameters[len(self.applied):], self.context, self.code, False) from Parser.StandardParser import StandardParser parser = StandardParser(self.code, self.context) parsed = parser.parse() if parsed is None: return Nil() self.applied = [] return parsed def eval(self): return self.get().eval() def min(self): if len(self.applied) == len(self.parameters): return self.get() return self def type(self): if len(self.applied) > 0: return self.outputType() return Function def outputType(self): return Expr @staticmethod def data(): return "Function: " def copy(self): f = Function(self.parameters, self.context.parent_context, self.code) f.applied = self.applied return f def to_cli(self): if len(self.applied) > 0: return self.get().to_cli() return "Function " + str(self.parameters) + " -> " + self.outputType().data()
def setOptimizationLevel(self, level): Context.checkOptimizationLevel(level) self.optimizationLevel = level
def setLanguageVersion(self, languageVersion): Context.checkLanguageVersion(self.languageVersion) self.languageVersion = self.languageVersion
__author__ = 'blu2' import zerorpc import sys from myRDD import * import StringIO import cloudpickle from datetime import datetime import params from Context import Context if __name__ == '__main__': C = Context() R = C.init() rdd = R.TextFile("inputfile4.txt").flatMap(lambda x: x.split(" ")).map(lambda x: (x, 1)).reduceByKey_Hash(lambda a, b: a + b) print rdd.collect()
def __init__(self): """Initialize tool-specific behavior here.""" self.context = Context.getInstance() self.logger = logging.getLogger(__name__) self.active = False
class EmacsEventGenerator(object): clsToggle = Toggle() clsLogging = False def __init__(self, name, cmd, eventType, interval=1): self.cmd = cmd self.interval = 1 self.inFrame = True self.allowError = False self.logging = False self.lastOutput = None self.eventType = eventType self.toggle = Toggle() self.toggle.enable() self.context = Context(set([self])) self.context.addRequirement(IsEmacs) self.context.addRequirement(self.toggle) self.context.addRequirement(EmacsEventGenerator.clsToggle) _mapping = { "toggle " + name + " generator" : self.toggleEnabled, "toggle " + name + " logging" : self.toggleLogging, } self.toggleRule = makeContextualRule(name + "ToggleRule", _mapping) self.toggleRule.activate() # always on def activate(self): self.subHandles = [] self.subHandles.append(getLoop().subscribeTimer(self.interval, self.update, priority=0)) self.subHandles.append(getLoop().subscribeEvent(FocusChangeEvent, self.update, priority=0)) self.subHandles.append(getLoop().subscribeEvent(EmacsConnectedEvent, self.update, priority=0)) def deactivate(self): for h in self.subHandles: h.unsubscribe() def update(self, ev=None): window = ev.window if ev else getFocusedWindow() newOutput = runEmacsCmd(self.cmd, inFrame=self.inFrame, allowError=self.allowError, dolog=(self.logging or self.clsLogging)) newOutput = self._postProcess(newOutput) if newOutput == self.lastOutput: return self.lastOutput = newOutput #log.info("New output!") pushEvent(self._makeEvent(newOutput)) def _makeEvent(self, newOutput): return self.eventType(newOutput) def _postProcess(self, output): lst = grammar.getStringList(output) lst.sort() return lst def toggleLogging(self, ev=None): self.logging = not self.logging log.info("Setting %s watcher logging to: %s" % (type(self), self.logging)) def toggleEnabled(self, ev=None): self.toggle.flip() log.info("Setting %s watcher to: %s" % (type(self), self.toggle.satisfied)) @classmethod def toggleAllGenerators(cls, ev=None): cls.clsToggle.flip() log.info("Setting all generators to: %s" % cls.clsToggle.satisfied) @classmethod def toggleAllGeneratorsLogging(cls, ev=None): cls.clsLogging = not cls.clsLogging log.info("Setting all generators logging to: %s" % cls.clsLogging)
def sendCommands(self, action): fullActuatorList = self.context.getProperty(ConfigurationConstants.getFullActuatorList()) if fullActuatorList: tokens = ''.join(fullActuatorList.split()).split(';') for tok in tokens: if tok: eventTopic = self.makeActionEvent(EventTopics.getActuatorAction(), tok, action) self.publishEvent(eventTopic, tok, action, action) try: time.sleep(0.01) except Exception, e: self.logger.error("Error on TimeShiftActionRule.sendCommands(): %s" % (e)) if __name__ == "__main__": context = Context(3) logger = logging.getLogger('RestoreStatusRule') logger.setLevel(logging.DEBUG) hdlr = logging.FileHandler('log/rule.log') formatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s") hdlr.setFormatter(formatter) logger.addHandler(hdlr) consoleHandler = logging.StreamHandler() consoleHandler.setFormatter(formatter) logger.addHandler(consoleHandler) rule = DefaultTimerRule(context, logger, "conf/agents/rule.conf") rule.process() rule2 = DelayTimerActionRule(context, logger, None) rule2.process() time.sleep(10.0) context.updateProperty(ConfigurationConstants.getPresence(), str(True))
from Context import Context from EditDistance import edits from WordFrequency import WordFrequency import re import Readers count_1w = WordFrequency.from_freq_file("data/Norvig/wordfreqs/count_1w.txt") count_2w = WordFrequency.from_freq_file("data/Norvig/wordfreqs/count_2w.txt") def corrections(text): "Spell-correct all words in text." return re.sub('[a-zA-Z]+', lambda m: correct(m.group(0)), text) def correct(context): "Return the word that is the most likely spell correction of w." candidates = edits(context.word()).items() #c, edit = max(candidates, key=lambda (c,e): Pedit(e) * Pw(c)) #return c for context in Context.gen_context_sequence_from_word_sequence(Readers.gen_words_from_file("doc.txt")): correct(context)
config.set(ConfigurationConstants.getRuleSettings(), u, self.getContext().getProperty(u)) for keyword in ConfigurationConstants.getRuleSettingsKeywords(): value = self.context.getProperty(keyword) if value: config.set(ConfigurationConstants.getRuleSettings(), keyword, value) config.write(f) except Exception, e: self.logger.error ("Error on SaveStatusRule.process(): %s" % (e)) def stop(self): pass if __name__ == "__main__": context = Context(3) context.updateProperty(ConfigurationConstants.getFullUserList(), "ciao;edo;prova") context.updateProperty(ConfigurationConstants.getMessageBroker(), "broker") context.updateProperty("ciao", "True") context.updateProperty("edo", "True") context.updateProperty("prova", "false") context.updateProperty(ConfigurationConstants.getIsDelayTimerOn(), "True") logger = logging.getLogger('RestoreStatusRule') hdlr = logging.FileHandler('log/rule.log') formatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s") hdlr.setFormatter(formatter) logger.addHandler(hdlr) rule = SaveStatusRule(context, logger, "conf/agents/rule.conf") rule.process()
def __init__(self): #sys.argv = ['Main.py', '../res/videos/test-14.mpeg', '--hide_input'] # [debug: run with set command-line args] # * Initialize global context, passing in custom command line args (parsed by Context) argParser = argparse.ArgumentParser(add_help=False) showInputGroup = argParser.add_mutually_exclusive_group() showInputGroup.add_argument('--show_input', dest='show_input', action="store_true", default=True, help="show input video (emulate see-through display)?") showInputGroup.add_argument('--hide_input', dest='show_input', action="store_false", default=False, help="hide input video (show only virtual objects)?") argParser.add_argument('--task', default="Task", help="task to run (maps to class name)") argParser.add_argument('--scene', dest="scene_files", metavar='SCENE_FILE', nargs='+', help="scene fragment(s) to load (filenames in <res>/data/)") self.context = Context.createInstance(description="Tangible Data Exploration", parent_argparsers=[argParser]) self.context.main = self # hijack global context to share a reference to self # NOTE Most objects require an initialized context, so do this as soon as possible # * Obtain a logger (NOTE Context must be initialized first since it configures logging) self.logger = logging.getLogger(__name__) self.logger.info("Resource path: {}".format(self.context.resPath)) if not haveCV: self.logger.warn("OpenCV library not available") # * Initialize GL rendering context and associated objects (NOTE order of initialization may be important) self.context.renderer = Renderer() self.context.controller = Controller() # * Initialize scene and load base scene fragments, including tools self.context.scene = Scene() self.context.scene.readXML(self.context.getResourcePath('data', 'CubeScene.xml')) # just the cube #self.context.scene.readXML(self.context.getResourcePath('data', 'DragonScene.xml')) # Stanford Dragon #self.context.scene.readXML(self.context.getResourcePath('data', 'BP3D-FMA7088-heart.xml')) # BodyParts3D heart model hierarchy #self.context.scene.readXML(self.context.getResourcePath('data', 'RadialTreeScene.xml')) #self.context.scene.readXML(self.context.getResourcePath('data', 'PerspectiveScene.xml')) # ** Load scene fragments specified on commandline (only need to specify filename in data/ directory) self.logger.info("Scene fragment(s): %s", self.context.options.scene_files) if self.context.options.scene_files is not None: for scene_file in self.context.options.scene_files: self.context.scene.readXML(self.context.getResourcePath('data', scene_file)) # * Initialize task (may load further scene fragments, including task-specific tools) try: taskModule = import_module('task.' + self.context.options.task) # fetch module by name from task package taskType = getattr(taskModule, self.context.options.task) # fetch class by name from corresponding module (same name, by convention) self.context.task = taskType() # create an instance of specified task class except Exception as e: self.logger.error("Task initialization error: {}".format(e)) self.context.task = Task() # fallback to dummy task # * Finalize scene (resolves scene fragments into one hierarchy, builds ID-actor mapping) self.context.scene.finalize() # NOTE should be called after all read*() methods have been called on scene # * Find cube in scene self.cubeActor = self.context.scene.findActorById('cube') self.cubeComponent = self.cubeActor.components['Cube'] if self.cubeActor is not None else None # * Open camera/input file self.logger.info("Input device/file: {}".format(self.context.options.input_source)) self.camera = cv2.VideoCapture(self.context.options.input_source) if not self.context.isImage else cv2.imread(self.context.options.input_source) # TODO move some more options (e.g. *video*) to context; introduce config.yaml-like solution with command-line overrides self.options={ 'gui': self.context.options.gui, 'debug': self.context.options.debug, 'isVideo': self.context.isVideo, 'loopVideo': self.context.options.loop_video, 'syncVideo': self.context.options.sync_video, 'videoFPS': self.context.options.video_fps, 'isImage': self.context.isImage, 'cameraWidth': cameraWidth, 'cameraHeight': cameraHeight, 'windowWidth': windowWidth, 'windowHeight': windowHeight } self.context.videoInput = VideoInput(self.camera, self.options) # TODO If live camera, let input image stabilize by eating up some frames, then configure camera # e.g. on Mac OS, use uvc-ctrl to turn off auto-exposure: # $ ./uvc-ctrl -s 1 3 10 # * Create image blitter, if input is to be shown if self.context.options.show_input: self.context.imageBlitter = FrameProcessorGL(self.options) # CV-GL renderer that blits (copies) CV image to OpenGL window # TODO Evaluate 2 options: Have separate tracker and blitter/renderer or one combined tracker that IS-A FrameProcessorGL? (or make a pipeline?) self.logger.info("Video see-through mode enabled; input video underlay will be shown") else: self.logger.info("Video see-through mode disabled; only virtual objects will be shown") # * Setup tracking self.context.cubeTracker = CubeTracker(self.options) # specialized cube tracker, available in context to allow access to cubeTracker's input and output images etc. if self.cubeComponent is not None: self.logger.info("Tracking setup: Cube has {} markers".format(len(self.cubeComponent.markers))) self.context.cubeTracker.addMarkersFromTrackable(self.cubeComponent)
def run(self): pc = 0 context = Context() stack = Stack() self.dprint("Begining execution...") while True: line = self.bytecode[pc] opcode = line[0] arg = ' '.join(line[1:]) if opcode == "LOAD": try: if float(arg) == int(arg): self.dprint("Load '{}' as int" .format(arg)) stack.push(int(arg)) else: self.dprint("Load '{}' as float" .format(arg)) stack.push(float(arg)) except ValueError: if context.getSymbol(arg) is not None: self.dprint("Load symbol '{}'" .format(arg)) stack.push(context.getSymbol( arg)) else: self.dprint("Raw load '{}'". format(arg)) stack.push(arg) elif opcode == "LOADSTR": arg = arg[1:-1] stack.push(arg) self.dprint("Load '{}' as string".format(arg)) elif opcode == "STORE": val = stack.pop() self.dprint("Store '{}' as symbol '{}'" .format(val,arg)) context.setSymbol(arg,val) elif opcode == "ADD": val2 = stack.pop() val1 = stack.pop() if isinstance(val2,str) or isinstance(val1,str): stack.push(''.join([str(val1),str(val2)])) self.dprint("Add {} and {} as str".format(val1,val2)) else: stack.push(val1 + val2) self.dprint("Add {} and {}".format(val1,val2)) elif opcode == "SUBTRACT": val2 = stack.pop() val1 = stack.pop() stack.push(val1 - val2) self.dprint("Subtract {} from {}".format( val2,val1)) elif opcode == "MULTIPLY": val2 = stack.pop() val1 = stack.pop() stack.push(val1 * val2) self.dprint("Multiply {} and {}".format( val1,val2)) elif opcode == "DIVIDE": val2 = stack.pop() val1 = stack.pop() stack.push(val1 / val2) self.dprint("Divide {} and {}".format( val1,val2)) elif opcode == "LESSTHAN": val2 = stack.pop() val1 = stack.pop() stack.push(val1 < val2) self.dprint("{} < {}".format(val1,val2)) elif opcode == "GREATERTHAN": val2 = stack.pop() val1 = stack.pop() stack.push(val1 > val2) self.dprint("{} > {}".format(val1,val2)) elif opcode == "EQUALS": val2 = stack.pop() val1 = stack.pop() stack.push(val1 == val2) self.dprint("{} == {}".format(val1,val2)) elif opcode == "NEGATE": val1 = stack.pop() stack.push(-1*val1) self.dprint("Negate {}".format(val1)) elif opcode == "BNOT": val1 = stack.pop() stack.push(not val1) self.dprint("BoolNot {}".format(val1)) elif opcode == "AND": val2 = stack.pop() val1 = stack.pop() stack.push(val2 and val1) self.dprint("{} AND {}".format(val2,val1)) elif opcode == "OR": val2 = stack.pop() val1 = stack.pop() stack.push(val2 or val1) self.dprint("{} OR {}".format(val2,val1)) elif opcode == "POWER": val1 = stack.pop() val2 = stack.pop() stack.push(val2**val1) elif opcode == "PAUSE": if arg: val = arg else: val = stack.pop() sleep(val) self.dprint("Sleep for {} seconds".format(val)) elif opcode == "JUMPNEWCONTEXT": context = context.newContext() context.setReturnPc(pc) pc = int(arg)-1 self.dprint("Procedure call to line {}" .format(pc)) elif opcode == "JUMPOLDCONTEXT": pc = context.getReturnPc() context = context.destroy() self.dprint("Return to caller") elif opcode == "JUMPIFNOT": loc = int(arg) condition = not stack.pop() if condition: self.dprint("Jump to {}".format(loc)) pc = loc-1 else: self.dprint("Jump not taken") elif opcode == "JUMP": loc = int(arg) pc = loc-1 self.dprint("Jumping back to loop condition.") elif opcode == "INPUT": if arg: val = input(arg) else: val = input() try: if float(val) == int(val): stack.push(int(val)) else: stack.push(float(val)) except ValueError: stack.push(val) self.dprint("Read input '{}'".format(val)) elif opcode == "PRINT": if arg: val = context.getSymbol(arg) else: val = stack.pop() self.dprint("Printing '{}'".format(val)) if isinstance(val,str): val = val.replace("\\n","\n") val = val.replace("\_"," ") val = val.replace("\\","") print(val,end="") elif opcode == "TERM": self.dprint("Terminating...") input("Press ENTER to continue...") break else: self.dprint("Unexpected opcode '{}'".format(opcode)) raise Exception("VirtualMachine - Invalid Opcode") pc += 1