How to use counter method in Testify

Best Python code snippet using Testify_python

random-teams.ts

Source:random-teams.ts Github

copy

Full Screen

1import type {PRNG} from '../../../sim';2import RandomTeams, {MoveCounter} from '../../random-teams';3export class RandomLetsGoTeams extends RandomTeams {4 constructor(format: Format | string, prng: PRNG | PRNGSeed | null) {5 super(format, prng);6 this.moveEnforcementCheckers = {7 Dark: (movePool, moves, abilities, types, counter) => !counter.get('Dark'),8 Dragon: (movePool, moves, abilities, types, counter) => !counter.get('Dragon'),9 Electric: (movePool, moves, abilities, types, counter) => !counter.get('Electric'),10 Fighting: (movePool, moves, abilities, types, counter) => (11 !counter.get('Fighting') && (!!counter.setupType || !counter.get('Status'))12 ),13 Fire: (movePool, moves, abilities, types, counter) => !counter.get('Fire'),14 Ghost: (movePool, moves, abilities, types, counter) => !types.has('Dark') && !counter.get('Ghost'),15 Ground: (movePool, moves, abilities, types, counter) => !counter.get('Ground'),16 Ice: (movePool, moves, abilities, types, counter) => !counter.get('Ice'),17 Water: (movePool, moves, abilities, types, counter) => !counter.get('Water') || !counter.get('stab'),18 };19 }20 shouldCullMove(21 move: Move,22 types: Set<string>,23 moves: Set<string>,24 abilities: Set<string>,25 counter: MoveCounter,26 movePool: string[],27 teamDetails: RandomTeamsTypes.TeamDetails,28 ): {cull: boolean, isSetup?: boolean} {29 switch (move.id) {30 // Set up once and only if we have the moves for it31 case 'bulkup': case 'swordsdance':32 return {33 cull: (34 counter.setupType !== 'Physical' ||35 counter.get('physicalsetup') > 1 ||36 counter.get('Physical') + counter.get('physicalpool') < 237 ),38 isSetup: true,39 };40 case 'calmmind': case 'nastyplot': case 'quiverdance':41 return {42 cull: (43 counter.setupType !== 'Special' ||44 counter.get('specialsetup') > 1 ||45 counter.get('Special') + counter.get('specialpool') < 246 ),47 isSetup: true,48 };49 case 'growth': case 'shellsmash':50 return {51 cull: (52 counter.setupType !== 'Mixed' ||53 (counter.damagingMoves.size + counter.get('physicalpool') + counter.get('specialpool')) < 254 ),55 isSetup: true,56 };57 case 'agility':58 return {59 cull: counter.damagingMoves.size < 2 && !counter.setupType,60 isSetup: !counter.setupType,61 };62 // Bad after setup63 case 'dragontail':64 return {cull: (65 !!counter.setupType || !!counter.get('speedsetup') || ['encore', 'roar', 'whirlwind'].some(m => moves.has(m))66 )};67 case 'fakeout': case 'uturn': case 'teleport':68 return {cull: !!counter.setupType || !!counter.get('speedsetup') || moves.has('substitute')};69 case 'haze': case 'leechseed': case 'roar': case 'whirlwind':70 return {cull: !!counter.setupType || !!counter.get('speedsetup') || moves.has('dragontail')};71 case 'protect':72 return {cull: !!counter.setupType || ['rest', 'lightscreen', 'reflect'].some(m => moves.has(m))};73 case 'seismictoss':74 return {cull: counter.damagingMoves.size > 1 || !!counter.setupType};75 case 'stealthrock':76 return {cull: !!counter.setupType || !!counter.get('speedsetup') || !!teamDetails.stealthRock};77 // Bit redundant to have both78 case 'leechlife': case 'substitute':79 return {cull: moves.has('uturn')};80 case 'dragonpulse':81 return {cull: moves.has('dragontail') || moves.has('outrage')};82 case 'thunderbolt':83 return {cull: moves.has('thunder')};84 case 'flareblitz': case 'flamethrower':85 return {cull: moves.has('fireblast') || moves.has('firepunch')};86 case 'megadrain':87 return {cull: moves.has('petaldance') || moves.has('powerwhip')};88 case 'bonemerang':89 return {cull: moves.has('earthquake')};90 case 'icebeam':91 return {cull: moves.has('blizzard')};92 case 'rockslide':93 return {cull: moves.has('stoneedge')};94 case 'hydropump': case 'willowisp':95 return {cull: moves.has('scald')};96 case 'surf':97 return {cull: moves.has('hydropump') || moves.has('scald')};98 }99 // Increased/decreased priority moves are unneeded with moves that boost only speed100 if (move.priority !== 0 && !!counter.get('speedsetup')) return {cull: true};101 // This move doesn't satisfy our setup requirements:102 if (103 (move.category === 'Physical' && counter.setupType === 'Special') ||104 (move.category === 'Special' && counter.setupType === 'Physical')105 ) {106 // Reject STABs last in case the setup type changes later on107 if (!types.has(move.type) || counter.get('stab') > 1 || counter.get(move.category) < 2) return {cull: true};108 }109 return {cull: false};110 }111 randomSet(species: string | Species, teamDetails: RandomTeamsTypes.TeamDetails = {}): RandomTeamsTypes.RandomSet {112 species = this.dex.species.get(species);113 let forme = species.name;114 if (typeof species.battleOnly === 'string') {115 // Only change the forme. The species has custom moves, and may have different typing and requirements.116 forme = species.battleOnly;117 }118 const movePool = (species.randomBattleMoves || Object.keys(this.dex.species.getLearnset(species.id)!)).slice();119 const types = new Set(species.types);120 const moves = new Set<string>();121 let counter;122 do {123 // Choose next 4 moves from learnset/viable moves and add them to moves list:124 while (moves.size < this.maxMoveCount && movePool.length) {125 const moveid = this.sampleNoReplace(movePool);126 moves.add(moveid);127 }128 counter = this.queryMoves(moves, species.types, new Set(), movePool);129 // Iterate through the moves again, this time to cull them:130 for (const moveid of moves) {131 const move = this.dex.moves.get(moveid);132 let {cull, isSetup} = this.shouldCullMove(move, types, moves, new Set(), counter, movePool, teamDetails);133 if (134 !isSetup &&135 counter.setupType && counter.setupType !== 'Mixed' &&136 move.category !== counter.setupType &&137 counter.get(counter.setupType) < 2 && (138 // Mono-attacking with setup and RestTalk is allowed139 // Reject Status moves only if there is nothing else to reject140 move.category !== 'Status' || (141 counter.get(counter.setupType) + counter.get('Status') > 3 &&142 counter.get('physicalsetup') + counter.get('specialsetup') < 2143 )144 )145 ) {146 cull = true;147 }148 const moveIsRejectable = !move.damage && (move.category !== 'Status' || !move.flags.heal) && (149 move.category === 'Status' ||150 !types.has(move.type) ||151 move.selfSwitch ||152 move.basePower && move.basePower < 40 && !move.multihit153 );154 // Pokemon should have moves that benefit their Type, as well as moves required by its forme155 if (moveIsRejectable && !cull && !isSetup && counter.get('physicalsetup') + counter.get('specialsetup') < 2 && (156 !counter.setupType || counter.setupType === 'Mixed' ||157 (move.category !== counter.setupType && move.category !== 'Status') ||158 counter.get(counter.setupType) + counter.get('Status') > 3159 )) {160 if (161 (counter.damagingMoves.size === 0 || !counter.get('stab')) &&162 (counter.get('physicalpool') || counter.get('specialpool'))163 ) {164 cull = true;165 } else {166 for (const type of types) {167 if (this.moveEnforcementCheckers[type]?.(movePool, moves, new Set(), types, counter, species, teamDetails)) cull = true;168 }169 }170 }171 // Remove rejected moves from the move list172 if (cull && movePool.length) {173 moves.delete(moveid);174 break;175 }176 }177 } while (moves.size < this.maxMoveCount && movePool.length);178 const ivs = {hp: 31, atk: 31, def: 31, spa: 31, spd: 31, spe: 31};179 // Minimize confusion damage180 if (!counter.get('Physical') && !moves.has('transform')) ivs.atk = 0;181 const requiredItem = species.requiredItem || (species.requiredItems ? this.sample(species.requiredItems) : null);182 return {183 name: species.baseSpecies,184 species: forme,185 level: this.adjustLevel || 100,186 gender: species.gender,187 happiness: 70,188 shiny: this.randomChance(1, 1024),189 item: (requiredItem || ''),190 ability: 'No Ability',191 evs: {hp: 20, atk: 20, def: 20, spa: 20, spd: 20, spe: 20},192 moves: Array.from(moves),193 ivs,194 };195 }196 randomTeam() {197 this.enforceNoDirectCustomBanlistChanges();198 const pokemon: RandomTeamsTypes.RandomSet[] = [];199 const pokemonPool: string[] = [];200 for (const id in this.dex.data.FormatsData) {201 const species = this.dex.species.get(id);202 if (203 species.num < 1 ||204 (species.num > 151 && ![808, 809].includes(species.num)) ||205 species.gen > 7 ||206 species.nfe ||207 !species.randomBattleMoves?.length ||208 (this.forceMonotype && !species.types.includes(this.forceMonotype))209 ) {210 continue;211 }212 pokemonPool.push(id);213 }214 const typeCount: {[k: string]: number} = {};215 const typeComboCount: {[k: string]: number} = {};216 const baseFormes: {[k: string]: number} = {};217 const teamDetails: RandomTeamsTypes.TeamDetails = {};218 while (pokemonPool.length && pokemon.length < this.maxTeamSize) {219 const species = this.dex.species.get(this.sampleNoReplace(pokemonPool));220 if (!species.exists) continue;221 // Limit to one of each species (Species Clause)222 if (baseFormes[species.baseSpecies]) continue;223 const types = species.types;224 // Once we have 2 Pokémon of a given type we reject more Pokémon of that type 80% of the time225 let skip = false;226 for (const type of species.types) {227 if (typeCount[type] > 1 && this.randomChance(4, 5)) {228 skip = true;229 break;230 }231 }232 if (skip) continue;233 // Limit 1 of any type combination234 const typeCombo = types.slice().sort().join();235 if (!this.forceMonotype && typeComboCount[typeCombo] >= 1) continue;236 // Okay, the set passes, add it to our team237 const set = this.randomSet(species, teamDetails);238 pokemon.push(set);239 // Now that our Pokemon has passed all checks, we can increment our counters240 baseFormes[species.baseSpecies] = 1;241 // Increment type counters242 for (const type of types) {243 if (type in typeCount) {244 typeCount[type]++;245 } else {246 typeCount[type] = 1;247 }248 }249 if (typeCombo in typeComboCount) {250 typeComboCount[typeCombo]++;251 } else {252 typeComboCount[typeCombo] = 1;253 }254 // Team details255 if (set.moves.includes('stealthrock')) teamDetails.stealthRock = 1;256 if (set.moves.includes('rapidspin')) teamDetails.rapidSpin = 1;257 }258 return pokemon;259 }260}...

Full Screen

Full Screen

database.py

Source:database.py Github

copy

Full Screen

1import MySQLdb as sql2import os3import sys4import re5from tqdm import tqdm6import csv7def showing_percentage(counter_percentage, counter_perc_print):8 9 if counter_percentage >= 5.00 and counter_perc_print == 0:10 counter_perc_print = counter_perc_print + 111 print '5%'12 if counter_percentage >= 10.00 and counter_perc_print == 1:13 counter_perc_print = counter_perc_print + 114 print '10%'15 if counter_percentage >= 15.00 and counter_perc_print == 2:16 counter_perc_print = counter_perc_print + 117 print '15%'18 if counter_percentage >= 20.00 and counter_perc_print == 3:19 counter_perc_print = counter_perc_print + 120 print '20%'21 if counter_percentage >= 25.00 and counter_perc_print == 4:22 counter_perc_print = counter_perc_print + 123 print '25%'24 if counter_percentage >= 30.00 and counter_perc_print == 5:25 counter_perc_print = counter_perc_print + 126 print '30%'27 if counter_percentage >= 35.00 and counter_perc_print == 6:28 counter_perc_print = counter_perc_print + 129 print '35%'30 if counter_percentage >= 40.00 and counter_perc_print == 7:31 counter_perc_print = counter_perc_print + 132 print '40%'33 if counter_percentage >= 45.00 and counter_perc_print == 8:34 counter_perc_print = counter_perc_print + 135 print '45%'36 if counter_percentage >= 50.00 and counter_perc_print == 9:37 counter_perc_print = counter_perc_print + 138 print '50%'39 if counter_percentage >= 55.00 and counter_perc_print == 10:40 counter_perc_print = counter_perc_print + 141 print '55%'42 if counter_percentage >= 60.00 and counter_perc_print == 11:43 counter_perc_print = counter_perc_print + 144 print '60%'45 if counter_percentage >= 65.00 and counter_perc_print == 12:46 counter_perc_print = counter_perc_print + 147 print '65%'48 if counter_percentage >= 70.00 and counter_perc_print == 13:49 counter_perc_print = counter_perc_print + 150 print '70%'51 if counter_percentage >= 75.00 and counter_perc_print == 14:52 counter_perc_print = counter_perc_print + 153 print '75%'54 if counter_percentage >= 80.00 and counter_perc_print == 15:55 counter_perc_print = counter_perc_print + 156 print '80%'57 if counter_percentage >= 85.00 and counter_perc_print == 16:58 counter_perc_print = counter_perc_print + 159 print '85%'60 if counter_percentage >= 90.00 and counter_perc_print == 17:61 counter_perc_print = counter_perc_print + 162 print '90%'63 if counter_percentage >= 95.00 and counter_perc_print == 18:64 counter_perc_print = counter_perc_print + 165 print '95%'66 return counter_perc_print67 68def connect_db(db_name):69 """70 Connects to db db_name71 Args:72 db_name: path to the db to connect to73 Returns:74 connection: A connection to db_name75 """76 # Connect to the database77 # if not os.path.isfile(db_name):78 # print("Database '" + str(db_name) + "' does not exist. Please create to continue")79 # print("Exiting...")80 # sys.exit()81 # print("Connecting to database...")82 return sql.connect(host="localhost", user="root", db=db_name)83def model_change_name(list_model):84 """85 This format the name of the models to be found in the database86 """87 list_correct_model_names=[]88 for model_name in list_model:89 list_correct_model_names.append("tf-"+model_name)90 return list_correct_model_names91def searching_top_5(db_name):92 """93 Prints the top-5 elements of each database94 """95 connection = connect_db(db_name)96 cursor = connection.cursor()97 #cmd = "SELECT * FROM exec_data as E Limit 5"98 #cursor.execute(cmd)99 #result = cursor.fetchall()100 #col_names = [i[0] for i in cursor.description]101 #print(col_names)102 for model in list_model:103 output = open(model+'-top_5_complete.csv', 'w')104 headers = 'filename,label,pred_1,pred_2,pred_3,pred_4,pred_5,predictedOnTop,performance\n'105 output.write(headers)106 row_count = 0107 print(model)108 with open(DATA_FILE, 'rb') as csvfile:109 lines = [line.decode('utf-8-sig') for line in csvfile]110 for row in tqdm(csv.reader(lines), total=len(lines)):111 # Remove the headers of csv file112 if row_count is 0:113 row_count = 1114 continue115 cmd = "SELECT E.pred_1, E.pred_2, E.pred_3, E.pred_4, E.pred_5, E.performance FROM exec_data as E, images as I WHERE E.model_name='" + str(model) + "' AND I.filename='" + str(row[0]) +"' AND E.img_num=I.img_num"116 cursor.execute(cmd)117 result = cursor.fetchall()118 for pred_1, pred_2, pred_3, pred_4, pred_5, performance in result:119 predicted_1 = re.sub('[()\',!@#$]', '', str(pred_1))120 predicted_2 = re.sub('[()\',!@#$]', '', str(pred_2))121 predicted_3 = re.sub('[()\',!@#$]', '', str(pred_3))122 predicted_4 = re.sub('[()\',!@#$]', '', str(pred_4))123 predicted_5 = re.sub('[()\',!@#$]', '', str(pred_5))124 if pred_1 == row[1]:125 which_top = 1126 #predictedByOtherModel = re.sub('[()\',!@#$]', '', str(pred_1))127 elif pred_2 == row[1]:128 which_top = 2129 #predictedByOtherModel = re.sub('[()\',!@#$]', '', str(pred_2))130 elif pred_3 == row[1]:131 which_top = 3132 #predictedByOtherModel = re.sub('[()\',!@#$]', '', str(pred_3))133 elif pred_4 == row[1]:134 which_top = 4135 #predictedByOtherModel = re.sub('[()\',!@#$]', '', str(pred_4))136 elif pred_5 == row[1]:137 which_top = 5138 #predictedByOtherModel = re.sub('[()\',!@#$]', '', str(pred_5))139 else:140 # In case of 0 means that it fails in top-5141 which_top = 0142 #predictedByOtherModel = re.sub('[()\',!@#$]', '', str(pred_1))143 headers = 'filename,label,pred_1,pred_2,pred_3,pred_4,pred_5,predictedOnTop,performance\n'144 output.write(str(row[0]) + ',' + str(row[1]) + ',' + str(predicted_1) + ',' + str(predicted_2) + ',' + str(predicted_3) + ',' + str(predicted_4) + ',' + str(predicted_5) + ','+ str(which_top) + ',' + str(performance) + '\n')145 #[print("RESULT:",x) for x in result]146 output.close()147 148def determine_best_top_n_model(db_name, img_num, list_model, n):149 """150 Return the name of the model which is deemed best for img_num151 Args:152 db_name (string): path to the db to connect to153 img_num (int): number of the image154 n (int): 1 or 5 - can only use these values155 Returns:156 string: Name of the best model for img_num, or failed if failure157 """158 if n not in [1, 5]:159 print(str(n) + "is not a valid number, must be 1 or 5")160 print("Exiting...")161 sys.exit()162 163 connection = connect_db(db_name)164 cursor = connection.cursor()165 query = "SELECT model_name, top_" + str(n)166 query += ", performance FROM exec_data WHERE img_num=(%s)"167 potential = list()168 169 cursor.execute(query, (img_num,))170 for row in cursor.fetchall():171 model_name, top_n, performance = row172 173 if model_name in list_model and top_n == 1:174 potential.append((model_name, performance))175 176 if potential == list():177 return 'failed'178 return min(potential, key=lambda x: x[1])[0]179def get_img_num_database(db_name, img_filename):180 #print("Connecting to database...")181 connection = connect_db(db_name)182 cursor = connection.cursor()183 184 cmd = 'SELECT img_num, filename FROM images WHERE filename=\''+str(img_filename)+'\''185 cursor.execute(cmd)186 result = cursor.fetchall()187 for img_num, filename in result:188 return img_num, filename189 190def get_best_models(db_name, list_images, list_model):191 """192 Return the data to be show in a plot193 Args:194 db_name (string): path to the db to connect to195 """196 #if not os.path.isfile(db_name):197 # print("Database2 '" + str(db_name) + "' does not exist. Please create to continue")198 # print("Exiting...")199 # sys.exit()200 if len(list_model) == 0:201 print("No models were selected")202 return [], []203 204 if len(list_images) == 0:205 print("No images were selected")206 return [], []207 208 #print("Connecting to database...")209 connection = connect_db(db_name)210 cursor = connection.cursor()211 tmp_results=[]212 213 list_correct_model_names=model_change_name(list_model)214 215 list_correct_model_names.append("failed")216 217 percentage = 100.0/len(list_images)218 counter_percentage = 0.0219 counter_perc_print = 0220 221 for img_filename in list_images:222 cmd = 'SELECT img_num, filename FROM images WHERE filename=\''+str(img_filename)+'\''223 cursor.execute(cmd)224 result = cursor.fetchall()225 226 for img_num, filename in result:227 best_top_1_model = determine_best_top_n_model(db_name, img_num, list_correct_model_names, 1)228 #print(img_num, filename, best_top_1_model)229 tmp_results.append((filename, best_top_1_model))230 231 counter_percentage = counter_percentage + percentage232 counter_perc_print = showing_percentage(counter_percentage, counter_perc_print)233 234 # The last one is failed235 results_to_plot = [0]*len(list_correct_model_names)236 237 for counter, model in enumerate(list_correct_model_names):238 for filename, best_top_1_model in tmp_results:239 if best_top_1_model == model:240 results_to_plot[counter] = results_to_plot[counter] + 1241 242 return list_correct_model_names, results_to_plot243 244 245 ...

Full Screen

Full Screen

cmanager_win32.py

Source:cmanager_win32.py Github

copy

Full Screen

1# This Source Code Form is subject to the terms of the Mozilla Public2# License, v. 2.0. If a copy of the MPL was not distributed with this3# file, You can obtain one at http://mozilla.org/MPL/2.0/.4from cmanager import CounterManager5from ctypes import windll6from ctypes.wintypes import DWORD, HANDLE, LPSTR, LPCSTR, LPCWSTR, Structure, \7 pointer, LONG8from ctypes import byref, create_string_buffer, memmove, Union, c_double, \9 c_longlong10import struct11from utils import TalosError12pdh = windll.pdh13_LONGLONG = c_longlong14class _PDH_COUNTER_PATH_ELEMENTS_A(Structure):15 _fields_ = [("szMachineName", LPSTR),16 ("szObjectName", LPSTR),17 ("szInstanceName", LPSTR),18 ("szParentInstance", LPSTR),19 ("dwInstanceIndex", DWORD),20 ("szCounterName", LPSTR)]21_PDH_MORE_DATA = -2147481646 # the need more space error22def _getExpandedCounterPaths(processName, counterName):23 '''24 Get list of expanded counter paths given a counter name. Returns a25 list of strings or None, if no counter paths can be created26 '''27 pcchPathListLength = DWORD(0)28 szWildCardPath = LPSTR('\\process(%s)\\%s' % (processName, counterName))29 if pdh.PdhExpandCounterPathA(30 szWildCardPath,31 LPSTR(None),32 pointer(pcchPathListLength)33 ) != _PDH_MORE_DATA:34 return []35 pathListLength = pcchPathListLength.value36 szExpandedPathList = LPCSTR('\0' * pathListLength)37 if pdh.PdhExpandCounterPathA(szWildCardPath, szExpandedPathList,38 pointer(pcchPathListLength)) != 0:39 return []40 buffer = create_string_buffer(pcchPathListLength.value)41 memmove(buffer, szExpandedPathList, pcchPathListLength.value)42 paths = []43 i = 044 path = ''45 for j in range(0, pcchPathListLength.value):46 c = struct.unpack_from('c', buffer, offset=j)[0]47 if c == '\0':48 if j == i:49 # double null: we're done50 break51 paths.append(path)52 path = ''53 i = j + 154 else:55 path += c56 return paths57class _PDH_Counter_Union(Union):58 _fields_ = [('longValue', LONG),59 ('doubleValue', c_double),60 ('largeValue', _LONGLONG),61 ('AnsiStringValue', LPCSTR),62 ('WideStringValue', LPCWSTR)]63class _PDH_FMT_COUNTERVALUE(Structure):64 _fields_ = [('CStatus', DWORD),65 ('union', _PDH_Counter_Union)]66_PDH_FMT_LONG = 0x0000010067class WinCounterManager(CounterManager):68 def __init__(self, process_name, process, counters,69 childProcess="plugin-container"):70 CounterManager.__init__(self)71 self.childProcess = childProcess72 self.registeredCounters = {}73 self.registerCounters(counters)74 # PDH might need to be "refreshed" if it has been queried while the75 # browser is closed76 pdh.PdhEnumObjectsA(None, None, 0, 1, 0, True)77 for counter in self.registeredCounters:78 try:79 # Add the counter path for the default process.80 self._addCounter(process_name, 'process', counter)81 except TalosError:82 # Assume that this is a memory counter for the system,83 # not a process counter84 # If we got an error that has nothing to do with that,85 # the exception will almost certainly be re-raised86 self._addCounter(process_name, 'Memory', counter)87 self._updateCounterPathsForChildProcesses(counter)88 def _addCounter(self, processName, counterType, counterName):89 pCounterPathElements = _PDH_COUNTER_PATH_ELEMENTS_A(90 LPSTR(None),91 LPSTR(counterType),92 LPSTR(processName),93 LPSTR(None),94 DWORD(-1),95 LPSTR(counterName)96 )97 pcchbufferSize = DWORD(0)98 # First run we just try to get the buffer size so we can allocate a99 # string big enough to fill it100 if pdh.PdhMakeCounterPathA(pointer(pCounterPathElements),101 LPCSTR(0), pointer(pcchbufferSize),102 DWORD(0)) != _PDH_MORE_DATA:103 raise TalosError(104 "Could not create counter path for counter %s for %s"105 % (counterName, processName)106 )107 szFullPathBuffer = LPCSTR('\0'*pcchbufferSize.value)108 # Then we run to get the actual value109 if pdh.PdhMakeCounterPathA(pointer(pCounterPathElements),110 szFullPathBuffer, pointer(pcchbufferSize),111 DWORD(0)) != 0:112 raise TalosError(113 "Could not create counter path for counter %s for %s"114 % (counterName, processName)115 )116 path = szFullPathBuffer.value117 hq = HANDLE()118 if pdh.PdhOpenQuery(None, None, byref(hq)) != 0:119 raise TalosError("Could not open win32 counter query")120 hc = HANDLE()121 if pdh.PdhAddCounterA(hq, path, 0, byref(hc)) != 0:122 raise TalosError("Could not add win32 counter %s" % path)123 self.registeredCounters[counterName] = [hq, [(hc, path)]]124 def registerCounters(self, counters):125 # self.registeredCounters[counter][0] is a counter query handle126 # self.registeredCounters[counter][1] is a list of tuples, the first127 # member of which is a counter handle, the second a counter path128 for counter in counters:129 # Main_RSS is collected inside of pageloader130 if counter.strip() == 'Main_RSS':131 continue132 # mainthread_io is collected from the browser via environment133 # variables134 if counter.strip() == 'mainthread_io':135 continue136 self.registeredCounters[counter] = []137 def _updateCounterPathsForChildProcesses(self, counter):138 # Create a counter path for each instance of the child process that139 # is running. If any of these paths are not in our counter list,140 # add them to our counter query and append them to the counter list,141 # so that we'll begin tracking their statistics. We don't need to142 # worry about removing invalid paths from the list, as143 # getCounterValue() will generate a value of 0 for those.144 hq = self.registeredCounters[counter][0]145 oldCounterListLength = len(self.registeredCounters[counter][1])146 pdh.PdhEnumObjectsA(None, None, 0, 1, 0, True)147 expandedPaths = _getExpandedCounterPaths(self.childProcess, counter)148 if not expandedPaths:149 return150 for expandedPath in expandedPaths:151 alreadyInCounterList = False152 for singleCounter in self.registeredCounters[counter][1]:153 if expandedPath == singleCounter[1]:154 alreadyInCounterList = True155 if not alreadyInCounterList:156 try:157 newhc = HANDLE()158 if pdh.PdhAddCounterA(hq, expandedPath, 0,159 byref(newhc)) != 0:160 raise TalosError(161 "Could not add expanded win32 counter %s"162 % expandedPath163 )164 self.registeredCounters[counter][1].append((newhc,165 expandedPath))166 except:167 continue168 if oldCounterListLength != len(self.registeredCounters[counter][1]):169 pdh.PdhCollectQueryData(hq)170 def getCounterValue(self, counter):171 # Update counter paths, to catch any new child processes that might172 # have been launched since last call. Then iterate through all173 # counter paths for this counter, and return a combined value.174 if counter not in self.registeredCounters:175 return None176 if self.registeredCounters[counter] == []:177 return None178 self._updateCounterPathsForChildProcesses(counter)179 hq = self.registeredCounters[counter][0]180 # we'll just ignore the return value here, in case no counters181 # are valid anymore182 pdh.PdhCollectQueryData(hq)183 aggregateValue = 0184 for singleCounter in self.registeredCounters[counter][1]:185 hc = singleCounter[0]186 dwType = DWORD(0)187 value = _PDH_FMT_COUNTERVALUE()188 # if we can't get a value, just assume a value of 0189 if pdh.PdhGetFormattedCounterValue(hc, _PDH_FMT_LONG,190 byref(dwType),191 byref(value)) == 0:192 aggregateValue += value.union.longValue...

Full Screen

Full Screen

test_clock.py

Source:test_clock.py Github

copy

Full Screen

...9 counter = 010 def __call__(self, *args, **kwargs):11 self.counter += 112@pytest.fixture()13def clock_counter():14 yield ClockCounter()15def test_schedule_once(kivy_clock, clock_counter):16 kivy_clock.schedule_once(clock_counter)17 kivy_clock.tick()18 assert clock_counter.counter == 119def test_schedule_once_twice(kivy_clock, clock_counter):20 kivy_clock.schedule_once(clock_counter)21 kivy_clock.schedule_once(clock_counter)22 kivy_clock.tick()23 assert clock_counter.counter == 224def test_schedule_once_draw_after(kivy_clock, clock_counter):25 kivy_clock.schedule_once(clock_counter, 0)26 kivy_clock.tick_draw()27 assert clock_counter.counter == 028 kivy_clock.tick()29 assert clock_counter.counter == 130def test_schedule_once_draw_before(kivy_clock, clock_counter):31 kivy_clock.schedule_once(clock_counter, -1)32 kivy_clock.tick_draw()33 assert clock_counter.counter == 134 kivy_clock.tick()35 assert clock_counter.counter == 136def test_unschedule(kivy_clock, clock_counter):37 kivy_clock.schedule_once(clock_counter)38 kivy_clock.unschedule(clock_counter)39 kivy_clock.tick()40 assert clock_counter.counter == 041def test_unschedule_event(kivy_clock, clock_counter):42 ev = kivy_clock.schedule_once(clock_counter)43 kivy_clock.unschedule(ev)44 kivy_clock.tick()45 assert clock_counter.counter == 046def test_unschedule_after_tick(kivy_clock, clock_counter):47 kivy_clock.schedule_once(clock_counter, 5.)48 kivy_clock.tick()49 kivy_clock.unschedule(clock_counter)50 kivy_clock.tick()51 assert clock_counter.counter == 052def test_unschedule_draw(kivy_clock, clock_counter):53 kivy_clock.schedule_once(clock_counter, 0)54 kivy_clock.tick_draw()55 assert clock_counter.counter == 056 kivy_clock.unschedule(clock_counter)57 kivy_clock.tick()58 assert clock_counter.counter == 059def test_trigger_create(kivy_clock, clock_counter):60 trigger = kivy_clock.create_trigger(clock_counter, 0)61 trigger()62 assert clock_counter.counter == 063 kivy_clock.tick()64 assert clock_counter.counter == 165def test_trigger_cancel(kivy_clock, clock_counter):66 trigger = kivy_clock.create_trigger(clock_counter, 5.)67 trigger()68 trigger.cancel()69 kivy_clock.tick()70 assert clock_counter.counter == 071def test_trigger_interval(kivy_clock, clock_counter):72 trigger = kivy_clock.create_trigger(clock_counter, 0, interval=True)73 trigger()74 kivy_clock.tick()75 assert clock_counter.counter == 176 kivy_clock.tick()77 assert clock_counter.counter == 278def test_trigger_decorator(kivy_clock, clock_counter):79 from kivy.clock import triggered80 @triggered()81 def triggered_callback():82 clock_counter(dt=0)83 triggered_callback()84 assert clock_counter.counter == 085 kivy_clock.tick()86 assert clock_counter.counter == 187def test_trigger_decorator_cancel(kivy_clock, clock_counter):88 from kivy.clock import triggered89 @triggered()90 def triggered_callback():91 clock_counter(dt=0)92 triggered_callback()93 triggered_callback.cancel()94 kivy_clock.tick()95 assert clock_counter.counter == 096def test_exception_caught(kivy_clock, clock_counter):97 exception = None98 def handle_test_exception(e):99 nonlocal exception100 exception = str(e)101 # monkey patch to ignore exception102 kivy_clock.handle_exception = handle_test_exception103 def raise_exception(*args):104 raise ValueError('Stooooop')105 kivy_clock.schedule_once(raise_exception)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testify automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful