def handle_event(self, event): self.key_pressed = False if event.type == QUIT: util.switch(util.Displays.MENU) if event.type == pygame.KEYDOWN: previous_sequence = self.current_sequence if event.key == pygame.K_ESCAPE: util.switch(util.Displays.MENU) if event.key in (pygame.K_LEFT, pygame.K_UP, pygame.K_RIGHT, pygame.K_DOWN): self.key_pressed = True self.elapsed_since_change = 0 self.current_sequence = self._map_to_sequence(event) if previous_sequence != self.current_sequence: self.current_sequence.reset() if event.type == pygame.KEYUP: if event.key in (pygame.K_LEFT, pygame.K_UP, pygame.K_RIGHT, pygame.K_DOWN): self.current_sequence = self.sequences[Movement.IDLE] self.current_sequence.reset()
def handle_event(self, event): if event.type == QUIT: pygame.mixer.music.stop() util.switch(util.Displays.MENU) if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.mixer.music.stop() util.switch(util.Displays.MENU)
def handle_event(self, event): if event.type == QUIT: util.switch(util.Displays.MENU) if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: util.switch(util.Displays.MENU) if event.type == pygame.MOUSEBUTTONUP: loc = pygame.mouse.get_pos() for smiley in self.smileys: smiley.selected = smiley.within_bounds(loc)
def handle_event(self, event): self.key_pressed = False if event.type == QUIT: util.switch(util.Displays.MENU) if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: util.switch(util.Displays.MENU) if event.type == pygame.MOUSEBUTTONUP: pos = pygame.mouse.get_pos() self.image_loc = pos self.image_color = self.background_depth.get_at(pos)
def handle_event(self, event): if event.type == QUIT: end() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: end() if event.type == pygame.KEYDOWN: if event.key == pygame.K_DOWN: self.next() elif event.key == pygame.K_UP: self.previous() elif event.key == pygame.K_RETURN: if self.selected_index == len(self.choices) - 1: pygame.quit() sys.exit() else: util.switch(self.choices[self.selected_index].id)
def __readConfig(self): """ Description. """ with open(self.Config_file) as configfile: while 1: line = configfile.readline() if not line: break # remove line returns line = line.strip('\r\n') # make sure it has useful data if (not "=" in line) or (line[0] == '%'): continue # split across equal sign line = line.split("=",1) this_param = line[0].strip() this_value = line[1].strip() for case in switch(this_param): #integer values #if case("NB_FSI_ITER") : #self.Config[this_param] = int(this_value) #break #float values if case("DELTA_T") : pass if case("START_TIME") : pass if case("STOP_TIME") : pass if case("SPRING_MASS") : pass if case("INERTIA_FLEXURAL") : pass if case("SPRING_STIFFNESS") : pass if case("SPRING_DAMPING") : pass if case("TORSIONAL_STIFFNESS") : pass if case("TORSIONAL_DAMPING") : pass if case("CORD") : pass if case("FLEXURAL_AXIS") : pass if case("GRAVITY_CENTER") : pass if case("INITIAL_DISP") : pass if case("INITIAL_ANGLE") : pass if case("RHO") : self.Config[this_param] = float(this_value) break #string values if case("UNSTEADY_SIMULATION") : pass if case("MESH_FILE") : pass if case("CSD_SOLVER") : pass if case("MOVING_MARKER") : pass if case("STRUCT_TYPE") : self.Config[this_param] = this_value break if case(): print(this_param + " is an invalid option !") break
def reset(s, state, backslashed=False): s.parserState = state s.backslashed = backslashed s.identifier = None s.currentIndent = u'' for case in switch(state): if case(ReaderState.Number): s.appendExp(NumberExp(s.loc())) elif case(ReaderState.Symbol): s.appendExp(SymbolExp(s.loc())) elif case(ReaderState.Quote): s.appendExp(QuoteExp(s.loc()))
def modify_moral_graph(self, modification): L = [] for case in switch(modification.type): if case(Modification.ADD_NODE): self._graph_m.add_node(modification.data) break if case(Modification.REMOVE_NODE): self._graph_m.remove_node(modification.data) break if case(Modification.ADD_LINK): pair = set(modification.data) parents = set(self._old_network.predecessors(modification.data[1])) nodes = pair.union(parents) subgraph = self._graph_m.subgraph(nodes) complement = nx.complement(subgraph) for edge in complement.edges_iter(): L.append(edge) break if case(Modification.REMOVE_LINK): head = modification.data[1] tail = modification.data[0] children_head = set(self._old_network.successors(head)) children_tail = set(self._old_network.successors(tail)) if len(children_tail.intersection(children_head)) <= 0: self._graph_m.remove_edge(modification.data) L.append(modification.data) for parent in self._old_network.predecessors_iter(head): if parent == tail: continue children_z_i = set(self._old_network.successors(parent)).intersection(children_tail) if not len(children_z_i) == 1: continue if head not in children_z_i: continue if not self._old_network.has_edge(parent, tail): continue if self._old_network.has_edge(tail, parent): continue self._graph_m.remove_edge(tail, parent) L.append((tail, parent)) break if case(): raise Exception("Not a defined modification") return L
def modify_moral_graph(self, modification): L = [] for case in switch(modification.type): if case(Modification.ADD_NODE): self._graph_m.add_node(modification.data) break if case(Modification.REMOVE_NODE): self._graph_m.remove_node(modification.data) break if case(Modification.ADD_LINK): pair = set(modification.data) parents = set( self._old_network.predecessors(modification.data[1])) nodes = pair.union(parents) subgraph = self._graph_m.subgraph(nodes) complement = nx.complement(subgraph) for edge in complement.edges_iter(): L.append(edge) break if case(Modification.REMOVE_LINK): head = modification.data[1] tail = modification.data[0] children_head = set(self._old_network.successors(head)) children_tail = set(self._old_network.successors(tail)) if len(children_tail.intersection(children_head)) <= 0: self._graph_m.remove_edge(modification.data) L.append(modification.data) for parent in self._old_network.predecessors_iter(head): if parent == tail: continue children_z_i = set(self._old_network.successors( parent)).intersection(children_tail) if not len(children_z_i) == 1: continue if head not in children_z_i: continue if not self._old_network.has_edge(parent, tail): continue if self._old_network.has_edge(tail, parent): continue self._graph_m.remove_edge(tail, parent) L.append((tail, parent)) break if case(): raise Exception('Not a defined modification') return L
def crawler_news(website): try: return_msg = {} return_msg["result"] = "fail" #check if table 'news_QR_code' exists check_table(news=True) with DataTypeDao() as dataTypeDao: existed = dataTypeDao.checkTypeExisted(website) if not existed: create_data_type(website) for case in switch(website): if case('inside'): #start grab INSIDE info try: grab_inside_articles() except: return_msg["error"] = "ERROR occurs in INSIDE crawler. Please check the correction of news_crawler" return return_msg break if case('techOrange'): #start grab TECHORANGE info try: grab_techorange_articles() except: return_msg["error"] = "ERROR occurs in TECHORANGE crawler. Please check the correction of news_crawler" return return_msg break if case('medium'): #start grab MEDIUM info try: grab_medium_articles() except: return_msg["error"] = "ERROR occurs in MEDIUM crawler. Please check the correction of news_crawler" return return_msg break return_msg["result"] = "success" return return_msg except DB_Exception as e: return_msg["error"] = gen_error_msg(e.args[1]) return return_msg
def incremental_compilation(self, modificationList): for modification in modificationList: L = self.modify_moral_graph(modification) for case in switch(modification.type): if case(Modification.ADD_NODE): self.add_node(modification.data) break if case(Modification.REMOVE_NODE): self.remove_node(modification.data) break if case(Modification.ADD_LINK): self.mark_affected_mps_by_add_link(L) break if case(Modification.REMOVE_LINK): self.mark_affected_mps_by_remove_link(None, None, L) break if case(): pass raise Exception("not implemented")
def apply(s, m, left, node, right, _): for case in switch(type(node)): if case(reader.QuoteExp): node = execution.StringLiteralExec(node.loc, node.content) elif case(reader.NumberExp): value = node.integer if node.dot: value += "." if node.decimal is not None: value += node.decimal node = execution.NumberLiteralExec(node.loc, float(value)) elif case(reader.SymbolExp): if node.isAtom: node = execution.AtomLiteralExec(node.loc, node.content) else: node = execution.VarExec(node.loc, node.content) else: return Error( node.loc, "Internal error: AST node of indecipherable type %s found in a place that shouldn't be possible" % (type(node).__name__)) return (left, node, right)
def ast(s, iter): s.reset(ReaderState.Indent) for ch in iter: for case in dynamicSwitch(s, 'parserState'): s.char += 1 if case(ReaderState.Cr): s.newline() s.newexp() s.reset(ReaderState.Indent) if i == u'\n': break # If complete CRLF, DONE if case(ReaderState.Indent) and not isCloseParen(ch): if isNonLineSpace(ch): s.currentIndent += ch break # If indent continued, DONE if isLineSpace(ch): s.handleLineSpace(ch) break # If indent ended line (with newline), DONE if ch == u'#': s.reset(ReaderState.Comment) break # If indent ended line (with comment), DONE if ch == u',': s.error("Comma at start of line not understood" ) # FIXME: This should clear entire line break # If line starts with comment (illegal), DONE # Line has begun! Adjust group and move into scanning state: finalGroup = s.finalGroup() # If group already contains lines if finalGroup.indent == s.currentIndent: if finalGroup.finalStatement().nodes: finalGroup.appendStatement() # First line of group if finalGroup.indent is None: finalGroup.indent = s.currentIndent if finalGroup.finalStatement().nodes: finalGroup.appendStatement() # FIXME: Is this really the right thing to do? s.error( "Indentation after ( is ambiguous; please add a , at the end of the previous line." ) # Indent or dedent event elif finalGroup.indent != s.currentIndent: # Indent event if s.currentIndent.startswith(finalGroup.indent): s.appendGroup(True) s.finalGroup().indent = s.currentIndent # Dedent event (or error) else: unrollIdx = len(s.groupStack) - 1 parenthesisIssue = s.finalGroup( ).openedWithParenthesis if not parenthesisIssue: while True: unrollIdx -= 1 if unrollIdx < 0: break group = s.groupStack[unrollIdx] if group.indent == s.currentIndent: break if group.openedWithParenthesis: parenthesisIssue = True break # Error if parenthesisIssue: group = s.groupStack[ unrollIdx] # Redundant but ehhh s.error( "Indentation on this line doesn't match any since parenthesis on line %d char %d" % (group.loc.line, group.loc.char)) elif unrollIdx < 0: s.error( "Indentation on this line doesn't match any previous one" ) # Dedent else: s.unrollTo(unrollIdx + 1) s.finalGroup().appendStatement() # If we didn't break above, we're done with the indent. s.reset(ReaderState.Scanning) if case(ReaderState.Dot): if isNonLineSpace(ch): break # Whitespace after dot is not interesting. DONE elif isDigit(ch): s.reset(ReaderState.Number) s.finalExp().appendDot() elif ch == u'.' or ch == u'(' or ch == u')' or ch == u'"' or ch == '\\': s.error("'.' was followed by special character '%s'" % ch) elif ch == u'#' or isLineSpace(ch): s.error("Line ended with a '.'") else: s.reset(ReaderState.Symbol) s.finalExp().isAtom = True if case(ReaderState.Quote): trueCh = ch if s.backslashed: for chCase in switch(ch): if chCase(u'\\'): trueCh = u'\\' elif chCase('n'): trueCh = u'\n' elif chCase('r'): trueCh = u'\r' elif chCase('t'): trueCh = u'\t' elif isQuote(ch): pass # trueCh is already ch else: trueCh = None s.backslashed = False if trueCh is None: s.error( "Unrecognized backslash sequence '\%s'" % (ch), True) break # Don't know what to do with this backslash, so just eat it. DONE elif ch == u'\\': s.backslashed = True break # Consumed backslash inside string. DONE elif isQuote(ch): s.reset(ReaderState.Scanning) break # Consumed quote at end of string. DONE. s.finalExp().append(trueCh) break # These checks are shared by: Scanning Symbol Number Comment if isLineSpace(ch): s.handleLineSpace(ch) break # Consumed newline. DONE if case(ReaderState.Comment ): # FIXME: This + linespace could go earlier? break # Inside comment, don't care. DONE # These checks are shared by: Scanning Symbol Number (and Indent for right parens) if isNonLineSpace(ch): s.reset(ReaderState.Scanning) break if isOpenParen(ch): s.appendGroup(True, True) s.reset(ReaderState.Scanning) break # Have consumed (. DONE if isCloseParen(ch): # Unroll stack looking for last parenthesis-based group unrollIdx = len(s.groupStack) while True: unrollIdx -= 1 if unrollIdx < 0: break group = s.groupStack[unrollIdx] if group.openedWithParenthesis: break # None found if unrollIdx < 0: s.error("Stray right parenthesis matches nothing", True) else: s.unrollTo(unrollIdx) s.reset(ReaderState.Scanning) break # Have consumed (. DONE if isQuote(ch): s.reset(ReaderState.Quote) break # Have consumed ". DONE if ch == u',': s.finalGroup().appendStatement() s.reset(ReaderState.Scanning) break # Have consumed ,. DONE if ch == u'#': s.reset(ReaderState.Comment) break # Have consumed #. DONE if ch == u'\\': # Shared by: Scanning Symbol Number s.reset(ReaderState.Backslash) elif ch == u'.': # Shared by: Scanning Symbol Number if case(ReaderState.Number): if s.finalExp().dot: s.reset(ReaderState.Dot ) # We're starting an atom or something else: # FIXME: This will ridiculously require 3..function to call a function on number s.finalExp( ).dot = True # This is a decimal in a number elif case(ReaderState.Backslash): s.reset(ReaderState.Symbol) s.finalExp().isAtom = True s.finalExp().isEscaped = True else: s.reset(ReaderState.Dot) break # Have consumed .. DONE elif isDigit(ch): if case(ReaderState.Backslash): s.error(u"Backslash cannot be followed by a number") elif case(ReaderState.Scanning) or (case( ReaderState.Symbol) and s.identifier is False): s.reset(ReaderState.Number) else: # Symbol character if case(ReaderState.Scanning) or case(ReaderState.Number): s.reset(ReaderState.Symbol) elif case(ReaderState.Backslash): s.reset(ReaderState.Symbol) s.finalExp().isEscaped = True if case(ReaderState.Number): s.finalExp().append(ch) break # Added to number. DONE if case(ReaderState.Symbol): if s.identifier is None: s.identifier = isIdStart(ch) else: if (s.identifier and not isIdContinue(ch)) or ( not s.identifier and isIdStart(ch)): s.reset(ReaderState.Symbol) s.identifier = isIdStart(ch) s.finalExp().append(ch) break # Added to symbol. DONE # Done; unroll all groups while len(s.groupStack) > 1: group = s.finalGroup() if group.openedWithParenthesis: s.error("Parenthesis on line %d char %d never closed" % (group.loc.line, group.loc.char)) s.groupStack.pop()
def _forward_alg(self, feats, target, mask): seq_length = feats.size(0) batch_size = feats.size(1) # return 0.001*torch.mm(self.transitions, Variable(torch.randn(self.tagset_size, self.tagset_size)).cuda(0)).sum() # scores: (seq_len, batch, to_tagsize, from_tagsize) 下一个step加上的score scores = self.compute_scores(feats) start_tag = Variable( torch.LongTensor(1, batch_size).fill_(self.tag_to_ix[START_TAG])) end_tag = Variable( torch.LongTensor(1, batch_size).fill_(self.tag_to_ix[STOP_TAG])) if self.config['USE_CUDA']: start_tag = start_tag.cuda(feats.get_device()) end_tag = end_tag.cuda(feats.get_device()) from_tag = torch.cat([start_tag, target], 0) # to_tag: (seq_len+1, batch) to_tag = torch.cat([target, end_tag], 0) # scores_add_an_end: (seq_len+1, batch, to_tagsize, from_tagsize) scores_add_an_end = torch.cat([ scores, self.transitions.view( 1, 1, self.tagset_size, self.tagset_size).expand( 1, batch_size, self.tagset_size, self.tagset_size) ], 0) # from_tag: (seq_len+1, batch, to_tagsize, 1) from_tag = from_tag.view(seq_length+1, batch_size, 1, 1)\ .expand(seq_length+1, batch_size, self.tagset_size, 1) # from_score: (seq_len+1, batch, to_tagsize) from_score = torch.gather(scores_add_an_end, -1, from_tag).squeeze(-1) # to_tag: (seq_len+1, batch, 1) to_tag = to_tag.unsqueeze(-1) # sen_scores: (seq_len+1, batch) sen_scores = torch.gather(from_score, -1, to_tag).squeeze(-1) # mask_add_an_end: (seq_len+1, bat_size) one_mask = Variable(torch.ByteTensor(1, batch_size).fill_(1)) if self.config['USE_CUDA']: one_mask = one_mask.cuda(feats.get_device()) mask_add_an_end = torch.cat([one_mask, mask], 0) masked_sen_scores = sen_scores.masked_select(mask_add_an_end).sum() # Do the forward algorithm to compute the partition function init_alphas = torch.Tensor(1, self.tagset_size).fill_(-10000) # START_TAG has all of the score. init_alphas[0][self.tag_to_ix[START_TAG]] = 0. # Wrap in a variable so that we will get automatic backprop forward_var = Variable(init_alphas) if self.config['USE_CUDA']: forward_var = forward_var.cuda(feats.get_device()) forward_var = forward_var.expand( batch_size, self.tagset_size) # (batch, from_target) for idx in range(scores.size(0)): cur_values = scores[idx] # brod_forward_var: (batch, to_target, from_target) brod_forward_var = forward_var.unsqueeze(1).expand( batch_size, self.tagset_size, self.tagset_size) next_step_var = brod_forward_var + cur_values # (batch_size, to_target, from_target) next_step_var = log_sum_exp(next_step_var) # (batch, to_target) # (batch, to_target) 下一个循环变成from_target forward_var = util.switch( forward_var.contiguous(), next_step_var.contiguous(), mask[idx].view(batch_size, 1).expand(batch_size, self.tagset_size)).view( batch_size, -1) # (B, from_target) terminal_var = forward_var + self.transitions[ self.tag_to_ix[STOP_TAG]].unsqueeze(0).expand_as(forward_var) # terminal_var = util.switch(forward_var.contiguous(), terminal_var.contiguous(), # mask[idx].view(batch_size, 1).expand(batch_size, self.tagset_size)).view(batch_size, # -1) alpha = log_sum_exp(terminal_var) # (B, ) all = alpha.sum() loss = (all - masked_sen_scores) / batch_size return loss