def process(self): self.matchedAddresses = Match.matchWithCriterias({ "toLookIn": self.matchedAddresses, "completionState": self.completionState, "toMatch": self.concatInput }) if len(self.matchedAddresses) == 1: utils.printFinalCompletionAndQuit(self.matchedAddresses[0].value) tmp = Match.getTabOfDiffEltsOfAddrFrom(self.matchedAddresses, {"completionState": self.completionState}) if len(tmp) == 0: utils.quitWithError("Unknown address") elif len(tmp) == 1: if self.completionState == CompletionState.CITY: self.completedByEngine = tmp[0].upper() + ", " self.completionState = CompletionState.STREETNAME self.concatInput = "" self.displayMostProbablesLetters({"noInput": True}) elif self.completionState == CompletionState.STREETNAME: utils.printFinalCompletionAndQuit(tmp[0].value) else: self.matchedAddresses = Match.matchWithCriterias({ "toLookIn": self.matchedAddresses, "completionState": self.completionState, "toMatch": self.concatInput }) self.displayMostProbablesLetters({"noInput": False})
def get_true_true(result, index, param, mass): TT = [] for i in range(len(result)): scan = result[i][0] spectrum = index.spectraDict[scan] charge = spectrum.ch cand = [] sumint = [] for j in range(len(result[i][1])): pepObj1 = index.uniquePepObjs[0][result[i][1][j][0][0]] pepObj2 = index.uniquePepObjs[0][result[i][1][j][0][1]] SL = [set(), set()] positions = result[i][1][j][1] for pro in pepObj1.proteinID: cols = pro.split('|R') SL[0].add(cols[1][0]) for pro in pepObj2.proteinID: cols = pro.split('|R') SL[1].add(cols[1][0]) feature = list(result[i][1][j][2][0]) feature.extend(result[i][1][j][2][1]) if feature[0] / float(feature[7]) >= 0.20 and feature[1] / float(feature[7]) >= 0.20 and feature[8] / float(feature[15]) >= 0.20 and feature[9] / float(feature[15]) >= 0.20 and feature[2] >= 0.1 and feature[10] >= 0.1 and len(SL[0].intersection(SL[1])) > 0: xl = XLink(pepObj1, pepObj2, positions, charge, mass, param) match = Match(spectrum, xl, mass, param) match.match(mass) cand.append(match) sumint.append(feature[2] + feature[10]) if len(cand) == 0: continue comb = zip(cand, sumint) cand = list(zip(*sorted(comb, key = lambda x : x[1], reverse = True))[0]) sumint = list(zip(*sorted(comb, key = lambda x : x[1], reverse = True))[1]) TT.append(cand[0]) for i in range(len(TT)): pepObj1 = TT[i].xlink.pepObjs[0] pepObj2 = TT[i].xlink.pepObjs[1] s = pepObj1.sequence + '\t' + pepObj2.sequence + '\t' + ','.join(pepObj1.proteinID) + '\t' + ','.join(pepObj2.proteinID) print s return TT
def id_perm_changes(s, handle, fd, permdata, set): removelist = [] changelist = [] addlist = [] if not check_fd_sel(fd, set) or not check_perm_sel(permdata, set): return([removelist,changelist,addlist]) for perm_act in set['PermAct']: # pass if no action is defined if not perm_act['Action']: pass elif perm_act['Action']['Action'] == 'Remove': for perm in permdata['perms']: if Match.parse(perm_act['Criteria'], perm): removelist.append(perm) elif perm_act['Action']['Action'] == 'Change': for perm in permdata['perms']: if Match.parse(perm_act['Criteria'], perm): # delete the old permission newperm = perm.copy() if 'Read' in perm: del(newperm['Read']) if 'Write'in perm: del(newperm['Write']) if 'Manage' in perm: del(newperm['Manage']) for key,val in perm_act['Action']['Perms'].items(): newperm[key] = val changelist.append(newperm) elif perm_act['Action']['Action'] == 'Add': addFlag = True for perm in permdata['perms']: if not Match.parse(perm_act['Criteria'], perm): addFlag = False if addFlag: pEntry = {} pEntry['handle'] = perm_act['Action']['Handle'] grpdata = DCC.prop_get(s, pEntry['handle'], InfoSet = 'Title') pEntry['name'] = grpdata['title'] if 'Read' in perm_act['Action']['Perms']: pEntry['Read'] = perm_act['Action']['Perms']['Read'] if 'Write' in perm_act['Action']['Perms']: pEntry['Write'] = perm_act['Action']['Perms']['Write'] if 'Manage' in perm_act['Action']['Perms']: pEntry['Manage'] = perm_act['Action']['Perms']['Manage'] addlist.append(pEntry) elif perm_act['Action']['Action'] == 'Message': for perm in permdata['perms']: if Match.parse(perm_act['Criteria'], perm): print(perm_act['Action']['Message']) DCC.print_perm(perm, LF = True) return([removelist, changelist, addlist])
def setStatus(self): template = GC.status_buy_icon if Match.this(self.global_rs_image, template): return "buy" template = GC.status_sell_icon if Match.this(self.global_rs_image, template): return "sell" template = GC.status_empty_icon if Match.this(self.global_rs_image, template): return "empty"
def getMatchesPerSpectrum(mass, param, index, title): spectraDict = index.spectraDict uniquePepObjs = index.uniquePepObjs[0] precMassPepIndexTuple = index.precMassPepIndexTuple searchIndex = index.searchIndex xresidue = param['xresidue'] indexList = searchIndex[title] spectrum = spectraDict[title] matches = [] XL = [] for i in indexList: index1 = precMassPepIndexTuple[1][i] index2 = precMassPepIndexTuple[2][i] pepObj1 = uniquePepObjs[index1] pepObj2 = uniquePepObjs[index2] pepSorted = sorted([pepObj1, pepObj2], key = lambda x : x.sequence) pepObj1 = pepSorted[0] pepObj2 = pepSorted[1] charge = spectraDict[title].ch mz = spectraDict[title].mz it = spectraDict[title].it kPos1 = [] kPos2 = [] if param['ntermxlink'] == True: if pepObj1.isNterm == True: kPos1.append(0) if pepObj2.isNterm == True: kPos2.append(0) pepseq1 = pepObj1.sequence kPos1.extend(list(zip(*filter(lambda x : x[1] == xresidue, enumerate(pepseq1[:-1])))[0])) pepseq2 = pepObj2.sequence kPos2.extend(list(zip(*filter(lambda x : x[1] == xresidue, enumerate(pepseq2[:-1])))[0])) for p1 in kPos1: for p2 in kPos2: positions = [p1, p2] xl = XLink(pepObj1, pepObj2, positions, charge, mass, param); XL.append(xl) match = Match(spectrum, xl, mass, param) match.match(mass) matches.append(match.getMatchInfo(index)) return matches
def calculateCombatDamage(self, combat_assignment, is_first_strike=False): new_combat_list = [] # Remove all attackers and blockers that are no longer valid for attacker, blockers in combat_assignment.items(): # Do the attacker first - make sure it is still valid if Match.isCreature(attacker) and attacker.in_combat: newblockers = [ blocker for blocker in blockers if Match.isCreature(blocker) and blocker.in_combat ] new_combat_list.append((attacker, newblockers)) # These guys are still valid damage_assignment = {} for attacker, blockers in new_combat_list: if attacker.canStrike(is_first_strike): attacker.didStrike() if not attacker.blocked: # XXX I should check that the attacker can damage the player damage = {attacker.opponent: attacker.combatDamage()} else: trampling = "trample" in attacker.abilities if len(blockers) > 1 or trampling: # Ask the player how to distribute damage # XXX I should check whether the attacker can assign damage to blocker damage = self.active_player.getDamageAssignment( [(attacker, blockers)], trample=trampling, deathtouch="deathtouch" in attacker.abilities) elif len(blockers) == 1: # XXX I should check whether the attacker can assign damage to blocker damage = {blockers[0]: attacker.combatDamage()} else: damage = { } # attacker was blocked, but there are no more blockers if trampling: damage[attacker.opponent] = attacker.trample(damage) damage_assignment[attacker] = damage # attacker receives all damage from blockers for blocker in blockers: if blocker.canStrike(is_first_strike): blocker.didStrike() # XXX Check whether the blocker can assign damage to attacker damage = {attacker: blocker.combatDamage()} # Handles the case where one blocker can block multiple creatures if damage_assignment.has_key(blocker): damage_assignment[blocker].update(damage) else: damage_assignment[blocker] = damage return damage_assignment
def build(self): query = Input(name='query', shape=(self.config['text1_maxlen'],)) doc = Input(name='doc', shape=(self.config['text2_maxlen'],)) dpool_index = Input(name='dpool_index', shape=[self.config['text1_maxlen'], self.config['text2_maxlen'], 3], dtype='int32') embedding = Embedding(self.config['vocab_size'], self.config['embed_size'], weights=[self.config['embed']], trainable = self.embed_trainable) q_embed = embedding(query) d_embed = embedding(doc) q_conv1 = Conv1D(self.config['kernel_count'], self.config['kernel_size'], padding='same') (q_embed) d_conv1 = Conv1D(self.config['kernel_count'], self.config['kernel_size'], padding='same') (d_embed) cross = Match(match_type='plus')([q_conv1, d_conv1]) cross_reshape = Reshape((self.config['text1_maxlen'], self.config['text2_maxlen'], 1))(cross) conv2d = Conv2D(self.config['kernel_count'], self.config['kernel_size'], padding='same', activation='relu') dpool = DynamicMaxPooling(self.config['dpool_size'][0], self.config['dpool_size'][1]) conv1 = conv2d(cross_reshape) pool1 = dpool([conv1, dpool_index]) pool1_flat = Flatten()(pool1) out_ = Dense(1)(pool1_flat) model = Model(inputs=[query, doc, dpool_index], outputs=out_) return model
def quit_match(self, matchid, userid): ''' 退赛 params int matchid 赛事id int userid 用户id ''' #logging.jsinfo('****** quit_match bg....') #这个赛事的参赛用户列表 MatchData.get(matchid).user_list.remove(userid) #这里也用到了pop方法哦! MatchData.get(matchid).user_conf.pop(userid, None) match = MatchData.get(matchid) if not match: logging.jsinfo('****** quit_match 1111') return 1 # 电竞赛额外处理 added by WangJian if (match.level == 'E_SPORTS'): #logging.jsinfo('****** quit_match 2222') lists = MatchDB.get_e_sport_extral_matchs(matchid) for i in lists: sub_match = MatchData.get( i['sub_id'] ) #logging.jsinfo('****** quit_match 3333, subid:%s', str(i['sub_id'])) if not sub_match: #logging.jsinfo('****** quit_match 4444') continue #logging.jsinfo('****** quit_match 5555') sub_match.user_list.remove(userid) sub_match.user_conf.pop(userid, None) #logging.jsinfo('****** quit_match 6666') return 1
def checkStatus(self, img_rgb): template = GC.chat_buy_anchor cv2.imwrite("basdfadfs.png", img_rgb) match = Match.this(img_rgb, template) if match: return True return False
def generateNextLevel(self): for i in range(len(self._league)): if self._league[i][0] == False: nextLevel = i break while len(self._next) != 0: if len(self._next) == 1: team = self._next.pop() self._league[nextLevel].append(Match(team, team)) elif len(self._next) == 2: self._league[nextLevel].append(Match(self._next.pop(),self._next.pop())) else: t1 = self._next.pop() t2 = self._next.pop() self._league[nextLevel].append(Match(t1,t2))
def match(self): i = 0 while i < len(self.submissions): order = self.submissions[i] i += 1 if order[1].isPass is 1: pass elif order[1].isLong is 0: if len(self.longOrders) == 0: self.shortOrders.append(order) self.shortOrders.sort(key=lambda x: x[1].bias, reverse=False) elif self.longOrders[0][1].bias >= order[1].bias: isMatch = True matchPrice = self.calculatePrice( self.longOrders[0][1].bias) self.price = matchPrice match0 = Match(matchPrice, 1, 1, self.curStep) match1 = Match(matchPrice, 1, 0, self.curStep) self.matchTable[self.longOrders[0][0]] = match0 self.matchTable[order[0]] = match1 self.upgradeAsset(self.longOrders[0][0], match0) self.upgradeAsset(order[0], match1) del self.longOrders[0] else: self.shortOrders.append(order) self.shortOrders.sort(key=lambda x: x[1].bias, reverse=False) else: if len(self.shortOrders) == 0: self.longOrders.append(order) self.longOrders.sort(key=lambda x: x[1].bias, reverse=True) elif self.shortOrders[0][1].bias <= order[1].bias: isMatch = True matchPrice = self.calculatePrice( self.shortOrders[0][1].bias) self.price = matchPrice match0 = Match(matchPrice, 1, 0, self.curStep) match1 = Match(matchPrice, 1, 1, self.curStep) self.matchTable[self.shortOrders[0][0]] = match0 self.matchTable[order[0]] = match1 self.upgradeAsset(self.shortOrders[0][0], match0) self.upgradeAsset(order[0], match1) del self.shortOrders[0] else: self.longOrders.append(order) self.longOrders.sort(key=lambda x: x[1].bias, reverse=True)
def findItem(self, img_rgb, item_file): for item in self.all_items: crop = Screenshot.crop(img_rgb, item.getSelfWindowCoord()) # cv2.imwrite("asdf.png", crop) if Match.this(crop, item_file, 0.70): return item.getSelfGlobalCoord() return False
def generateLeague(self): for i in range(ceil((log(len(self._teams))/log(2)))): self._league.append([False]) self._league[0].append(False) #This false represents that this levels haven't been cleared temp = list(self._teams.keys()) shuffle(temp) while len(temp) != 0: if len(temp) == 1: team = temp.pop() self._league[0].append(Match(team, team)) elif len(temp) == 2: self._league[0].append(Match(temp.pop(),temp.pop())) else: t1 = temp.pop() t2 = temp.pop() self._league[0].append(Match(t1,t2))
def check_fd_sel(fd, set): try: obj_sel = set['ObjSel']['Criteria'] if Match.parse(obj_sel, fd): return(True) return(False) except: if debug: print('ObjSel is not defined') return(True)
def arc2(a1d_kernel_count=256, a1d_kernel_size=3, num_conv2d_layers=1, a2d_kernel_counts=[64], a2d_kernel_sizes=[[5, 5], [5, 5]], a2d_mpool_sizes=[[2, 2], [2, 2]]): emb_layer = create_pretrained_embedding(config.word_embed_weights, mask_zero=False) q1 = Input(shape=(config.word_maxlen, )) q2 = Input(shape=(config.word_maxlen, )) q1_w = Input(shape=(config.word_maxlen, )) q2_w = Input(shape=(config.word_maxlen, )) if len(config.feats) == 0: magic_input = Input(shape=(1, )) else: magic_input = Input(shape=(len(config.feats), )) q1_embed = emb_layer(q1) q2_embed = emb_layer(q2) q_conv1 = Conv1D(a1d_kernel_count, a1d_kernel_size, padding='same')(q1_embed) d_conv1 = Conv1D(a1d_kernel_count, a1d_kernel_size, padding='same')(q2_embed) cross = Match(match_type='plus')([q_conv1, d_conv1]) z = Reshape((config.word_maxlen, config.word_maxlen, -1))(cross) for i in range(num_conv2d_layers): z = Conv2D(filters=a2d_kernel_counts[i], kernel_size=a2d_kernel_sizes[i], padding='same', activation='relu')(z) z = MaxPooling2D(pool_size=(a2d_mpool_sizes[i][0], a2d_mpool_sizes[i][1]))(z) #dpool = DynamicMaxPooling(self.config['dpool_size'][0], self.config['dpool_size'][1])([conv2d, dpool_index]) pool1_flat = Flatten()(z) pool1_flat_drop = Dropout(rate=0.5)(pool1_flat) out_ = Dense(1, activation='sigmoid')(pool1_flat_drop) model = Model(inputs=[q1, q2, q1_w, q2_w, magic_input], outputs=out_) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=[ Precision, Recall, F1, ]) model.summary() return model
class Main: print(1, 2) data = DM.DataManagement() data.createTournament(123) print(data.tournament) tournament = TN.Tournament(1) official = Off.Official("Max Mustermann", [1, 2, 3]) print(type(official.team)) match = Match.Match(Team.Team("Flying Foxes", tournament), Team.Team("Mighty Ducks", tournament)) # match.setResult(120,80) print(match.getResult()) example = TN.Tournament("Example tournament") foxes = Team.Team("Flying Foxes", example, rating=2100) ducks = Team.Team("Mighty Ducks", example, rating=1800) example.addTeam(foxes) example.addTeam(ducks) example.addPhase("Swiss System", 7) match2 = Match.Match(foxes, ducks) example.getCurrentPhase().addMatch(match) example.getCurrentPhase().addMatch(match2) for mat in example.getCurrentPhase().matches: mat.print() algo = Algorithms.Algorithms(None, Scheduling.Scheduling()) algo.schedule(example.getCurrentPhase()) print(example.getCurrentPhase().getMatches()[0].getResult()) match2.setResult((150, 100)) print(example.getCurrentPhase().getMatches()[0].getResult()) data.storeTournament(example) for mat in example.getCurrentPhase().matches: mat.print() data.loadTournament("Example tournament") tn = data.getTournament() print("Serialized") print(tn.getIdentifier()) print(tn.getCurrentPhase()) print(example.getCurrentPhase()) print(data.listStoredTournaments())
def apply_match(self, matchid, userid, username=''): ''' 赛事报名 params int id 赛事id ''' #加入赛事的用户列表 #logging.info('**** MatcherServer bg, mathid:%s, uid:%s', str(matchid), str(userid)) match = MatchData.get(matchid) if not match: #logging.info('**** MatcherServer, apply_match, unknow match, id:%s', str(matchid)) return False #重复报名的要退款 if match.user_list.count( str(userid) ) > 0: msg = { P.MATCH_ID : matchid, P.USER_ID : userid, P.USER_NAME : username, P.BUSISORT : 'MATCH_GAME', P.BUSINO : 'APPLY', } remotename = AGENT_ADDRESS c_sequence_id = '' data = P.pack().event( P.REPEAT_APPLY_BACKMONEY ).mid( c_sequence_id ).body( msg ).get() Message.send( remotename, data ) logging.info('REPEAT_APPLY_BACKMONEY---->%s'%msg) return False match.user_list.append( str(userid) ) match.user_conf[ str(userid) ] = {} match.user_conf[ str(userid) ][ 'username' ] = username match.user_conf[ str(userid) ][ 'user_agent' ] = '' match.user_conf[ str(userid) ][ 'is_trustee' ] = False #是否是托管状态 match.user_conf[ str(userid) ][ 'rebuy_times' ] = 0 #玩家已经rebuy的次数 match.user_conf[ str(userid) ][ 'rebuy_money' ] = 0 #玩家已经rebuy到的筹码 match.user_conf[ str(userid) ][ 'pro_rebuy_money' ] = 0 #预买筹码,还没到帐的筹码 match.user_conf[ str(userid) ][ 'rebuy_orderid' ] = [] #订单id:(lobby_orderid, acct_orderid) # 电竞赛额外处理 added by WangJian if (match.level == 'E_SPORTS'): lists = MatchDB.get_e_sport_extral_matchs(matchid) for i in lists: sub_match = MatchData.get( i['sub_id'] ) if not sub_match: continue sub_match.user_list.append( str(userid) ) sub_match.user_conf[ str(userid) ] = {} sub_match.user_conf[ str(userid) ][ 'username' ] = username sub_match.user_conf[ str(userid) ][ 'user_agent' ] = '' sub_match.user_conf[ str(userid) ][ 'is_trustee' ] = False #是否是托管状态 sub_match.user_conf[ str(userid) ][ 'rebuy_times' ] = 0 #玩家已经rebuy的次数 sub_match.user_conf[ str(userid) ][ 'rebuy_money' ] = 0 #玩家已经rebuy到的筹码 sub_match.user_conf[ str(userid) ][ 'pro_rebuy_money' ] = 0 #预买筹码,还没到帐的筹码 sub_match.user_conf[ str(userid) ][ 'rebuy_orderid' ] = [] #订单id:(lobby_orderid, acct_orderid)
def pairIsValid(player1, player2): """ Checks if a two players have already played with each other Args: player1 = id of player finding match player2 = id of player to be cross checked Returns: boolean value: True if a match already exists """ return Match.existsFor(player1, player2)
def reportMatch(tournament, winner, loser, draw='FALSE'): """ Reports a match's result to the database and assigns corresponding points to a player Args: tournament = id of tournament where the match took place winner = id of the winner loser = id of the loser draw = true if the match is a draw """ if draw == 'TRUE': wPoint = 1 lPoint = 1 else: wPoint = 3 lPoint = 0 Match.add(tournament, winner, loser) Score.add(tournament, winner, wPoint) Score.add(tournament, loser, lPoint)
def kickout_offline_user(self, match_id): ''' 强制不在线玩家退赛 入参:match_id 出参:offline_user_list 被踢玩家列表 编写:liulk 日期:2012.08.08 11:56 ''' #检查赛事配置,是否需要踢出不在线玩家 ret = MatchDB.kickout_or_not(match_id) if not ret: #不用踢人 return None else: #要踢人 #初始化踢人列表 offline_user_list = [] #取该赛事参赛人员列表 userlist = [] for item in MatchData.get(match_id).user_list: userlist.append(item) logging.info('apply userlist is----------> : %s'%userlist) userlist_len = len(userlist) for val in range(userlist_len): #检查该用户是否在线True or False online = Player.check_user_online_status( userlist[val] ) if online: continue else: #不在线,要踢掉他了,将userid加入踢人列表 offline_user_list.append(userlist[val]) #同时更新内存中的user_list, user_conf self.quit_match(match_id, userlist[val]) #将踢人列表发给代理服务,进行强制退赛 msg = { P.MATCH_ID : match_id, P.PLAYER_LIST : offline_user_list, } remotename = AGENT_ADDRESS logging.info('remotename is : %s'%str(remotename)) c_sequence_id = '' # 取子序列号 data = P.pack().event( P.KICKOUT_OFFLINE_USER ).mid( c_sequence_id ).body( msg ).get() Message.send( remotename, data ) logging.info('Inform lobby_misc to kick out the offline users!') logging.info('OFFLINE USER_LIST: %s'%offline_user_list) return offline_user_list
def build_model(emb_matrix, max_sequence_length): n1d_kernel_count = 32 n1d_kernel_size = 15 num_conv2d_layers = 2 n2d_kernel_counts = [32, 32] h2d_kernel_size = [[15, 15], [15, 15]] n2d_mpool_size = [[2, 2], [2, 2]] dropout_rate = 0.1 # The embedding layer containing the word vectors emb_layer = Embedding(input_dim=emb_matrix.shape[0], output_dim=emb_matrix.shape[1], weights=[emb_matrix], input_length=max_sequence_length, trainable=False) conv1d_layer = Conv1D(n1d_kernel_count, n1d_kernel_size, padding='same') seq1 = Input(shape=(max_sequence_length, )) seq2 = Input(shape=(max_sequence_length, )) q_embed = emb_layer(seq1) d_embed = emb_layer(seq2) q_conv1 = conv1d_layer(q_embed) d_conv1 = conv1d_layer(d_embed) cross = Match(match_type='plus')([q_conv1, d_conv1]) z = Reshape((max_sequence_length, max_sequence_length, -1))(cross) for i in range(num_conv2d_layers): z = Conv2D(filters=n2d_kernel_counts[i], kernel_size=h2d_kernel_size[i], padding='same', activation='relu')(z) z = MaxPooling2D(pool_size=(n2d_mpool_size[i][0], n2d_mpool_size[i][1]))(z) #dpool = DynamicMaxPooling(self.config['dpool_size'][0], self.config['dpool_size'][1])([conv2d, dpool_index]) pool1_flat = Flatten()(z) pool1_flat_drop = Dropout(dropout_rate)(pool1_flat) dense = Dense(300, activation='relu')(pool1_flat_drop) dense = Dropout(0.4)(dense) dense = Dense(30, activation='relu')(dense) dense = Dropout(0.4)(dense) pred = Dense(1, activation='sigmoid')(dense) model = Model(inputs=[seq1, seq2], outputs=pred) ada = Adam(lr=0.0001) model.compile(loss='binary_crossentropy', optimizer=ada, metrics=['acc']) return model
def calculateCombatDamage(self, combat_assignment, is_first_strike=False): new_combat_list = [] # Remove all attackers and blockers that are no longer valid for attacker, blockers in combat_assignment.items(): # Do the attacker first - make sure it is still valid if Match.isCreature(attacker) and attacker.in_combat and not attacker.is_LKI: newblockers = [blocker for blocker in blockers if Match.isCreature(blocker) and blocker.in_combat and not blocker.is_LKI] new_combat_list.append((attacker, newblockers)) # These guys are still valid damage_assignment = {} for attacker, blockers in new_combat_list: if attacker.canStrike(is_first_strike): attacker.didStrike() if not attacker.blocked: # XXX I should check that the attacker can damage the player damage = {attacker.opponent: attacker.combatDamage()} else: trampling = "trample" in attacker.abilities if len(blockers) > 1 or trampling: # Ask the player how to distribute damage # XXX I should check whether the attacker can assign damage to blocker damage = self.active_player.getDamageAssignment([(attacker, blockers)], trample=trampling, deathtouch="deathtouch" in attacker.abilities) elif len(blockers) == 1: # XXX I should check whether the attacker can assign damage to blocker damage = {blockers[0]: attacker.combatDamage()} else: damage = {} # attacker was blocked, but there are no more blockers if trampling: damage[attacker.opponent] = attacker.trample(damage) damage_assignment[attacker] = damage # attacker receives all damage from blockers for blocker in blockers: if blocker.canStrike(is_first_strike): blocker.didStrike() # XXX Check whether the blocker can assign damage to attacker damage = {attacker: blocker.combatDamage()} # Handles the case where one blocker can block multiple creatures if damage_assignment.has_key(blocker): damage_assignment[blocker].update(damage) else: damage_assignment[blocker] = damage return damage_assignment
def main(): start = time.time() seed(42) version_message = "Motif Analysis - Regulatory Analysis Toolbox (RGT) - v" + str( __version__) parser = argparse.ArgumentParser(prog='rgt-motifanalysis') parser.add_argument('--version', action='version', version=version_message) subparsers = parser.add_subparsers(help='Commands:') matching = subparsers.add_parser('matching', help='find all MPBS from input files') Match.options(matching) matching.set_defaults(func=Match.main) enrichment = subparsers.add_parser( 'enrichment', help='calculate statistics for MPBS files') Enrichment.options(enrichment) enrichment.set_defaults(func=Enrichment.main) # mapper = subparsers.add_parser('mapper', help='map genes names to TF IDs and viceversa') # Mapper.options(mapper) # mapper.set_defaults(func=Mapper.main) if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() args.func(args) secs = time.time() - start m, s = divmod(secs, 60) h, m = divmod(m, 60) print() print("[total time: ", "%dh %dm %ds" % (h, m, s), "]", sep="")
def readMatchs(self, matchList): try: file = open(self.__matchStats, "r") for linea in file.readlines(): matchNumber, gamerNames, totalPlays = linea.split("$") match = Match(matchNumber, [gamerNames], [totalPlays]) matchList.append(match) file.close() except: print("Archivo no disponible")
def findMatches(self, listOfMatches, discovered): ''' Finds the matches across all views from pairwise matches of features Graph algorithm: Iterate through all edges to find connected components :param listOfMatches: empty list to store Match objects :param discovered: empty list of dicts [viewid][image pt : match object] :return: ''' # for every connection for i in range(len(self.connections[VIEW_ID_1])): # Get the view id of the points viewId1 = self.connections[VIEW_ID_1][i] viewId2 = self.connections[VIEW_ID_2][i] for j in range(len(self.connections[SOURCE_POINTS][i])): # Get the coordinates of the point pt1 = tuple(self.connections[SOURCE_POINTS][i][j].astype('int16')) pt2 = tuple(self.connections[DESTINATION_POINTS][i][j].astype('int16')) # check if the point is in discovered # consider the cases: # if pt1 is discovered and pt2 is not then add to the existing match if pt1 in discovered[viewId1] and pt2 not in discovered[viewId2]: match = discovered[viewId1][pt1] match.addMatch(viewId2, pt2) discovered[viewId2][pt2] = match # if pt1 is not discovered and pt2 is discovered add to existing match elif pt1 not in discovered[viewId1] and pt2 in discovered[viewId2]: match = discovered[viewId2][pt2] match.addMatch(viewId1, pt1) discovered[viewId1][pt1] = match # if pt1 and pt2 are not discovered add both to the same match elif pt1 not in discovered[viewId1] and pt2 not in discovered[viewId2]: match = Match() match.addMatch(viewId1, pt1) match.addMatch(viewId2, pt2) discovered[viewId1][pt1] = match discovered[viewId2][pt2] = match listOfMatches.append(match)
def sim_match(a_name, b_name, teams): a_team = [x for x in teams if x["name"] == a_name][0] b_team = [x for x in teams if x["name"] == b_name][0] a_index = -1 b_index = -1 for i in range(len(teams)): if teams[i]["name"] == a_name: a_index = i if teams[i]["name"] == b_name: b_index = i a_elo = a_team[ELO] b_elo = b_team[ELO] match = Match(a_elo, b_elo) outcome = match.get_outcome() exp = match.get_expectation() a_goals, b_goals = match.get_score() match_data = { "a": { "name": a_name, "scored": a_goals, "elo": a_elo, "index": a_index }, "b": { "name": b_name, "scored": b_goals, "elo": b_elo, "index": b_index }, "exp": exp, "outcome": outcome } teams = update_team_goals(match_data, teams) teams = update_points(match_data, teams) teams = update_standings(match_data, teams) return teams
def confirmPrice(self): template = GC.offer_confirm found = Match.this(self.global_rs_image, template) # print found, "found" if found: found_coord = [ found[0], found[1], found[0] + GC.offer_button_dimensions[0], found[1] + GC.offer_button_dimensions[1] ] Mouse.clickRadius( self._calculateGlobalCoord(self.global_rs_coord, found_coord))
def displayMostProbablesLetters(self, criterias): pairsOfSeqOcc = self.getPairsOfSequenceOccurrencesIn(self.matchedAddresses, criterias) pairsCompleted = self.autoCompleteInput(criterias, pairsOfSeqOcc) sortedPairsOfSeqOcc = sorted(pairsCompleted.items(), key=lambda x: (-x[1], x[0]))[:5] if self.completionState == CompletionState.CITY: if len(sortedPairsOfSeqOcc) == 1: self.matchedAddresses = sorted(self.matchedAddresses, key=lambda address: address.city) tmp = Match.getTabOfDiffEltsOfAddrFrom(self.matchedAddresses, {"completionState": self.completionState}) inpt = utils.askForAnInputWithNum(tmp, {"completionState": self.completionState}, sortedPairsOfSeqOcc[0][0], "") final = self.getAddressFromCity(inpt) utils.printFinalCompletionAndQuit(final) else: self.printProbablesLetters(sortedPairsOfSeqOcc) else: if len(sortedPairsOfSeqOcc) == 1 and len(Match.getTabOfDiffEltsOfAddrFrom(self.matchedAddresses, {"completionState": CompletionState.CITY})) == 1: self.matchedAddresses = sorted(self.matchedAddresses, key=lambda address: address.streetName) utils.askForAnInputWithNum(self.matchedAddresses, {"completionState": self.completionState}, self.completedByEngine, sortedPairsOfSeqOcc[0][0]) else: if len(self.matchedAddresses) == 1: utils.printFinalCompletionAndQuit(self.matchedAddresses[0].value) else: self.printProbablesLetters(sortedPairsOfSeqOcc)
def build(self): def conv2d_work(input_dim): seq = Sequential() assert self.config['num_conv2d_layers'] > 0 for i in range(self.config['num_conv2d_layers']): seq.add(Conv2D(filters=self.config['2d_kernel_counts'][i], kernel_size=self.config['2d_kernel_sizes'][i], padding='same', activation='relu')) seq.add(MaxPooling2D(pool_size=(self.config['2d_mpool_sizes'][i][0], self.config['2d_mpool_sizes'][i][1]))) return seq query = Input(name='query', shape=(self.config['text1_maxlen'],)) show_layer_info('Input', query) doc = Input(name='doc', shape=(self.config['text2_maxlen'],)) show_layer_info('Input', doc) embedding = Embedding(self.config['vocab_size'], self.config['embed_size'], weights=[self.config['embed']], trainable = self.embed_trainable) q_embed = embedding(query) show_layer_info('Embedding', q_embed) d_embed = embedding(doc) show_layer_info('Embedding', d_embed) q_conv1 = Conv1D(self.config['1d_kernel_count'], self.config['1d_kernel_size'], padding='same') (q_embed) show_layer_info('Conv1D', q_conv1) d_conv1 = Conv1D(self.config['1d_kernel_count'], self.config['1d_kernel_size'], padding='same') (d_embed) show_layer_info('Conv1D', d_conv1) cross = Match(match_type='plus')([q_conv1, d_conv1]) show_layer_info('Match-plus', cross) z = Reshape((self.config['text1_maxlen'], self.config['text2_maxlen'], -1))(cross) show_layer_info('Reshape', z) for i in range(self.config['num_conv2d_layers']): z = Conv2D(filters=self.config['2d_kernel_counts'][i], kernel_size=self.config['2d_kernel_sizes'][i], padding='same', activation='relu')(z) show_layer_info('Conv2D', z) z = MaxPooling2D(pool_size=(self.config['2d_mpool_sizes'][i][0], self.config['2d_mpool_sizes'][i][1]))(z) show_layer_info('MaxPooling2D', z) #dpool = DynamicMaxPooling(self.config['dpool_size'][0], self.config['dpool_size'][1])([conv2d, dpool_index]) pool1_flat = Flatten()(z) show_layer_info('Flatten', pool1_flat) pool1_flat_drop = Dropout(rate=self.config['dropout_rate'])(pool1_flat) show_layer_info('Dropout', pool1_flat_drop) if self.config['target_mode'] == 'classification': out_ = Dense(2, activation='softmax')(pool1_flat_drop) elif self.config['target_mode'] in ['regression', 'ranking']: out_ = Dense(1)(pool1_flat_drop) show_layer_info('Dense', out_) model = Model(inputs=[query, doc], outputs=out_) return model
def build(self): query = Input(name='query', shape=(self.config['text1_maxlen'], )) show_layer_info('Input', query) doc = Input(name='doc', shape=(self.config['text2_maxlen'], )) show_layer_info('Input', doc) embedding = Embedding(self.config['vocab_size'], self.config['embed_size'], weights=[self.config['embed']], trainable=self.embed_trainable) q_embed = embedding(query) show_layer_info('Embedding', q_embed) d_embed = embedding(doc) show_layer_info('Embedding', d_embed) q_rep = Bidirectional( LSTM(self.config['hidden_size'], return_sequences=True, dropout=self.config['dropout_rate']))(q_embed) show_layer_info('Bidirectional-LSTM', q_rep) d_rep = Bidirectional( LSTM(self.config['hidden_size'], return_sequences=True, dropout=self.config['dropout_rate']))(d_embed) show_layer_info('Bidirectional-LSTM', d_rep) cross = Match(match_type='dot')([q_rep, d_rep]) #cross = Dot(axes=[2, 2])([q_embed, d_embed]) show_layer_info('Match-dot', cross) cross_reshape = Reshape((-1, ))(cross) show_layer_info('Reshape', cross_reshape) mm_k = Lambda(lambda x: K.tf.nn.top_k( x, k=self.config['topk'], sorted=True)[0])(cross_reshape) show_layer_info('Lambda-topk', mm_k) pool1_flat_drop = Dropout(rate=self.config['dropout_rate'])(mm_k) show_layer_info('Dropout', pool1_flat_drop) if self.config['target_mode'] == 'classification': out_ = Dense(2, activation='softmax')(pool1_flat_drop) elif self.config['target_mode'] in ['regression', 'ranking']: out_ = Dense(1)(pool1_flat_drop) show_layer_info('Dense', out_) #model = Model(inputs=[query, doc, dpool_index], outputs=out_) model = Model(inputs=[query, doc], outputs=out_) return model
def main(): start = time.time() seed(42) version_message = "Motif Analysis - Regulatory Analysis Toolbox (RGT) - v" + str(__version__) parser = argparse.ArgumentParser(prog='rgt-motifanalysis') parser.add_argument('--version', action='version', version=version_message) subparsers = parser.add_subparsers(help='Commands:') matching = subparsers.add_parser('matching', help='find all MPBS from input files') Match.options(matching) matching.set_defaults(func=Match.main) enrichment = subparsers.add_parser('enrichment', help='calculate statistics for MPBS files') Enrichment.options(enrichment) enrichment.set_defaults(func=Enrichment.main) # mapper = subparsers.add_parser('mapper', help='map genes names to TF IDs and viceversa') # Mapper.options(mapper) # mapper.set_defaults(func=Mapper.main) if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() args.func(args) secs = time.time() - start m, s = divmod(secs, 60) h, m = divmod(m, 60) print() print("[total time: ", "%dh %dm %ds" % (h, m, s), "]", sep="")
def setSelfWindowCoord(self, img_rgb): # off_set = [-7, -7] off_set = [-69, 42] template = GC.bag_icon match = Match.this(img_rgb, template) if match: # print match,"match" return [ match[0] + off_set[0], match[1] + off_set[1], match[2] + self.WINDOWSIZE[0], match[3] + self.WINDOWSIZE[1] ] return None
def getMatch(data={}): global teams match = m.Match(data['dates'], data['gender'], data['match_type'], getOutcome(data['outcome']), getToss(data['toss']), data['umpires']) if ('city' in data.keys()): match.city = data['city'] if ('neutral_venue' in data.keys()): match.neutralVenue = data['neutral_venue'] if ('competition' in data.keys()): match.competition = data['competition'] if ('venue' in data.keys()): match.venue = data['venue'] if ('player_of_match' in data.keys()): match.playerOfMatch = data['player_of_match'] if ('supersubs' in data.keys()): match.supersubs = data['supersubs'] if ('overs' in data.keys()): match.overs = data['overs'] #todo if ('bowl_out' in data.keys()): match.bowlout = data['bowl_out'] # teams for i in data['teams']: teams[i] = m.Team(i) return match
def __init__(self, left, right): self.left = left self.right = right self.modelstate = STATE_NEW self.tree_structure_lock = threading.Lock() self.operation_thread = None self.operation_arg = None self.comparison_thread = None self.stop_comparison = False self.top = Match.Match(left, right, None) self.top.mark_as_unenumerated()
def Match(self, query: str): matches: [Match] = [] if query == "hello": match = Match() match.text = "Hello There!" match.data = "Data :-)" match.subtext = "Example" match.icon = "planetkde" matches.append(match) return matches
def Kafka_Consumer_UserRecords(CONFIG): # 基本設定 settings = { 'bootstrap.servers': f'{CONFIG["KAFKA"]["HOST"]}', 'group.id': CONFIG["KAFKA"]['TOPIC_1'], 'client.id': 'client-1', 'enable.auto.commit': True, 'session.timeout.ms': 6000, 'default.topic.config': { 'auto.offset.reset': 'smallest' } } # 設定Consumer物件 c = Consumer(settings) # 設定要Consum的topic c.subscribe([CONFIG["KAFKA"]['TOPIC_1']]) try: while True: # 將kafka 上的資訊拉下來 msg = c.poll(1) if msg is None: continue if not msg.error(): # Test print('({0}, {1})'.format(msg.key(), msg.value())) # 將bytes轉換成string msg_key = msg.key().decode() msg_value = msg.value().decode() result = Match.Recipe_Match(CONFIG, msg_key, msg_value) return result elif msg.error().code() == KafkaError._PARTITION_EOF: print('End of partition reached {0}/{1}'.format( msg.topic(), msg.partition())) else: print('Error occured: {0}'.format(msg.error().str())) except KeyboardInterrupt: pass finally: c.close()
def clickBuy(self): template = GC.status_buy_button found = Match.this(self.global_rs_image, template) if found: found_coord = [ found[0], found[1], found[0] + GC.status_buy_button_dimensions[0], found[1] + GC.status_buy_button_dimensions[1] ] # print found_coord # Mouse.win32MoveToRadius(self._calculateGlobalCoord(self.global_self_coord,found_coord)) # Mouse.win32ClickRadius(self._calculateGlobalCoord(self.global_self_coord, found_coord)) Mouse.clickRadius( self._calculateGlobalCoord(self.global_self_coord, found_coord))
def build(self): query = Input(name='query', shape=(self.config['query_maxlen'],)) doc = Input(name='doc', shape=(self.config['doc_maxlen'],)) embedding = Embedding(self.config['vocab_size'], self.config['embed_size'], weights=[self.config['embed']], trainable = self.embed_trainable) q_embed = embedding(query) d_embed = embedding(doc) q_conv1 = Conv1D(self.config['1d_kernel_count'], self.config['1d_kernel_size'], activation='relu', padding='same') (q_embed) d_conv1 = Conv1D(self.config['1d_kernel_count'], self.config['1d_kernel_size'], activation='relu', padding='same') (d_embed) cross = Match(match_type='concat')([q_conv1, d_conv1]) z = Reshape((self.config['query_maxlen'], self.config['doc_maxlen'], -1))(cross) for i in range(self.config['num_conv2d_layers']): z = Conv2D(self.config['2d_kernel_counts'][i], self.config['2d_kernel_sizes'][i], padding='same', activation='relu')(z) print z.shape z = MaxPooling2D(pool_size=(self.config['2d_mpool_sizes'][i][0], self.config['2d_mpool_sizes'][i][1]))(z) print z.shape pool1_flat = Flatten()(z) pool1_flat_drop = Dropout(rate=self.config['dropout_rate'])(pool1_flat) hidden_res = pool1_flat_drop num_layers = len(self.config['hidden_sizes']) for i in range(num_layers): hidden_res = Dense(self.config['hidden_sizes'][i])(hidden_res) hidden_res = BatchNormalization(center=False, scale=False)(hidden_res) if i < num_layers - 1: hidden_res = Activation('relu')(hidden_res) else: hidden_res = Activation('tanh')(hidden_res) out_ = hidden_res model = Model(inputs=[query, doc], outputs=out_) return model
def fix_objact(s, fd, handle, set, **kwargs): ask_flag = kwargs.get('Ask',True) if not check_fd_sel(fd, set): return for obj_act in set['ObjAct']: if not obj_act['Action']: pass if Match.parse(obj_act['Criteria'], fd): if obj_act['Action']['Action'] == 'SetOwner': nu = DCC.prop_get(s, obj_act['Action']['Owner'], InfoSet = 'User') print('??? Change Owner from [', fd['owner-userid'], ',', fd['owner-username'], '] to [', nu['owner-userid'], ',', nu['owner-username'], ']', sep = '', end = '') if ask_flag == False or MyUtil.get_yn(': (Y/N)? '): DCC.change_owner(s, handle, obj_act['Action']['Owner']) elif obj_act['Action']['Action'] == 'AddKeyword': print('??? Add Keyword "', obj_act['Action']['Keyword'], '" to "', fd['keywords'].strip(), '"', sep = '', end = '') if ask_flag == False or MyUtil.get_yn(': (Y/N)? '): kw = obj_act['Action']['Keyword'] + fd['keywords'].strip(' ') DCC.set_metadata(s, handle, Keywords = kw) elif obj_act['Action']['Action'] == 'DelKeyword': print('??? Remove Keyword "', obj_act['Action']['Keyword'], '" from "', fd['keywords'], '"', sep = '', end = '') if ask_flag == False or MyUtil.get_yn(': (Y/N)? '): kw = fd['keywords'].strip(' ').replace(obj_act['Action']['Keyword'], '') DCC.set_metadata(s, handle, Keywords = kw) elif obj_act['Action']['Action'] == 'RepTitle': print('??? Change Title to "', obj_act['Action']['Title'], '" from "', fd['title'], '"', sep = '', end = '') if ask_flag == False or MyUtil.get_yn(': (Y/N)? '): DCC.set_metadata(s, handle, Title = obj_act['Action']['Title']) elif obj_act['Action']['Action'] == 'RepTmtNum': print('??? Change TmtNum to "', obj_act['Action']['TmtNum'], '" from "', fd['tmtnum'], '"', sep = '', end = '') if ask_flag == False or MyUtil.get_yn(': (Y/N)? '): DCC.set_metadata(s, handle, Summary = obj_act['Action']['TmtNum']) pass elif obj_act['Action']['Action'] == 'Message': print(obj_act['Action']['Message']) else: print('Error in PERM.fix_objact: ObjAct Action not recognized:', obj_act['Action']['Action'])
def get_winners(self): """Get stage winners. If the stage was a cup, returns winning clubs of match pairs. If the stage was a league, returns top x clubs of the league, x being the number of promotions in stage setup. If the stage was not yet finished, will probably fail. """ retval = [] if self.type == StageType.Cup: if self.setup.matchrules.replays != Match.TiebreakerType.Off: for m in self.rounds[0]: w = m.get_winner_name() if w != "unknown" and w != "draw": retval.append(w) for m in self.rounds[1]: w = m.get_winner_name() if w == "draw": raise ValueError("Replay match was a draw!") if w != "unknown": retval.append(w) else: if self.setup.rounds == 1: for m in self.rounds[0]: w = m.get_winner_name() if w != "unknown": retval.append(w) elif self.setup.rounds == 2: ms = zip(self.rounds[0], self.rounds[1]) for m1, m2 in ms: w = Match.double_match_result(m1.mr, m2.mr, self.setup.matchrules) if w == Match.MatchResultType.Club1: retval.append(m2.club1.name) elif w == Match.MatchResultType.Club2: retval.append(m2.club2.name) else: raise ValueError("Match.double_match_result() returned draw!") else: raise ValueError("Only up to two rounds per knockout stage supported at the moment") else: for group in self.groups_club_names: table = LeagueTable.create_league_table(self.rounds, group, self.setup.pointsperwin) if len(self.promotions) > 0: retval.extend(table.get_top(self.promotions[0].num / self.setup.groups)) # TODO - only returns top x return retval
def check_perm_sel(permdata, set): # PermSel Criteria is a list of checks against permissions. If the complete list passes # then the PermAct actions will be undertaken. try: perm_sels = set['PermSel']['Criteria'] for perm_sel in perm_sels: if debug: print('check_perm_sel:',perm_sel) for perm in permdata['perms']: match_flag = False if Match.parse(perm_sel, perm): match_flag = True break if match_flag == False: if debug: print('check_perm_sel: returning False') return(False) if debug: print('check_perm_sel: returning True') return(True) except: if debug: print('PermSel is not defined') return(True)
def deleteMatches(): """Removes all match records from the database.""" Match.deleteAll() Score.reset()
for i in range(len(tophits)): pep1 = tophits[i][0][0] pep2 = tophits[i][0][1] pro1 = tophits[i][2][0] pro2 = tophits[i][2][1] pos1 = tophits[i][1][0] pos2 = tophits[i][1][1] ch = tophits[i][3] title = tophits[i][5] filename = pep1 + '_' + pep2 + '_' + str(pos1) + '_' + str(pos2) + '_' + str(ch) + '_' + title + '.annotation' modification = dict(position=[], deltaMass=[]) for j in range(len(pep1)): if pep1[j].islower(): modification['position'].append(j) modification['deltaMass'].append(param['modMass']) pep1 = Peptide(pep1, ', '.join(pro1), modification, mass) modification = dict(position=[], deltaMass=[]) for j in range(len(pep2)): if pep2[j].islower(): modification['position'].append(j) modification['deltaMass'].append(param['modMass']) pep2 = Peptide(pep2, ', '.join(pro2), modification, mass) xl = XLink(pep1, pep2, [pos1, pos2], ch, mass, param) match = Match(specdict[title], xl, mass, param) match.annotate(filename, mass) print 'Outputting results done!' print 'XLSearch finished running!'
def get_true_false(TrueTrue, param, mass): linkermass = param['linkermass'] ttseq = set() m = [] for match in TrueTrue: ttseq.add(match.xlink.pepObjs[0].sequence) ttseq.add(match.xlink.pepObjs[1].sequence) m.append(match.xlink.mr - linkermass) m = max(m) fasta = FastaReader(param['uniprot_database']).readFasta() patternString = param['patternstring'] peptides = dict() for header, sequence in fasta: if 'MOUSE' in header: pepObjInPro = getPepObjsFromProtein(header, sequence, patternString, mass, param) for pep in pepObjInPro: if pep.sequence not in peptides and pep.sequence not in ttseq and pep.pm < m: peptides[pep.sequence] = pep peptides = peptides.values() TrueFalse = [] A = [] B = [] for i in range(len(TrueTrue)): print i match = TrueTrue[i] ch = match.spectrum.ch tol = match.xlink.mr * 5 * (10 ** (-6)) A.append([]) B.append([]) pepObjs = match.xlink.pepObjs for j in range(len(peptides)): if abs(pepObjs[0].pm + peptides[j].pm + linkermass - match.xlink.mr) <= tol: pepseq1 = pepObjs[0].sequence pepseq2 = peptides[j].sequence kPos1 = list(zip(*filter(lambda x : x[1] == param['xresidue'], enumerate(pepseq1[:-1])))[0]) kPos2 = list(zip(*filter(lambda x : x[1] == param['xresidue'], enumerate(pepseq2[:-1])))[0]) positions = [kPos1[len(kPos1)/2], kPos2[len(kPos2)/2]] xl = XLink(pepObjs[0], peptides[j], positions, ch, mass, param) tf = Match(match.spectrum, xl, mass, param) tf.match(mass) feature = tf.feature if feature[1][0] / float(feature[1][7]) + feature[1][1] / float(feature[1][7]) >= 0.2: A[-1].append(tf) for j in range(len(peptides)): if abs(pepObjs[1].pm + peptides[j].pm + linkermass - match.xlink.mr) <= tol: pepseq1 = pepObjs[1].sequence pepseq2 = peptides[j].sequence kPos1 = list(zip(*filter(lambda x : x[1] == param['xresidue'], enumerate(pepseq1[:-1])))[0]) kPos2 = list(zip(*filter(lambda x : x[1] == param['xresidue'], enumerate(pepseq2[:-1])))[0]) positions = [kPos1[len(kPos1)/2], kPos2[len(kPos2)/2]] xl = XLink(pepObjs[1], peptides[j], positions, ch, mass, param) tf = Match(match.spectrum, xl, mass, param) tf.match(mass) feature = tf.feature if feature[1][0] / float(feature[1][7]) + feature[1][1] / float(feature[1][7])>= 0.2: B[-1].append(tf) AB = [A, B] return AB
def run(self): out_links=Match.execute(self.parent.tableWidget.links) self.parent and self.parent.on_thread_finished(self, out_links)
def to_rounds(self, db): """Return rounds. Given DB, create rounds of the schedule. Call feed_club_names first in order to feed stage with club names. If club names missing, rounds will be filled with 'unknown'. """ if len(self.rounds) > 0: return self.rounds missing_clubs = self.setup.participantnum - len(self.club_names) while missing_clubs > 0: missing_clubs -= 1 self.club_names.append("unknown") if len(self.club_names) == 0: return self.rounds random.shuffle(self.club_names) if self.type == StageType.League: num_clubs_per_club = self.setup.participantnum / self.setup.groups plans = [] self.groups_club_names = [] for i in range(0, self.setup.groups): self.groups_club_names.append(self.club_names[i * num_clubs_per_club:(i + 1) * num_clubs_per_club]) for i in range(0, self.setup.groups): plans.append(round_robin.round_robin(self.groups_club_names[i])) plan = Primitives.ziplists(plans) * self.setup.rounds else: i = False l = [] for c in self.club_names: i = not i if i: c1 = c else: c2 = c l.append((c1, c2)) plan = [] i = False l_sw = [Primitives.switch_tuple(cp) for cp in l] for ind in range(self.setup.rounds): i = not i if i: plan.append(l) else: plan.append(l_sw) for round in plan: matches = [] self.multiple_legs = self.type == StageType.Cup and self.setup.rounds > 1 used_rules = self.setup.matchrules if self.multiple_legs or self.setup.matchrules.replays != Match.TiebreakerType.Off: # TODO: replays.AfterET used_rules = Match.std_match_rules() for c1, c2 in round: m = Match.Match(db.clubs[c1], db.clubs[c2], used_rules, Match.MatchResult(), stage_name = self.name) if db.clubs[c1].name != "unknown": m.stadium = db.stadiums[db.clubs[c1].stadium] m.stage_name = self.name matches.append(m) if len(matches) > 0: self.rounds.append(matches) if self.setup.matchrules.replays != Match.TiebreakerType.Off: self.rounds.append([]) if self.type == StageType.League: self.num_planned_rounds = len(self.rounds) else: self.num_planned_rounds = self.setup.rounds if self.setup.matchrules.replays != Match.TiebreakerType.Off: self.num_planned_rounds += 1 return self.rounds
def checkSBE(self): #State-Based Effects - rule 420.5 # check every time someone gets priority (rule 408.1b) # Also during cleanup step - if there is an effect, player gets priority players = self.players actions = [] # 420.5a A player with 0 or less life loses the game. def LoseGame(player, msg): def SBE(): player.lose(msg) return SBE for player in players: if player.life <= 0: actions.append(LoseGame(player, "has less than 1 life")) # 420.5b and 420.5c are combined # 420.5b A creature with toughness 0 or less is put into its owner's graveyard. Regeneration can't replace this event. # 420.5c A creature with lethal damage, but greater than 0 toughness, is destroyed. Lethal damage is an amount of damage greater than or equal to a creature's toughness. Regeneration can replace this event. def MoveToGraveyard(permanent): def SBE(): permanent.move_to("graveyard") return SBE for creature in self.battlefield.get(Match.isCreature): if creature.toughness <= 0: actions.append(MoveToGraveyard(creature)) elif creature.shouldDestroy() or creature.deathtouched: creature.deathtouched = False actions.append(creature.destroy) for walker in self.battlefield.get(Match.isPlaneswalker): if walker.shouldDestroy(): actions.append(walker.destroy) # 420.5d An Aura attached to an illegal object or player, or not attached to an object or player, is put into its owner's graveyard. for aura in self.battlefield.get(Match.isAura): if not aura.isValidAttachment(): actions.append(MoveToGraveyard(aura)) # 420.5e If two or more legendary permanents with the same name are on the battlefield, all are put into their owners' graveyards. This is called the "legend rule." If only one of those permanents is legendary, this rule doesn't apply. legendaries = self.battlefield.get(Match.isLegendaryPermanent) # XXX There's got to be a better way to find multiples remove_dup = [] for i, l1 in enumerate(legendaries): for l2 in legendaries[i+1:]: if l1.name == l2.name: remove_dup.extend([l1,l2]) break # 2 or more Planeswalkers with the same name planeswalkers = self.battlefield.get(Match.isPlaneswalker) for i, l1 in enumerate(planeswalkers): for l2 in planeswalkers[i+1:]: if l1.subtypes.intersects(l2.subtypes): remove_dup.extend([l1,l2]) break # Now remove all the cards in remove_dup if len(remove_dup) > 0: def SBE(): for card in remove_dup: player = card.controller card.move_to("graveyard") actions.append(SBE) # 420.5f A token in a zone other than the battlefield zone ceases to exist. # 704.5e. If a copy of a spell is in a zone other than the stack, it ceases to exist. If a copy of a card is in any zone other than the stack or the battlefield, it ceases to exist. if len(self._non_card_leaving_zone) > 0: def SBE(): for noncard in self._non_card_leaving_zone: noncard.zone.cease_to_exist(noncard) # XXX Now only GameObjects.cardmap has a reference to the token - we need to delete it somehow self._non_card_leaving_zone[:] = [] actions.append(SBE) # 420.5g A player who attempted to draw a card from an empty library since the last time state-based effects were checked loses the game. for player in players: if player.draw_empty: actions.append(LoseGame(player, "draws from an empty library")) # 420.5h A player with ten or more poison counters loses the game. for player in players: if player.poison >= 10: actions.append(LoseGame(player, "is poisoned")) # 420.5i If two or more permanents have the supertype world, all except the one that has been a permanent with the world supertype on the battlefield for the shortest amount of time are put into their owners' graveyards. In the event of a tie for the shortest amount of time, all are put into their owners' graveyards. This is called the "world rule." # 420.5j A copy of a spell in a zone other than the stack ceases to exist. A copy of a card in any zone other than the stack or the battlefield zone ceases to exist. # 420.5k An Equipment or Fortification attached to an illegal permanent becomes unattached from that permanent. It remains on the battlefield. for equipment in self.battlefield.get(Match.isEquipment): if equipment.attached_to and not equipment.isValidAttachment(): actions.append(equipment.unattach) # 420.5m A permanent that's neither an Aura, an Equipment, nor a Fortification, but is attached to another permanent, becomes unattached from that permanent. It remains on the battlefield . for permanent in self.battlefield.get(Match.isPermanent): if hasattr(permanent, "attached_to") and permanent.attached_to and not Match.isAttachment(permanent): actions.append(permanent.unattach) # 420.5n If a permanent has both a +1/+1 counter and a -1/-1 counter on it, N +1/+1 and N -1/-1 counters are removed from it, where N is the smaller of the number of +1/+1 and -1/-1 counters on it. def RemoveCounters(perm, num): def SBE(): perm.remove_counters("+1+1", num) perm.remove_counters("-1-1", num) return SBE for perm in self.battlefield.get(Match.isPermanent): if perm.num_counters() > 0: plus = perm.num_counters("+1+1") minus = perm.num_counters("-1-1") numremove = min(plus, minus) if numremove: actions.append(RemoveCounters(perm, numremove)) if actions: for action in actions: action() self.send(TimestepEvent()) return not len(actions) == 0
def get_false_false(TrueTrue, param, mass): linkermass = param['linkermass'] ttseq = set() m = [] for match in TrueTrue: ttseq.add(match.xlink.pepObjs[0].sequence) ttseq.add(match.xlink.pepObjs[1].sequence) m.append(match.xlink.mr - linkermass) mi = int(min(m) - 0.2) ma = int(max(m) + 0.2) fasta = FastaReader(param['uniprot_database']).readFasta() patternString = param['patternstring'] peptides = dict() for header, sequence in fasta: if 'YEAST' in header: pepObjInPro = getPepObjsFromProtein(header, sequence, patternString, mass, param) for pep in pepObjInPro: if pep.sequence not in peptides and pep.sequence not in ttseq: peptides[pep.sequence] = pep peptides = peptides.values() intdict = dict() for peptide in peptides: num = int(peptide.pm) if num > ma: continue if num not in intdict: intdict[num] = [peptide] else: intdict[num].append(peptide) FalseFalse = [] for k in range(len(TrueTrue)): match = TrueTrue[k] print k sys.stdout.flush() FalseFalse.append([]) pm = match.xlink.mr - linkermass ch = match.spectrum.ch tol = match.xlink.mr * 3 * (10 ** (-6)) mlist = range(500, ma - 500) shuffle(mlist) mlist = mlist[:25] for m in mlist: if m not in intdict: continue shuffle(intdict[m]) intdict[m] = intdict[m][:50] for i in range(len(intdict[m])): num = int(pm - intdict[m][i].pm) if num not in intdict: continue shuffle(intdict[num]) intdict[num] = intdict[num][:50] for j in range(len(intdict[num])): pepseq1 = intdict[m][i].sequence pepseq2 = intdict[num][j].sequence kPos1 = list(zip(*filter(lambda x : x[1] == param['xresidue'], enumerate(pepseq1[:-1])))[0]) kPos2 = list(zip(*filter(lambda x : x[1] == param['xresidue'], enumerate(pepseq2[:-1])))[0]) positions = [kPos1[len(kPos1)/2], kPos2[len(kPos2)/2]] xl = XLink(intdict[m][i], intdict[num][j], positions, ch, mass, param) if abs(match.xlink.mr - xl.mr) <= tol: ff = Match(match.spectrum, xl, mass, param) ff.match(mass) feature = ff.feature if feature[0][0] / float(feature[0][7]) + feature[0][1] / float(feature[0][7]) >= 0.15 and feature[1][0] / float(feature[1][7]) + feature[1][1] / float(feature[1][7]) >= 0.15: FalseFalse[-1].append(ff) return FalseFalse