def patchInitState(self, newState): s = State() s.patch(self.initState) self.patchedStateSequence.append(s) self.initState.patch(newState) self.patchSequence.append(newState)
def move(self, direction): moved = Level.move(self, direction) if moved and self.weapon: self.weapon.move(direction) if moved: State.use_turn() return moved
def getStateFromStr(self, stateStr): s = State() for rawPropositionStr in stateStr.split("\n"): propositionStr = rawPropositionStr.strip().replace("(", " ").replace(")", " ").replace(",", " ").lower() propositionStr = "(" + propositionStr.strip() + ")" if propositionStr != "()": if propPattern.match(propositionStr) != None: s.addProposition(propositionStr) else: print "not a proposition: " + propositionStr return s
def handleApplicationInit(): import State if not appinfo.args.nomodstartup: for m in State.modules: m.start() else: # In some cases, we at least need some modules. Start only those. if appinfo.args.shell: State.getModule("stdinconsole").start() global successStartup successStartup = True
def link(origin, tree): list_to_return = [] #must contain the new transitions(origin, subtree) that will be needed and delete the oldones aux_state = State() aux_destination = origin.delete_transition(tree) origin.add_transition(tree.right, aux_state) list_to_return.append((origin, tree.right)) for d in aux_destination: aux_state.add_transition(tree.left, d) list_to_return.append((aux_state, tree.left)) return list_to_return
def execute(self): if self.action == 'add': State.add_input_stream(self.stream_label, self.data_format, self.interface_id, self.filter_address) elif self.action == 'dismount': State.dismount_input_stream(self.stream_label) else: print 'Invalid input_stream_command action' r = Response.SetInputStream( return_code='0', dimino6_return_code='0', list=[]) return str(r)
def set_mix_density(self,state,i,mean,covariance,precision): ''' set state mixture i's density function ''' tmp_name = self.states[state]._node_em._mix_densities[i].get_name() tmp_density = State.mixture_density(tmp_name,mean,covariance,precision) self.states[state]._node_em.set_mix_density(i,tmp_density)
def purgeFactsWithSymbol(self, symbol): #In order to log the change, create a state # with facts that match symbol # remove from both true set and false set s = State() s.patch(self.initState) self.patchSequence.append("Purge symbol: "+symbol) self.patchedStateSequence.append(s) for prop in s.getTrueProps(): if symbol in prop: self.initState.removeTrueProp(prop) for prop in s.getFalseProps(): if symbol in prop: self.initState.removeFalseProp()
def rotate(self, direction): """ :param direction: -1 or 1, -1 -> ccw, 1 -> cw """ self.facing += direction if self.facing <= 0: self.facing = 8 elif self.facing > 8: self.facing = 1 self.rotation = (self.facing - 1) * 45 if self.weapon: self.weapon.on_rotate(direction) State.use_turn()
def fringe_expansion(current_state, fringe): moves = [(0, 1), (0, -1), (-1, 0), (1, 0)] for m in moves: if current_state.board.slide_blank(m) is None: continue else: fringe.append( State.State(current_state.board.slide_blank(m), current_state, current_state.depth + 1))
def execute(self): logging.info('params: %s'%s.__dict__) if self.action == 'on': State.on_record_session(self.start_time, self.duration, self.data_size, self.scan_name, self.experiment_name, self.station_code) elif self.action == 'off': State.off_record_session(self) else: print 'Invalid record action' # TODO: fill in parameters. return Response.SetRecord( return_code='0', dimino6_return_code='0', list=[])
def read_empty_map(data): states = [] with open(data, 'r') as info: for state in info: split_state = state.split(',') x = State.State(split_state[0], split_state[1]) states.append(x) make_adjecent_states(data, states) return states
def breadth_first_search(): initial_state = State(3, 3, 'left', 0, 0) if initial_state.final(): return initial_state unexploCOLOR2valid = list() exploCOLOR2 = set() unexploCOLOR2valid.append(initial_state) while unexploCOLOR2valid: state = unexploCOLOR2valid.pop(0) if state.final(): return state exploCOLOR2.add(state) child = childstate(state) for child in child: if (child not in exploCOLOR2) or (child not in unexploCOLOR2valid): unexploCOLOR2valid.append(child) return None
def test_clean_neighborhood(self): """Test clean_neighborhood() method.""" invalid_neighbors = ["A",] er = [] state = State.State(copy.deepcopy(TEST_STATES_DICT["B"])) state.clean_neighborhood(invalid_neighbors) self.assertEqual(er, state.get_neighbors())
def back_track(self, state): """ Returns list of actions from initial state till goal state """ list = [] while state.parent: list.append(St.Actions(state.action)) state = state.parent return list
def print_state_transitions(G): for edge in G.edges(): # Dont display a transition that goes to itself if not edge[0] == edge[1]: # Literally evaluate the state label to get the state values begin_state = ast.literal_eval(edge[0]) end_state = ast.literal_eval(edge[1]) # Print the transition print("State:") begin_state_obj = State.State(begin_state[0], begin_state[1], begin_state[2], begin_state[3], begin_state[4]) begin_state_obj.pretty_print() end_state_obj = State.State(end_state[0], end_state[1], end_state[2], end_state[3], end_state[4]) print_transition(begin_state_obj, end_state_obj) end_state_obj.pretty_print()
def __init__(self, StateCount): # StateCount - count состояний self.States = [] # Состояния сетевого графика self.Works = [] # Работы с.г. self.FullPaths = [] # Полные пути self.CriticalPathTime = None # Время кр. пути self.CriticalPathNumb = None # Номер кр. пути self.ShortedPathTime = None # Время кратчайшего пути for i in range(StateCount): self.States.append(State.State(len(self.States)))
def __init__(self, chatMgr): self.chatMgr = chatMgr self.whisperAvatarId = None self.sentenceList = [] qtGraph = {} self.setupQTGraph() self.fsm = FSM.FSM('QuickTalker', [ State.State('Hidden', self._ChatInputQuickTalker__enterHidden, self._ChatInputQuickTalker__exitHidden, ['Constructing']), State.State('Constructing', self._ChatInputQuickTalker__enterConstructing, self._ChatInputQuickTalker__exitConstructing, ['Constructing', 'SayIt', 'Hidden']), State.State('SayIt', self._ChatInputQuickTalker__enterSayIt, self._ChatInputQuickTalker__exitSayIt, ['Hidden']) ], 'Hidden', 'Hidden') self.fsm.enterInitialState()
def __init__(self, cr): DistributedObject.DistributedObject.__init__(self, cr) self.toons = [] self.activeIntervals = {} self.openSfx = base.loadSfx('phase_5/audio/sfx/elevator_door_open.mp3') self.closeSfx = base.loadSfx( 'phase_5/audio/sfx/elevator_door_close.mp3') self.suits = [] self.reserveSuits = [] self.joiningReserves = [] self.distBldgDoId = None self.currentFloor = -1 self.numFloors = None self.elevatorName = self._DistributedSuitInterior__uniqueName( 'elevator') self.floorModel = None self.elevatorOutOpen = 0 self.BottomFloor_SuitPositions = [ Point3(0, 15, 0), Point3(10, 20, 0), Point3(-7, 24, 0), Point3(-10, 0, 0) ] self.BottomFloor_SuitHs = [75, 170, -91, -44] self.Cubicle_SuitPositions = [ Point3(0, 18, 0), Point3(10, 12, 0), Point3(-9, 11, 0), Point3(-3, 13, 0) ] self.Cubicle_SuitHs = [170, 56, -52, 10] self.BossOffice_SuitPositions = [ Point3(0, 15, 0), Point3(10, 20, 0), Point3(-10, 6, 0), Point3(-17, 34, 11) ] self.BossOffice_SuitHs = [170, 120, 12, 38] self.waitMusic = base.loadMusic( 'phase_7/audio/bgm/encntr_toon_winning_indoor.mid') self.elevatorMusic = base.loadMusic( 'phase_7/audio/bgm/tt_elevator.mid') self.fsm = FSM.FSM('DistributedSuitInterior', [ State.State('WaitForAllToonsInside', self.enterWaitForAllToonsInside, self.exitWaitForAllToonsInside, ['Elevator']), State.State('Elevator', self.enterElevator, self.exitElevator, ['Battle']), State.State('Battle', self.enterBattle, self.exitBattle, ['Resting', 'Reward', 'ReservesJoining']), State.State('ReservesJoining', self.enterReservesJoining, self.exitReservesJoining, ['Battle']), State.State('Resting', self.enterResting, self.exitResting, ['Elevator']), State.State('Reward', self.enterReward, self.exitReward, ['Off']), State.State('Off', self.enterOff, self.exitOff, ['Elevator', 'WaitForAllToonsInside', 'Battle']) ], 'Off', 'Off') self.fsm.enterInitialState()
def a_star(self, heuristic): node = self.tree.create_node(state=State(self.wrigglers), pathCost=0) node.heuristic = heuristic(node) frontier = PQDict() stateFrontier = {} explored = {} # Sacrifice memory to have a huge speed up being able to instantly check for state in frontier stateFrontier[str(node.state)] = node.heuristic frontier.additem(node._identifier, node.heuristic) while(True): if(len(frontier) == 0): return None nodeID = frontier.popitem()[0] node = self.tree.get_node(nodeID) nodeStateStr = str(node.state) del stateFrontier[nodeStateStr] if self.testGoal(node.state): return node explored[nodeStateStr] = -1 # we don't care what the hash matches actions = self.getActions(node.state) for action in actions: child = self.childNode(node, action) child.heuristic = heuristic(child) childStr = str(child.state) inExplored = False inFrontier = False if childStr in explored: inExplored = True bGreater = False if childStr in stateFrontier: if(stateFrontier[childStr] < child.heuristic + child.pathCost): bGreater = True inFrontier = True if(not inExplored and not inFrontier): stateFrontier[childStr] = child.heuristic frontier.additem(child._identifier, child.heuristic + child.pathCost) elif(bGreater): bHappened = False for key in frontier: if(str(self.tree.get_node(key).state) == childStr): bHappened = True frontier.pop(key) frontier.additem(child._identifier, child.heuristic + child.pathCost) break assert bHappened
def __init__(self, cr): DistributedObject.DistributedObject.__init__(self, cr) self.localToonOnBoard = 0 self.openSfx = base.loadSfx('phase_5/audio/sfx/elevator_door_open.mp3') self.closeSfx = base.loadSfx('phase_5/audio/sfx/elevator_door_close.mp3') self.fsm = FSM.FSM('DistributedElevatorInt', [ State.State('off', self.enterOff, self.exitOff, [ 'opening', 'waitCountdown', 'closing', 'closed']), State.State('opening', self.enterOpening, self.exitOpening, [ 'waitCountdown']), State.State('waitCountdown', self.enterWaitCountdown, self.exitWaitCountdown, [ 'closing']), State.State('closing', self.enterClosing, self.exitClosing, [ 'closed']), State.State('closed', self.enterClosed, self.exitClosed, [ 'opening'])], 'off', 'off') self.fsm.enterInitialState() return None return
def __init__(self, cr): townBattle = cr.playGame.getPlace().townBattle DistributedBattleBase.DistributedBattleBase.__init__(self, cr, townBattle) self.streetBattle = 0 self.fsm.addState(State.State('BuildingReward', self.enterBuildingReward, self.exitBuildingReward, [ 'Resume'])) offState = self.fsm.getStateNamed('Off') offState.addTransition('BuildingReward') playMovieState = self.fsm.getStateNamed('PlayMovie') playMovieState.addTransition('BuildingReward')
def idsNextState(node, visited): childArray = [] if node.state.dirt_tuples is not None and node.state.vc_coord in node.state.dirt_tuples: newDirtTuples = copy.deepcopy(node.state.dirt_tuples) newDirtTuples.remove(node.state.vc_coord) newVcCoord = copy.deepcopy(node.state.vc_coord) newNode = IdsNode(State(newVcCoord, newDirtTuples), node, "S", node.nodeCost + 1, node.depth + 1) childArray.append(newNode) else: if node.state.vc_coord[0] != 0: newNode = IdsNode( State([node.state.vc_coord[0] - 1, node.state.vc_coord[1]], node.state.dirt_tuples), node, "MU", node.nodeCost + 2, node.depth + 1) if newNode.state not in visited: childArray.append(newNode) if node.state.vc_coord[0] != 9: newNode = IdsNode( State([node.state.vc_coord[0] + 1, node.state.vc_coord[1]], node.state.dirt_tuples), node, "MD", node.nodeCost + 2, node.depth + 1) if newNode.state not in visited.keys(): childArray.append(newNode) if node.state.vc_coord[1] != 0: newNode = IdsNode( State([node.state.vc_coord[0], node.state.vc_coord[1] - 1], node.state.dirt_tuples), node, "ML", node.nodeCost + 2, node.depth + 1) if newNode.state not in visited.keys(): childArray.append(newNode) if node.state.vc_coord[1] != 9: newNode = IdsNode( State([node.state.vc_coord[0], node.state.vc_coord[1] + 1], node.state.dirt_tuples), node, "MR", node.nodeCost + 2, node.depth + 1) if newNode.state not in visited.keys(): childArray.append(newNode) return childArray
def gameLogic(update, context): textReceived: str = update.message.text.lower() username = update.message.from_user.username if textReceived in ["quit", "exit"]: showQuitGameMessage(update, context) State.popState(username) State.changeMenuNow(update, context) elif textReceived == GAME_DATA["data"][username]["word"].lower(): showCorrectGuessMessage(update, context) State.popState(username) State.changeMenuNow(update, context)
def idsCall(): if dirtlist is None: return time_start = time.process_time() initialDirtTuple = list_to_xy_coord(dirtlist) print('-------------------------IDS--------------------------') print('Initial Dirt List --', initialDirtTuple) finalDirtTuple = [] initalState = State([vc_x, vc_y], initialDirtTuple) finalState = State([9, 9], finalDirtTuple) global IDSanslist IDSanslist = ids(initalState, finalState) print('Action Sequence --', IDSanslist[0], '\nPath Cost --', IDSanslist[1], '\nTotal no of nodes created --', IDSanslist[2], '\nMax size of auxiliary queue generated--', IDSanslist[3]) global IDStime_elapsed IDStime_elapsed = time.process_time() - time_start print('\nTime Elapsed for IDS --', IDStime_elapsed, 'seconds') print('---------------------------------------------------')
def test_states_can_transition(self): # ARRANGE fake_state = State.VeryFatState("Fake", []) new_map = Map.Map([fake_state]) # ACT new_map.convert_state(fake_state, "Very Thin") # ASSERT self.assertEqual(new_map.list_categories()["Fake"], "Very Thin")
def TryAddExapnasionToList(self, position, listOfExpandedNodes): if( not self.CurrentState.isShiftOperationPossible(position)): return False newStateList = Helper.DeepCopy2dArray(self.CurrentState.StateList) newState = State.State(newStateList, self.CurrentState.EmptyValue) newState.PerformShiftOperation(position) newNode = FrontierNode(self, newState, self.GoalState, self.AlgorithmType, self.HeuristicType) listOfExpandedNodes.append(newNode) return True
def test(): etat = s.State(3, 3) etat.create() etat.setCurrentPlayer("j1") etat.board[0][0] = "j1" etat.board[-1][-1] = "j2" etat.affiche() iaj = ia.IA("j1", 3, False) iaj.decide(etat) print(iaj.nombreNoeud)
def __init__(self, hood, parentFSMState, doneEvent): StateData.StateData.__init__(self, doneEvent) self.hood = hood self.parentFSMState = parentFSMState self.fsm = FSM.FSM('TownLoader', [ State.State('start', self.enterStart, self.exitStart, ['quietZone', 'street', 'toonInterior']), State.State('street', self.enterStreet, self.exitStreet, ['quietZone']), State.State('toonInterior', self.enterToonInterior, self.exitToonInterior, ['quietZone']), State.State('quietZone', self.enterQuietZone, self.exitQuietZone, ['street', 'toonInterior']), State.State('final', self.enterFinal, self.exitFinal, ['start']) ], 'start', 'final') self.branchZone = None self.placeDoneEvent = 'placeDone' self.townBattleDoneEvent = 'town-battle-done' return
def __main__(): order = State.Order() print("Hello! What game would you like to search?") answer = input("") while order.state is not None: order.answer(answer) answer = input("")
def ids_solver(board, limit, goal_board): found = False fringe = [State.State(board, None, 0, 0)] horizon = 0 while not found and limit > 0: limit -= 1 found = ids(fringe, limit, goal_board, horizon) if type(found) is State.State: return found return None
def text(update, context): username = update.message.from_user.username if State.lastState(username) == False: if botHelpMenu.evalInput(update): pass elif GameMenu.evalInput(update): pass elif coins.evalInput(update): pass else: return # state = State.getState(username, 0) state = State.lastState(username) if state != False: state(update, context) else: print("State not found")
def pick_action(self, state, legal): """ Runs through the Q-learning process and returns an action for pacman to take. It will either be the best action (exploit) or a random action (explore) Keyword Arguments state - The gamestate of the pacman game legal - List of legal actions Returns action - The action which will be taken """ # Define the current state curr_state = State.State(state) # intialise the space in q learner self.initialise_space(curr_state, legal) if (self.previous_state == None): # pick a random action action = random.choice(legal) # collect the reward reward = state.getScore() # Set the previous state, reward and actions self.previous_state = curr_state self.previous_action = action self.previous_reward = reward return action else: # Define the state-action pair sa = StateActionPair.StateActionPair(self.previous_state, self.previous_action) # Calculate the score score = state.getScore() # Update the q score self.update_q_score(sa, legal, curr_state, score) # Return an action action = self.epsilon_policy(curr_state, legal) # Update the previous state, action and reward self.previous_state = curr_state self.previous_action = action self.previous_score = score return action
def main(): global pix global elevations img = Image.open('elevations_pixels.PNG') pix = img.load() with open('elevations.txt') as f: elevations = [line.split() for line in f] img.show() #do_fall() #do_winter() #do_spring() #img.show() #return print("done") print(len(elevations)) points = [] if (len(sys.argv) > 2): print("argument was passed!") with open(sys.argv[1]) as f: points = [tuple([int(i) for i in line.split()]) for line in f] season = int(sys.argv[2]) change_season(season) paths = [] stime = time.time() for i in range(len(points) - 1): start = points[i] end = points[i + 1] init = State.State(elevations[start[0]][start[1]], Terrain.GetTerrainVal(pix[start[0], start[1]]), start[0], start[1], end[0], end[1]) paths.append(A_star(init)) etime = time.time() counter = 1 for path in paths: path.reverse() hr_output(path, counter) counter += 1 for s in path: pix[s.x, s.y] = (255, 0, 0, 255) print(etime - stime) img.show() img.close() #print(points) # no file parameter passed, defaults to using points for brown path else: print("Usage: python3 orienteering.py file [season mode bit]") print("\tSEASON MODE BITS") print("\t0 -> summmer") print("\t1 -> fall") print("\t2 -> winter") print("\t3 -> spring") points = [(230, 327), (276, 279), (303, 240), (306, 286), (290, 310), (304, 331), (306, 341), (253, 372), (246, 355), (288, 338), (282, 321), (243, 327), (230, 327)]
def __init__(self): try: self.ToonHead_initialized except: self.ToonHead_initialized = 1 Actor.Actor.__init__(self) self.toonName = 'ToonHead-' + str(self.this) self.__blinkName = 'blink-' + self.toonName self.__stareAtName = 'stareAt-' + self.toonName self.__lookName = 'look-' + self.toonName self.__eyes = None self.__eyelashOpen = None self.__eyelashClosed = None self.__lod500Eyes = None self.__lod250Eyes = None self.__lpupil = None self.__lod500lPupil = None self.__lod250lPupil = None self.__rpupil = None self.__lod500rPupil = None self.__lod250rPupil = None self.__muzzle = None self.__eyesOpen = ToonHead.EyesOpen self.__eyesClosed = ToonHead.EyesClosed self.eyelids = FSM.FSM('eyelids', [ State.State('off', self.enterEyelidsOff, self.exitEyelidsOff, [ 'open', 'closed', 'surprised']), State.State('open', self.enterEyelidsOpen, self.exitEyelidsOpen, [ 'closed', 'surprised', 'off']), State.State('surprised', self.enterEyelidsSurprised, self.exitEyelidsSurprised, [ 'open', 'closed', 'off']), State.State('closed', self.enterEyelidsClosed, self.exitEyelidsClosed, [ 'open', 'surprised', 'off'])], 'off', 'off') self.eyelids.enterInitialState() self.__stareAtNode = NodePath() self.__defaultStarePoint = Point3(0, 0, 0) self.__stareAtPoint = self.__defaultStarePoint self.__stareAtTime = 0 self.lookAtPositionCallbackArgs = None return None return
def loadNodefromTransitionTable(self, property_table, transition_table): state_list = [] for i in range(len(property_table)): succesorid = [] for j in range(len(transition_table)): if property_table[i][0] == transition_table[j][0]: succesorid.append(int(transition_table[j][1])) state = State(int(property_table[i][0]), bool(property_table[i][1]), succesorid) state_list.append(state) return state_list
def __init__(self, start, hmode): self.hmode = hmode self.S0 = State.State(start, 'None') self.Open = [] self.Open.append(self.S0) self.Closed = [] self.G = [] self.G.append(self.S0) self.result = 0 self.step = 0 self.post = []
def AR_step(prev_state): # states with autoregressive components ar_step = tf.zeros_like(prev_state) for i in range(len(sigma_T_n)): ar_step = State.update(ar_step,'TD_'+str(i) + '_x', rhoT_n*tf.math.log(State.__dict__[ 'TD_'+str(i) + '_x'](state))) for i in range(len(sigmaPhi_n)): ar_step = State.update(ar_step,'phi_'+str(i) + '_x', phi_n*tf.math.log(State.__dict__[ 'phi_'+str(i) + '_x'](state))) for i in range(len(sigmaChi_n)): ar_step = State.update(ar_step,'chi_'+str(i) + '_x', rhoChi_n*tf.math.log(State.__dict__[ 'chi_'+str(i) + '_x'](state))) for i in range(1,N+1): for j in range(1,N+1): ar_step = State.update(ar_step, 'd_'+str(i) + str(j) + '_x', (1.0 - rho_dni)*bar_dni + rho_dni.math.log(State.__dict__[ 'd_'+str(i) + str(j) + '_x'](state))) if (i == j): ar_step = State.update(ar_step, 'd_'+str(i) + str(j) + '_x', 0.0) return ar_step
def next_expression(self): expr = [self.tokens.pop(0)] if expr[0] == '{': c = self.tokens.pop(0) self.tokens.insert(0, '{'+c) state['{'+c] = State.brace(int(c)) return self.next_expression() elif type(state[expr[0]]) is Operator: for _ in range(state[expr[0]].arity): expr += self.next_expression() return expr
def test2(): state = State() r1 = Robot(20, 14) r2 = Robot(20, 20) r3 = Robot(20, 0) r1.time = 14 r2.time = 8 r3.time = 8 r1.state = "on_delivery" r2.state = "on_delivery" r3.state = "on_delivery" insort(state.delivery, r1) insort(state.delivery, r2) insort(state.delivery, r3) pack1 = Pack(20, 0) pack2 = Pack(20, 10) pack3 = Pack(20, 20) state.packs.append(pack1) state.packs.append(pack2) state.packs.append(pack3) prod1 = Product(0, 0) prod2 = Product(0, 10) prod3 = Product(0, 20) state.products.append(prod1) state.products.append(prod2) state.products.append(prod3) ord1 = Order(prod1, pack1) ord2 = Order(prod1, pack2) ord3 = Order(prod1, pack3) ord4 = Order(prod2, pack1) ord5 = Order(prod2, pack2) ord6 = Order(prod2, pack3) ord7 = Order(prod3, pack1) ord8 = Order(prod3, pack2) ord9 = Order(prod3, pack3) state.orders.append(ord1) state.orders.append(ord2) state.orders.append(ord3) state.orders.append(ord4) state.orders.append(ord5) state.orders.append(ord6) state.orders.append(ord7) state.orders.append(ord8) state.orders.append(ord9) return state
def test_place_in_order(self): player_list = ["red", "white"] ex_board = f.FishBoard(4, 3) ex_board.createBoard(equal=True, randomHoles=False) ex_state = s.State(ex_board, player_list) with self.assertRaises(ValueError): ex_state.place_penguin(0, 0, "white")
def __init__(self): OnStateChangeListener.__init__(self) wx.Frame.__init__(self, None, title=u'番茄时钟 —— by xhui', size=(330,100), style=(wx.DEFAULT_FRAME_STYLE | wx.STAY_ON_TOP) & #Raise User Action ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX)) bmp = wx.BitmapFromImage(wx.ImageFromStream(R['favicon.ico'], type=wx.BITMAP_TYPE_ICO)) icon = wx.EmptyIcon() icon.CopyFromBitmap(bmp) self.SetIcon(icon) self.Bind(wx.EVT_CLOSE, self.OnClose) self.Bind(wx.EVT_ICONIZE, self.OnIconify) # timer for counting every second self.__timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.__OnTimer, self.__timer) p = wx.Panel(self) font = wx.Font(18, wx.FONTFAMILY_SWISS, wx.NORMAL, wx.NORMAL) font.SetPixelSize(wx.Size(18,32)) self.text_box = wx.StaticText(p, -1, wx.GetApp().GetTimeLeft().Format("%M:%S")) self.text_box.SetFont(font) self.text_box.SetForegroundColour(wx.ColourDatabase().Find("DIM GREY")) font.SetPixelSize(wx.Size(10,20)) self.btn_start = wx.Button(p, -1, u"开始", size=(84,32)) self.btn_start.SetFont(font) self.Bind(wx.EVT_BUTTON, self.__BtnStartDown, self.btn_start) self.btn_start.Enable(True) self.btn_stop = wx.Button(p, -1, u"结束", size=(84,32)) self.btn_stop.SetFont(font) self.Bind(wx.EVT_BUTTON, self.__BtnStopDown, self.btn_stop) self.btn_stop.Enable(False) top_sizer = wx.BoxSizer(wx.VERTICAL) child_sizer = wx.BoxSizer(wx.HORIZONTAL) sizer_style = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND|wx.ALL&~wx.BOTTOM child_sizer.Add(self.text_box, 0,sizer_style, 12) child_sizer.Add(self.btn_start, 0, sizer_style, 12) child_sizer.Add(self.btn_stop, 0,sizer_style & ~wx.LEFT, 12) top_sizer.Add(child_sizer, 0, wx.ALIGN_RIGHT) child_sizer = wx.BoxSizer(wx.HORIZONTAL) self.__counter_bar = _CounterBar(p) child_sizer.Add(self.__counter_bar, 0, sizer_style, 0) top_sizer.Add(child_sizer, 0, wx.ALIGN_LEFT|wx.TOP, 10) p.SetSizer(top_sizer) self.__state = State() self.__state.AddListener(self) self.SetActionCallBack('start', self.__OnStateStart) self.SetActionCallBack('stop', self.__OnStateStop) self.SetActionCallBack('timeup', self.__OnStateTimeUp)
def toState(self, nodes): "do a merge of all necessary states, ignoring those that are full" raise Exception("This is deprecated!") keys = set() keys2nodes = dict() for node in nodes: key = self.__node2key[node] state = self.__key2node[key] keys.add(key) if key not in keys2nodes: keys2nodes[key] = [] keys2nodes[key].append(node) stateAll = State.State([]) for key in keys: state = self.get(key) if not state.full(): stateAll = State.merge(stateAll, State.subset(state, keys2nodes[key])) return stateAll
def play(strategy, color=W, debug=False): if debug: logfile = open(options.strategy+'.txt', 'w') state = State(initial_board) move_regex = re.compile('^\! ([a-e][1-6])-([a-e][1-6])') outcome = None while outcome == None: if debug: print state if state.som == color: if game_lost(state): stdout.write('= %s wins\n' % colorrep[- state.som]) outcome = -state.som elif game_drawn(state): stdout.write('Draw\n') outcome = 0 else: move = strategy(state)[0] state.move(move) #if debug: # logfile.write( '! %s-%s\n' % (repc[FCORD(move)], repc[TCORD(move)])) # logfile.flush() stdout.write('! %s-%s\n' % (repc[FCORD(move)], repc[TCORD(move)])) stdout.flush() else: match = None while not match: line = stdin.readline() if debug: logfile.write(line) logfile.flush() match = move_regex.match(line) t, f = match.groups() tcord, fcord = rep2c[t], rep2c[f] move = new_move(tcord, fcord, state.board[fcord]) if move in gen_moves(state): state.move(move) else: stdout.write("bad move") stdout.flush()
def execute(self): s = State.get_input_stream(getattr(self, 'stream_label', None)) l = [] for e in s: l.append([e['stream_label'], e['data_format'], e['interface_id'], e['filter_address']]) r = Response.GetInputStream( return_code='0', dimino6_return_code='0', list=l) return str(r)
def init(floor, wall, render_layer): lvl, enemies = Generation.generate() for xx in range(size_x): for yy in range(size_y): f = None if lvl[(xx, yy)] == 1: f = wall(xx, yy) else: f = floor(xx, yy) actors[(xx, yy)] = None terrain[(xx, yy)] = f render_layer.add(f) for k, v in enemies.items(): enemy = v(k[0], k[1]) actors[k] = enemy render_layer.add(enemy) State.spawn(enemy)
def positive_closure(origin, tree): list_to_return = [] #must contain the new transitions(origin, subtree) that will be needed and delete the oldones aux_destination = origin.delete_transition(tree) aux_state1 = State() aux_state2 = State() origin.add_transition(Global.epsilon, aux_state1) aux_state2.add_transition(Global.epsilon, aux_state1) list_to_return.append((aux_state2, Global.epsilon)) for d in aux_destination: aux_state2.add_transition(Global.epsilon, d) aux_state1.add_transition(tree.left, aux_state2) list_to_return.append((aux_state1, tree.left)) return list_to_return
def spanAutomata(self): if self.stateSpan: self.stateSpan={} print "Iterating automata states:" currentState=State(0,self.N) nextState=State(0,self.N) for stateNumber in range(2**self.N): #print "Current state:", stateNumber currentState.setState(stateNumber) nextState=self.stepAutomata(currentState) self.stateSpan[currentState.asInt()]=nextState.asInt()
def OnInit(self): # Prevent multiple instance of the program self.name = "PomodoroTimer-%s" % wx.GetUserId() self.instance = wx.SingleInstanceChecker(self.name) if self.instance.IsAnotherRunning(): wx.MessageBox(u"已有一个程序实例在运行。", "ERROR") return False # Init State Object, State is Singleton, so call State() will get same object self.__state = State() self.__state.AddListener(self) self.SetActionCallBack('start', self.__OnStateStart) self.SetActionCallBack('stop', self.__OnStateStop) self.SetActionCallBack('timeup', self.__OnStateTimeUp) # Init main frame self.__frame = MainFrame() self.SetTopWindow(self.__frame) self.__frame.Center() self.__frame.Show() # Init taskbar icon self.__tbicon = TaskBarIcon(self.__frame) # Init timer self.__timer = wx.Timer() self.Bind(wx.EVT_TIMER, self.__OnTimer, self.__timer) # Create database self.__conn = sqlite3.connect('timer.db') c = self.__conn.cursor() c.execute('''create table if not exists timer (date text, start_time text, end_time text, status text)''') c.execute('''select count(date) from timer where date = "%s"''' % wx.DateTime.Now().FormatISODate()) count = c.fetchone()[0] self.__frame.SetCount(count) self.__conn.commit() c.close() return True
class MainFrame(wx.Frame, OnStateChangeListener): def __init__(self): OnStateChangeListener.__init__(self) wx.Frame.__init__(self, None, title=u'番茄时钟 —— by xhui', size=(330,100), style=(wx.DEFAULT_FRAME_STYLE | wx.STAY_ON_TOP) & #Raise User Action ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX)) bmp = wx.BitmapFromImage(wx.ImageFromStream(R['favicon.ico'], type=wx.BITMAP_TYPE_ICO)) icon = wx.EmptyIcon() icon.CopyFromBitmap(bmp) self.SetIcon(icon) self.Bind(wx.EVT_CLOSE, self.OnClose) self.Bind(wx.EVT_ICONIZE, self.OnIconify) # timer for counting every second self.__timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.__OnTimer, self.__timer) p = wx.Panel(self) font = wx.Font(18, wx.FONTFAMILY_SWISS, wx.NORMAL, wx.NORMAL) font.SetPixelSize(wx.Size(18,32)) self.text_box = wx.StaticText(p, -1, wx.GetApp().GetTimeLeft().Format("%M:%S")) self.text_box.SetFont(font) self.text_box.SetForegroundColour(wx.ColourDatabase().Find("DIM GREY")) font.SetPixelSize(wx.Size(10,20)) self.btn_start = wx.Button(p, -1, u"开始", size=(84,32)) self.btn_start.SetFont(font) self.Bind(wx.EVT_BUTTON, self.__BtnStartDown, self.btn_start) self.btn_start.Enable(True) self.btn_stop = wx.Button(p, -1, u"结束", size=(84,32)) self.btn_stop.SetFont(font) self.Bind(wx.EVT_BUTTON, self.__BtnStopDown, self.btn_stop) self.btn_stop.Enable(False) top_sizer = wx.BoxSizer(wx.VERTICAL) child_sizer = wx.BoxSizer(wx.HORIZONTAL) sizer_style = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND|wx.ALL&~wx.BOTTOM child_sizer.Add(self.text_box, 0,sizer_style, 12) child_sizer.Add(self.btn_start, 0, sizer_style, 12) child_sizer.Add(self.btn_stop, 0,sizer_style & ~wx.LEFT, 12) top_sizer.Add(child_sizer, 0, wx.ALIGN_RIGHT) child_sizer = wx.BoxSizer(wx.HORIZONTAL) self.__counter_bar = _CounterBar(p) child_sizer.Add(self.__counter_bar, 0, sizer_style, 0) top_sizer.Add(child_sizer, 0, wx.ALIGN_LEFT|wx.TOP, 10) p.SetSizer(top_sizer) self.__state = State() self.__state.AddListener(self) self.SetActionCallBack('start', self.__OnStateStart) self.SetActionCallBack('stop', self.__OnStateStop) self.SetActionCallBack('timeup', self.__OnStateTimeUp) def OnIconify(self, evt): self.Hide() evt.Skip() def OnClose(self, evt): self.Hide() # Prevent Exit Event evt.Veto() def __OnStateStart(self): time = wx.GetApp().GetTimeLeft() self.__timer.Start(1000) self.text_box.SetLabel(time.Format("%M:%S")) if self.__state.getState() in ('StopState','IdleState'): self.text_box.SetForegroundColour(wx.RED) self.btn_start.Enable(False) self.btn_stop.Enable(True) self.btn_stop.SetLabel(u"中断") def __OnStateStop(self): self.__timer.Stop() state_name = self.__state.getState() time = wx.GetApp().GetWorkTimeSpan() self.btn_start.SetLabel(u"开始") self.btn_start.Enable(True) self.btn_stop.SetLabel(u"结束") if state_name in ('StopState', 'IdleState'): self.text_box.SetForegroundColour(wx.ColourDatabase().Find("DIM GREY")) self.btn_stop.Enable(False) elif state_name is 'WorkState': time = wx.GetApp().GetTimeLeft() self.btn_stop.Enable(True) elif state_name is 'RestState': self.text_box.SetForegroundColour(wx.RED) time = wx.GetApp().GetWorkTimeSpan() self.btn_stop.Enable(True) self.text_box.SetLabel(time.Format("%M:%S")) def __OnStateTimeUp(self): self.__timer.Stop() state_name = self.__state.getState() self.btn_stop.SetLabel(u"结束") if state_name is 'WorkState': self.__OnWorkStateTimeUp() elif state_name is 'RestState': self.__OnRestStateTimeUp() elif state_name is 'IdleState': self.__OnIdleStateTimeUp() self.__PopUp() def __OnWorkStateTimeUp(self): time = wx.GetApp().GetRestTimeSpan() self.text_box.SetLabel(time.Format("%M:%S")) self.text_box.SetForegroundColour(wx.BLUE) self.btn_start.SetLabel(u"休息") self.btn_start.Enable(True) self.btn_stop.Enable(True) def __OnRestStateTimeUp(self): time = wx.GetApp().GetWorkTimeSpan() self.text_box.SetLabel(time.Format("%M:%S")) self.text_box.SetForegroundColour(wx.RED) self.btn_start.SetLabel(u"开始") self.btn_start.Enable(True) self.btn_stop.Enable(True) def __OnIdleStateTimeUp(self): #time = wx.GetApp().GetWorkTimeSpan() #self.text_box.SetLabel(time.Format("%M:%S")) #self.text_box.SetForegroundColour(wx.RED) #self.btn_start.SetLabel(u"开始") #self.btn_start.Enable(True) #self.btn_stop.Enable(True) pass def SetCount(self, count): self.__counter_bar.SetCount(count) # Popup main frame def __PopUp(self): if self.IsIconized(): self.Iconize(False) if not self.IsShown(): self.Show() self.Raise() # Timer tick def __OnTimer(self, evt): time = wx.GetApp().GetTimeLeft() self.text_box.SetLabel(time.Format("%M:%S")) def __BtnStartDown(self, evt): self.__state.Start() def __BtnStopDown(self, evt): self.__state.Stop()
def rollbackTo(self, stateNum): s = State() s.patch(self.patchedStateSequence[stateNum]) self.initState = s self.patchSequence.append("Rollback-"+repr(stateNum)) self.patchedStateSequence.append(s)
"""This is an example of using a PDA to parse strings with well-formed parentheses.""" from PDA import * from State import * accept5 = State(state_type="Accept") pop4 = State(state_type="Pop") pop3 = State(state_type="Pop") push2 = State(state_type="Push") read1 = State(state_type="Read") # add transitions for 'a', 'b', and the 'end' of the tape. read1.add_transition(push2, character="(") read1.add_transition(pop3, character=")") read1.add_transition(pop4, character="!") push2.add_transition(read1, character="X") pop3.add_transition(read1, character="X") pop4.add_transition(accept5, character="!") start_state = State(state_type="Start", next_state=read1) my_pda = PDA(start_state) tape_word = "(((((((()))(((())))()()((())))))))!" my_pda.start(tape=tape_word, stack=['!'], verbose=False)
def think(self, who): if self.can_see(who, State.get_player()): self.move_towards(who, State.get_player())
def __init__(self,string): s = State() e = State(True) s.addLink(e,string) self.start = s self.end = e
def update(self, newState): for state in self.__states: newSt = State.subset(newState, state.nodes()) for st in newSt.states: state.addState(st)
#fonts pygame.font.init() font = pygame.font.SysFont("monospace", 15) #logic elements obstacles = [] c_obstacles = [] robot = None minus_robot = None target = None path = [] pathEdges = [] #define global state of application states = State() (V, E) = (None, None) while running: #Read and process user input for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.MOUSEBUTTONDOWN: (mousex, mousey) = pygame.mouse.get_pos() if states.getActualState() == "DRAWING_OBSTACLE": obstacles[len(obstacles) - 1].addVertex((mousex, mousey)) if states.getActualState() == "DRAWING_ROBOT": robot.addVertex((mousex, mousey)) if states.getActualState() == "SELECT_TARGET": print "Target selected" target.setVertex((mousex, mousey))
def Build_HMM(file,profileDim,gmm_param_dir): ''' This function build an hmm starting from a file. It discriminates between a discrete symbol version and a GMM version using different node_em class objects. Also searches for MIXTURES = Yes/No indicator from the input file. The profileDim parameter is the dimension of the input encoding used. ''' import string import State import HMM try: lines = open(file).readlines() except: print "Can't open build_hmm file, ",file info=parse_text(lines,profileDim,gmm_param_dir) tr_al=info['TRANSITION_ALPHABET'] if(info['EMISSION_ALPHABET'][0] == 'range'): # used for integer emission symbols such as dice throws em_al=[] for i in range(string.atoi(info['EMISSION_ALPHABET'][1])): em_al.append(str(i)) else: em_al=info['EMISSION_ALPHABET'] tied_t={} # tied transitions None if not tied tied_e={} # tied emissions None if not tied (this is at the state level) tied_e_mix = {} # tied emission mixture densities, None if not tied (this is at the sub-state mixture-tying level) links={} # temporary list for each state states=[] label={} endstate={} in_links={} fix_tr={} fix_em={} fix_em_mix = {} empty_tr=State.node_tr("_EMPTY_TR_",[]) #empty transition and emissions if info["MIXTURES"][0] == "Yes": # check if node_em is for discrete symbols or vector profile GMMs empty_em = State.node_em_gmm("_EMPTY_EM_",[],[]) # mix_weights = [], mix_densities = [] else: empty_em = State.node_em("_EMPTY_EM_",[]) for name in tr_al: # initialize dictionaries in_links[name]=[] links[name]=[None,None] for name in tr_al: # create in_link information for in_name in info[name]['LINK']: if(name not in in_links[in_name]): in_links[in_name].append(name) serial=0 # used as incremental internal number for transitions and emissions. It will be used toi set node_tr node_em for name in tr_al: # set node_tr if(info[name]['TRANS']!=[] and info[name]['TRANS'][0] != 'tied'): if(info[name]['TRANS'][0] == 'uniform'): # set uniform d=1.0/len(info[name]['LINK']) info[name]['TRANS']=[d]*len(info[name]['LINK']) obj=State.node_tr("_TR_"+str(serial),info[name]['TRANS']) serial=serial + 1 links[name][0]=obj tied_t[name]=None elif(info[name]['TRANS']!=[] and info[name]['TRANS'][0] == 'tied'): tmpname=info[name]['TRANS'][1] links[name][0]=links[tmpname][0] # links[name][0] is for transitions tied_t[name]=tmpname elif(info[name]['TRANS']==[]): links[name][0]=empty_tr tied_t[name]=None # This section implements the tying of emission density functions (either discrete/continuous at the state level or for GMM at the sub-state mixture level) # For mixture-tying, the implementation is such that a collection of states will share one codebook of mixture densities while still having individual state # mixture weights serial=0 for name in tr_al: # set node_em if (info["MIXTURES"][0] != "Yes"): if(info[name]['EMISSION']!=[] and info[name]['EM_LIST'][0] == 'all'): info[name]['EM_LIST']=em_al elif(info[name]['EMISSION']!=[] and info[name]['EMISSION'][0] != 'tied'): if(info[name]['EMISSION'][0] == 'uniform'): # set uniform d=1.0/len(info[name]['EM_LIST']) info[name]['EMISSION']=[d]*len(info[name]['EM_LIST']) obj=State.node_em("_EM_"+str(serial),info[name]['EMISSION']) serial=serial + 1 links[name][1]=obj tied_e[name]=None tied_e_mix[name] = None elif(info[name]['EMISSION']==[]): links[name][1]=empty_em tied_e[name]=None tied_e_mix[name] = None elif(info[name]['EMISSION']!=[] and info[name]['EMISSION'][0] == 'tied'): # check for states with tied emissions discrete and GMM at the state level tmpname=info[name]['EMISSION'][1] links[name][1]=links[tmpname][1] tied_e[name]=tmpname tied_e_mix[name] = tmpname elif(info["MIXTURES"][0] == "Yes"): if(info[name]['EMISSION']!=[] and info[name]['EMISSION'][0] == 'tied'): # check for states with tied emissions discrete and GMM at the state level tmpname=info[name]['EMISSION'][1] links[name][1]=links[tmpname][1] tied_e[name]=tmpname tied_e_mix[name] = tmpname elif (info[name]['MIXTURE_NUM'] != []) and (info[name]['MIXTURE_NUM'][0] != 'tied'): #normalise mixture weights to sum to one weight_sum = float(sum(info[name]["MIXTURE_WEIGHTS"])) info[name]["MIXTURE_WEIGHTS"] = [w/weight_sum for w in info[name]["MIXTURE_WEIGHTS"]] mix_densities = [] for k in range(int(info[name]["MIXTURE_NUM"][0])): #tmp_mix_density = State.mixture_density("_EM_GMM_"+str(serial)+"_MIX_"+str(k),info[name]["MIXTURE_MEANS"][k],info[name]["MIXTURE_COVARS"][k]) #all mixture densities in a state share the same name, this is because tying of mixture densities works by tying all mixtures in a state to another state. tmp_mix_density = State.mixture_density("_EM_GMM_"+str(serial)+"_MIX",info[name]["MIXTURE_MEANS"][k],info[name]["MIXTURE_COVARS"][k]) mix_densities.append(tmp_mix_density) obj = State.node_em_gmm("_EM_GMM_"+str(serial),info[name]["MIXTURE_WEIGHTS"],mix_densities) serial=serial+1 links[name][1]=obj tied_e[name]=None tied_e_mix[name] = None elif (info[name]['MIXTURE_NUM'] == []): links[name][1] = empty_em tied_e[name] = None tied_e_mix[name] = None elif (info[name]['MIXTURE_NUM'][0] == 'tied'): # check for states with tied emissions GMM at the sub-state mixture level #normalise mixture weights to sum to one weight_sum = float(sum(info[name]["MIXTURE_WEIGHTS"])) info[name]["MIXTURE_WEIGHTS"] = [w/weight_sum for w in info[name]["MIXTURE_WEIGHTS"]] tmpname = info[name]["MIXTURE_NUM"][1] #this is used to obtain the reference pointer to the tied to state's mixture densities tmp_node_em_gmm = links[tmpname][1] tied_mixture_densities = tmp_node_em_gmm.get_mixtures() obj = State.node_em_gmm("_EM_GMM_"+str(serial),info[name]["MIXTURE_WEIGHTS"],tied_mixture_densities) serial=serial+1 links[name][1] = obj tied_e[name]= None tied_e_mix[name]=tmpname for name in tr_al: # set labels if(info[name]['FIX_TR']): # fixed transitions fix_tr[name]='YES' else: fix_tr[name]=None if(info[name]['FIX_EM']): # fixed emissions fix_em[name]='YES' else: fix_em[name]=None if(info[name]['FIX_EM_MIX']): # fixed emission mixture densities fix_em_mix[name]='YES' else: fix_em_mix[name]=None if(info[name]['LABEL'] == ['None']): # LABELS label[name]=None else: label[name]=info[name]['LABEL'] endstate[name]=info[name]['ENDSTATE'] # set endstates states.append(State.State(name,links[name][0],links[name][1],info[name]['LINK'],in_links[name],info[name]['EM_LIST'],tied_t[name],tied_e[name],tied_e_mix[name],endstate[name],label[name])) # set State[i] and appnd it to the state list hmm = HMM.HMM(states,em_al,fix_tr,fix_em,fix_em_mix,info["MIXTURES"][0],profileDim) #int(info["MIXTURES"][1])) # set self.hmm => the HMM return(hmm)
class InitFileMgr: def __init__(self, fname): self.pddlFName = fname self.initState = self.getInitStateFromString() # the state to be maintained self.patchSequence = [] # history of applied patches self.patchedStateSequence = [] # history of init states def getPDDLStr(self): pddlStr = tryIO(self.pddlFName, "read") return pddlStr def writeFile(self, ofname, txt): tryIO(ofname, "write", txt) def pushCurrentInitToHistory(self): s=State() s.patch(self.initState) self.patchedStateSequence.append(s) def replaceInitState(self, newState): self.pushCurrentInitToHistory() self.patchSequence.append('replaced state') self.initState = State() self.initState.patch(newState) def getCurrentState(self): return self.initState def extractInitSection(self): pddlStr = self.getPDDLStr() initSection = "" for section in pddlStr.split("(:"): if section.strip().find("init") == 0: initSection = section.replace("init", "") break return initSection def getInitStateFromString(self): op = OutputParser("") return op.getStateFromStr(self.extractInitSection()) def patchInitState(self, newState): s = State() s.patch(self.initState) self.patchedStateSequence.append(s) self.initState.patch(newState) self.patchSequence.append(newState) def printInitState(self): print "Patch generation " + repr(len(self.patchSequence)) self.initState.printState() def writeCurrentPDDL(self, ofname): print "Writing PDDL file " + ofname pddlStr = self.getPDDLStr() pddlOutStr = "" propList = list(self.initState.getTrueProps()) propList.sort() pddlPart1 = pddlStr.split("(:init")[0] pddlPart2 = pddlStr.split("(:init")[1].strip().split("(:goal")[1] pddlOutStr = pddlPart1 + "\n\n(:init \n" + "\n".join(propList) + ")" +\ "\n\n(:goal" + pddlPart2 # for section in pddlStr.split("(:"): # if section.strip().find("init") != 0: # pddlOutStr += "(:" + section + "\n\n" # else: # pddlOutStr += "(:init \n" + \ # "\n".join(propList) # pddlOutStr += "\n" self.writeFile(ofname, pddlOutStr) def rollbackTo(self, stateNum): s = State() s.patch(self.patchedStateSequence[stateNum]) self.initState = s self.patchSequence.append("Rollback-"+repr(stateNum)) self.patchedStateSequence.append(s) def purgeFactsWithSymbol(self, symbol): #In order to log the change, create a state # with facts that match symbol # remove from both true set and false set s = State() s.patch(self.initState) self.patchSequence.append("Purge symbol: "+symbol) self.patchedStateSequence.append(s) for prop in s.getTrueProps(): if symbol in prop: self.initState.removeTrueProp(prop) for prop in s.getFalseProps(): if symbol in prop: self.initState.removeFalseProp()
def annotation(self, num): merge = State.State([]) for state in self.__states: if not state.full(): merge = State.merge(merge, state) return merge.annotation(num)
from flask import Flask from flask import render_template import Panel import State from pygooglechart import Chart from pygooglechart import SimpleLineChart from pygooglechart import Axis import os app = Flask(__name__) panel1 = Panel.panel_production('Jim', 2, 2, 4, 1) panel2 = Panel.panel_production('Jim2', 2, 2, 4, 2) panels = [panel1, panel2] myPanel = "jim" CA = State.stateReg('California',15,5) #initialize sample vars panel1.setOCV(1) panel1.setSCI(1) def makeChart(): # Set the vertical range from 0 to 100 max_y = 100 # Chart size of 200x125 pixels and specifying the range for the Y axis chart = SimpleLineChart(400, 250, y_range=[0, max_y]) # Add the chart data # Aggregate data into array before adding to chart data = [ 32, 34, 34, 32, 34, 34, 32, 32, 32, 34, 34, 32, 29, 29, 34, 34, 34, 37,