How to use counter method in fast-check-monorepo

Best JavaScript code snippet using fast-check-monorepo

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

test_caching.py

Source:test_caching.py Github

copy

Full Screen

1"""Test caching extension."""2from __future__ import with_statement3import tempfile4from _tools import *5requires_joblib = skip_on_condition(6 "not mdp.config.has_joblib",7 "This test requires the 'joblib' module.")8_counter = 09class _CounterNode(mdp.Node):10 def __init__(self):11 super(_CounterNode, self).__init__()12 def is_trainable(self):13 return False14 def _execute(self, x):15 """The execute method has the side effect of increasing16 a global counter by one."""17 global _counter18 _counter += 119 return x20@requires_joblib21def test_caching_extension():22 """Test that the caching extension is working at the global level."""23 global _counter24 _counter = 025 node = _CounterNode()26 # before decoration the global counter is incremented at every call27 k = 028 for i in range(3):29 x = mdp.numx.array([[i]], dtype='d')30 for j in range(2):31 k += 132 assert mdp.numx.all(node.execute(x) == x)33 assert _counter == k34 # reset counter35 _counter = 036 # activate the extension37 cachedir = tempfile.mkdtemp(prefix='mdp-tmp-joblib-cache.',38 dir=py.test.mdp_tempdirname)39 mdp.caching.activate_caching(cachedir=cachedir)40 assert mdp.get_active_extensions() == ['cache_execute']41 # after decoration the global counter is incremented for each new 'x'42 for i in range(3):43 x = mdp.numx.array([[i]], dtype='d')44 for _ in range(2):45 assert mdp.numx.all(node.execute(x) == x)46 assert _counter == i + 147 # after deactivation48 mdp.caching.deactivate_caching()49 assert mdp.get_active_extensions() == []50 # reset counter51 _counter = 052 k = 053 for i in range(3):54 x = mdp.numx.array([[i]], dtype='d')55 for j in range(2):56 k += 157 assert mdp.numx.all(node.execute(x) == x)58 assert _counter == k59@requires_joblib60def test_different_instances_same_content():61 global _counter62 x = mdp.numx.array([[100.]], dtype='d')63 cachedir = tempfile.mkdtemp(prefix='mdp-tmp-joblib-cache.',64 dir=py.test.mdp_tempdirname)65 mdp.caching.activate_caching(cachedir=cachedir)66 node = _CounterNode()67 _counter = 068 # add attribute to make instance unique69 node.attr = 'unique'70 # cache x71 node.execute(x)72 assert _counter == 173 # should be cached now74 node.execute(x)75 assert _counter == 176 # create new instance, make it also unique and check that77 # result is still cached78 _counter = 079 node = _CounterNode()80 node.attr = 'unique and different'81 node.execute(x)82 assert _counter == 183 mdp.caching.deactivate_caching()84@requires_joblib85def test_caching_context_manager():86 global _counter87 node = _CounterNode()88 _counter = 089 assert mdp.get_active_extensions() == []90 cachedir = tempfile.mkdtemp(prefix='mdp-tmp-joblib-cache.',91 dir=py.test.mdp_tempdirname)92 with mdp.caching.cache(cachedir=cachedir):93 assert mdp.get_active_extensions() == ['cache_execute']94 for i in range(3):95 x = mdp.numx.array([[i]], dtype='d')96 for _ in range(2):97 assert mdp.numx.all(node.execute(x) == x)98 assert _counter == i + 199 assert mdp.get_active_extensions() == []100@requires_joblib101def test_class_caching():102 """Test that we can cache individual classes."""103 cached = mdp.nodes.PCANode()104 notcached = mdp.nodes.SFANode()105 with mdp.caching.cache(cache_classes=[mdp.nodes.PCANode]):106 assert cached.is_cached()107 assert not notcached.is_cached()108@requires_joblib109def test_class_caching_functionality():110 """Test that cached classes really cache."""111 global _counter112 x = mdp.numx.array([[210]], dtype='d')113 node = _CounterNode()114 # here _CounterNode is not cached115 _counter = 0116 with mdp.caching.cache(cache_classes=[mdp.nodes.PCANode]):117 node.execute(x)118 assert _counter == 1119 node.execute(x)120 assert _counter == 2121 # here _CounterNode is cached122 _counter = 0123 with mdp.caching.cache(cache_classes=[_CounterNode]):124 node.execute(x)125 assert _counter == 1126 node.execute(x)127 assert _counter == 1128@requires_joblib129def test_instance_caching():130 """Test that we can cache individual instances."""131 cached = mdp.nodes.PCANode()132 notcached = mdp.nodes.PCANode()133 with mdp.caching.cache(cache_instances=[cached]):134 assert cached.is_cached()135 assert not notcached.is_cached()136@requires_joblib137def test_instance_caching_functionality():138 """Test that cached instances really cache."""139 global _counter140 x = mdp.numx.array([[130]], dtype='d')141 node = _CounterNode()142 othernode = _CounterNode()143 # here _CounterNode is not cached144 _counter = 0145 with mdp.caching.cache(cache_instances=[othernode]):146 node.execute(x)147 assert _counter == 1148 node.execute(x)149 assert _counter == 2150 # here _CounterNode is cached151 _counter = 0152 with mdp.caching.cache(cache_instances=[node]):153 node.execute(x)154 assert _counter == 1155 node.execute(x)156 assert _counter == 1157@requires_joblib158def test_preexecution_problem():159 """Test that automatic setting of e.g. input_dim does not stop160 the caching extension from caching on the first run."""161 global _counter162 x = mdp.numx.array([[102.]])163 node = _CounterNode()164 # here _CounterNode is cached165 _counter = 0166 with mdp.caching.cache():167 # on the first execution, input_dim and dtype are set ...168 node.execute(x)169 assert _counter == 1170 # ... yet the result is cached171 node.execute(x)172 assert _counter == 1173@requires_joblib174def test_switch_cache():175 """Test changing cache directory while extension is active."""176 global _counter177 dir1 = tempfile.mkdtemp(prefix='mdp-tmp-joblib-cache.',178 dir=py.test.mdp_tempdirname)179 dir2 = tempfile.mkdtemp(prefix='mdp-tmp-joblib-cache.',180 dir=py.test.mdp_tempdirname)181 x = mdp.numx.array([[10]], dtype='d')182 mdp.caching.activate_caching(cachedir=dir1)183 node = _CounterNode()184 _counter = 0185 node.execute(x)186 assert _counter == 1187 node.execute(x)188 assert _counter == 1189 # now change path190 mdp.caching.set_cachedir(cachedir=dir2)191 node.execute(x)192 assert _counter == 2193 node.execute(x)194 assert _counter == 2195 mdp.caching.deactivate_caching()196@requires_joblib197def test_execute_magic():198 """Test calling execute with magic while caching."""199 x = mdp.numx_rand.rand(100, 10)200 node = mdp.nodes.PCANode()201 with mdp.caching.cache():202 y = node(x)203 y2 = node(x)...

Full Screen

Full Screen

winperf.py

Source:winperf.py Github

copy

Full Screen

1# Generated by h2py from winperf.h2PERF_DATA_VERSION = 13PERF_DATA_REVISION = 14PERF_NO_INSTANCES = -15PERF_SIZE_DWORD = 0x000000006PERF_SIZE_LARGE = 0x000001007PERF_SIZE_ZERO = 0x000002008PERF_SIZE_VARIABLE_LEN = 0x000003009PERF_TYPE_NUMBER = 0x0000000010PERF_TYPE_COUNTER = 0x0000040011PERF_TYPE_TEXT = 0x0000080012PERF_TYPE_ZERO = 0x00000C0013PERF_NUMBER_HEX = 0x0000000014PERF_NUMBER_DECIMAL = 0x0001000015PERF_NUMBER_DEC_1000 = 0x0002000016PERF_COUNTER_VALUE = 0x0000000017PERF_COUNTER_RATE = 0x0001000018PERF_COUNTER_FRACTION = 0x0002000019PERF_COUNTER_BASE = 0x0003000020PERF_COUNTER_ELAPSED = 0x0004000021PERF_COUNTER_QUEUELEN = 0x0005000022PERF_COUNTER_HISTOGRAM = 0x0006000023PERF_TEXT_UNICODE = 0x0000000024PERF_TEXT_ASCII = 0x0001000025PERF_TIMER_TICK = 0x0000000026PERF_TIMER_100NS = 0x0010000027PERF_OBJECT_TIMER = 0x0020000028PERF_DELTA_COUNTER = 0x0040000029PERF_DELTA_BASE = 0x0080000030PERF_INVERSE_COUNTER = 0x0100000031PERF_MULTI_COUNTER = 0x0200000032PERF_DISPLAY_NO_SUFFIX = 0x0000000033PERF_DISPLAY_PER_SEC = 0x1000000034PERF_DISPLAY_PERCENT = 0x2000000035PERF_DISPLAY_SECONDS = 0x3000000036PERF_DISPLAY_NOSHOW = 0x4000000037PERF_COUNTER_COUNTER = \38 (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\39 PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_PER_SEC)40PERF_COUNTER_TIMER = \41 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\42 PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_PERCENT)43PERF_COUNTER_QUEUELEN_TYPE = \44 (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_QUEUELEN |\45 PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_NO_SUFFIX)46PERF_COUNTER_LARGE_QUEUELEN_TYPE = \47 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_QUEUELEN |\48 PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_NO_SUFFIX)49PERF_COUNTER_BULK_COUNT = \50 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\51 PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_PER_SEC)52PERF_COUNTER_TEXT = \53 (PERF_SIZE_VARIABLE_LEN | PERF_TYPE_TEXT | PERF_TEXT_UNICODE |\54 PERF_DISPLAY_NO_SUFFIX)55PERF_COUNTER_RAWCOUNT = \56 (PERF_SIZE_DWORD | PERF_TYPE_NUMBER | PERF_NUMBER_DECIMAL |\57 PERF_DISPLAY_NO_SUFFIX)58PERF_COUNTER_LARGE_RAWCOUNT = \59 (PERF_SIZE_LARGE | PERF_TYPE_NUMBER | PERF_NUMBER_DECIMAL |\60 PERF_DISPLAY_NO_SUFFIX)61PERF_COUNTER_RAWCOUNT_HEX = \62 (PERF_SIZE_DWORD | PERF_TYPE_NUMBER | PERF_NUMBER_HEX |\63 PERF_DISPLAY_NO_SUFFIX)64PERF_COUNTER_LARGE_RAWCOUNT_HEX = \65 (PERF_SIZE_LARGE | PERF_TYPE_NUMBER | PERF_NUMBER_HEX |\66 PERF_DISPLAY_NO_SUFFIX)67PERF_SAMPLE_FRACTION = \68 (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_FRACTION |\69 PERF_DELTA_COUNTER | PERF_DELTA_BASE | PERF_DISPLAY_PERCENT)70PERF_SAMPLE_COUNTER = \71 (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\72 PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_NO_SUFFIX)73PERF_COUNTER_NODATA = \74 (PERF_SIZE_ZERO | PERF_DISPLAY_NOSHOW)75PERF_COUNTER_TIMER_INV = \76 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\77 PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_INVERSE_COUNTER | \78 PERF_DISPLAY_PERCENT)79PERF_SAMPLE_BASE = \80 (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_BASE |\81 PERF_DISPLAY_NOSHOW |\82 0x00000001)83PERF_AVERAGE_TIMER = \84 (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_FRACTION |\85 PERF_DISPLAY_SECONDS)86PERF_AVERAGE_BASE = \87 (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_BASE |\88 PERF_DISPLAY_NOSHOW |\89 0x00000002)90PERF_AVERAGE_BULK = \91 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_FRACTION |\92 PERF_DISPLAY_NOSHOW)93PERF_100NSEC_TIMER = \94 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\95 PERF_TIMER_100NS | PERF_DELTA_COUNTER | PERF_DISPLAY_PERCENT)96PERF_100NSEC_TIMER_INV = \97 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\98 PERF_TIMER_100NS | PERF_DELTA_COUNTER | PERF_INVERSE_COUNTER |\99 PERF_DISPLAY_PERCENT)100PERF_COUNTER_MULTI_TIMER = \101 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\102 PERF_DELTA_COUNTER | PERF_TIMER_TICK | PERF_MULTI_COUNTER |\103 PERF_DISPLAY_PERCENT)104PERF_COUNTER_MULTI_TIMER_INV = \105 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\106 PERF_DELTA_COUNTER | PERF_MULTI_COUNTER | PERF_TIMER_TICK |\107 PERF_INVERSE_COUNTER | PERF_DISPLAY_PERCENT)108PERF_COUNTER_MULTI_BASE = \109 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_BASE |\110 PERF_MULTI_COUNTER | PERF_DISPLAY_NOSHOW)111PERF_100NSEC_MULTI_TIMER = \112 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_DELTA_COUNTER |\113 PERF_COUNTER_RATE | PERF_TIMER_100NS | PERF_MULTI_COUNTER |\114 PERF_DISPLAY_PERCENT)115PERF_100NSEC_MULTI_TIMER_INV = \116 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_DELTA_COUNTER |\117 PERF_COUNTER_RATE | PERF_TIMER_100NS | PERF_MULTI_COUNTER |\118 PERF_INVERSE_COUNTER | PERF_DISPLAY_PERCENT)119PERF_RAW_FRACTION = \120 (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_FRACTION |\121 PERF_DISPLAY_PERCENT)122PERF_RAW_BASE = \123 (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_BASE |\124 PERF_DISPLAY_NOSHOW |\125 0x00000003)126PERF_ELAPSED_TIME = \127 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_ELAPSED |\128 PERF_OBJECT_TIMER | PERF_DISPLAY_SECONDS)129PERF_COUNTER_HISTOGRAM_TYPE = -2147483648 # 0x80000000130PERF_COUNTER_DELTA = \131 (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_VALUE |\132 PERF_DELTA_COUNTER | PERF_DISPLAY_NO_SUFFIX)133PERF_COUNTER_LARGE_DELTA = \134 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_VALUE |\135 PERF_DELTA_COUNTER | PERF_DISPLAY_NO_SUFFIX)136PERF_DETAIL_NOVICE = 100137PERF_DETAIL_ADVANCED = 200138PERF_DETAIL_EXPERT = 300139PERF_DETAIL_WIZARD = 400...

Full Screen

Full Screen

characterCounter.js

Source:characterCounter.js Github

copy

Full Screen

1;(function($) {2 'use strict'3 let _defaults = {}4 /**5 * @class6 *7 */8 class CharacterCounter extends Component {9 /**10 * Construct CharacterCounter instance11 * @constructor12 * @param {Element} el13 * @param {Object} options14 */15 constructor(el, options) {16 super(CharacterCounter, el, options)17 this.el.M_CharacterCounter = this18 /**19 * Options for the character counter20 */21 this.options = $.extend({}, CharacterCounter.defaults, options)22 this.isInvalid = false23 this.isValidLength = false24 this._setupCounter()25 this._setupEventHandlers()26 }27 static get defaults() {28 return _defaults29 }30 static init(els, options) {31 return super.init(this, els, options)32 }33 /**34 * Get Instance35 */36 static getInstance(el) {37 let domElem = !!el.jquery ? el[0] : el38 return domElem.M_CharacterCounter39 }40 /**41 * Teardown component42 */43 destroy() {44 this._removeEventHandlers()45 this.el.CharacterCounter = undefined46 this._removeCounter()47 }48 /**49 * Setup Event Handlers50 */51 _setupEventHandlers() {52 this._handleUpdateCounterBound = this.updateCounter.bind(this)53 this.el.addEventListener('focus', this._handleUpdateCounterBound, true)54 this.el.addEventListener('input', this._handleUpdateCounterBound, true)55 }56 /**57 * Remove Event Handlers58 */59 _removeEventHandlers() {60 this.el.removeEventListener('focus', this._handleUpdateCounterBound, true)61 this.el.removeEventListener('input', this._handleUpdateCounterBound, true)62 }63 /**64 * Setup counter element65 */66 _setupCounter() {67 this.counterEl = document.createElement('span')68 $(this.counterEl)69 .addClass('character-counter')70 .css({71 float: 'right',72 'font-size': '12px',73 height: 1,74 })75 this.$el.parent().append(this.counterEl)76 }77 /**78 * Remove counter element79 */80 _removeCounter() {81 $(this.counterEl).remove()82 }83 /**84 * Update counter85 */86 updateCounter() {87 let maxLength = +this.$el.attr('data-length'),88 actualLength = this.el.value.length89 this.isValidLength = actualLength <= maxLength90 let counterString = actualLength91 if (maxLength) {92 counterString += '/' + maxLength93 this._validateInput()94 }95 $(this.counterEl).html(counterString)96 }97 /**98 * Add validation classes99 */100 _validateInput() {101 if (this.isValidLength && this.isInvalid) {102 this.isInvalid = false103 this.$el.removeClass('invalid')104 } else if (!this.isValidLength && !this.isInvalid) {105 this.isInvalid = true106 this.$el.removeClass('valid')107 this.$el.addClass('invalid')108 }109 }110 }111 M.CharacterCounter = CharacterCounter112 if (M.jQueryLoaded) {113 M.initializeJqueryWrapper(CharacterCounter, 'characterCounter', 'M_CharacterCounter')114 }...

Full Screen

Full Screen

StatBox.js

Source:StatBox.js Github

copy

Full Screen

1class StatBox {2 constructor(domId) {3 this.domBox = document.createElement("div")4 this.domBox.setAttribute("id", `${domId}-stats`)5 this.domBox.classList.add("stat-box")6 this.rwCounterContainer = document.createElement("div")7 this.rCounterContainer = document.createElement("div")8 this.wCounterContainer = document.createElement("div")9 this.rwCounterContainer.classList.add("counter-container")10 this.rCounterContainer.classList.add("counter-container")11 this.wCounterContainer.classList.add("counter-container")12 this.rwCounterText = document.createElement("h1")13 this.rCounterText = document.createElement("h1")14 this.wCounterText = document.createElement("h1")15 this.rwCounterText.classList.add("stat-h1s-sloppy-dop")16 this.rCounterText.classList.add("stat-h1s-sloppy-dop")17 this.wCounterText.classList.add("stat-h1s-sloppy-dop")18 this.rwCounterText.innerHTML = "Read/Write"19 this.rCounterText.innerHTML = "Read"20 this.wCounterText.innerHTML = "Write"21 this.rwCounter = document.createElement("h2")22 this.rCounter = document.createElement("h2")23 this.wCounter = document.createElement("h2")24 this.rwCounter.id = `${domId}-read-write`25 this.rCounter.id = `${domId}-read`26 this.wCounter.id = `${domId}-write`27 this.rwCounter.innerHTML = 028 this.rCounter.innerHTML = 029 this.wCounter.innerHTML = 030 this.rwCounterContainer.appendChild(this.rwCounter)31 this.rCounterContainer.appendChild(this.rCounter)32 this.wCounterContainer.appendChild(this.wCounter)33 this.rwCounterContainer.appendChild(this.rwCounterText)34 this.rCounterContainer.appendChild(this.rCounterText)35 this.wCounterContainer.appendChild(this.wCounterText)36 this.domBox.appendChild(this.rwCounterContainer)37 this.domBox.appendChild(this.rCounterContainer)38 this.domBox.appendChild(this.wCounterContainer)39 document.getElementById(domId).appendChild(this.domBox)40 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { counter } = require("fast-check-monorepo");2console.log(counter(3));3const { counter } = require("fast-check-monorepo");4console.log(counter(4));5const { counter } = require("fast-check-monorepo");6console.log(counter(5));7const { counter } = require("fast-check-monorepo");8console.log(counter(6));9const { counter } = require("fast-check-monorepo");10console.log(counter(7));11const { counter } = require("fast-check-monorepo");12console.log(counter(8));13const { counter } = require("fast-check-monorepo");14console.log(counter(9));15const { counter } = require("fast-check-monorepo");16console.log(counter(10));17const { counter } = require("fast-check-monorepo");18console.log(counter(11));19const { counter } = require("fast-check-monorepo");20console.log(counter(12));21const { counter } = require("fast-check-monorepo");22console.log(counter(13));23const { counter } = require("fast-check-monorepo");24console.log(counter(14));25const { counter } = require("fast-check-monorepo");26console.log(counter(15));

Full Screen

Using AI Code Generation

copy

Full Screen

1const { counter } = require('fast-check-monorepo');2console.log(counter(2));3const { counter } = require('fast-check-monorepo');4console.log(counter(3));5test1.js 100% (1/1)6test2.js 100% (1/1)7test3.js 100% (1/1)8test4.js 100% (1/1)

Full Screen

Using AI Code Generation

copy

Full Screen

1const { counter } = require('fast-check-monorepo');2counter(10);3const { counter } = require('fast-check-monorepo');4counter(10);5const { counter } = require('fast-check-monorepo');6counter(10);7const { counter } = require('fast-check-monorepo');8counter(10);9const { counter } = require('fast-check-monorepo');10counter(10);11const { counter } = require('fast-check-monorepo');12counter(10);13const { counter } = require('fast-check-monorepo');14counter(10);15const { counter } = require('fast-check-monorepo');16counter(10);17const { counter } = require('fast-check-monorepo');18counter(10);19const { counter } = require('fast-check-monorepo');20counter(10);21const { counter } = require('fast-check-monorepo');22counter(10);23const { counter } = require('fast-check-monorepo');24counter(10);25const { counter } = require('fast-check-monorepo');26counter(10);27const { counter } = require('fast-check-monorepo');28counter(10);

Full Screen

Using AI Code Generation

copy

Full Screen

1const counter = require('fast-check-monorepo').counter;2const counter2 = require('fast-check').counter;3const counter3 = require('fast-check').counter;4const counter4 = require('fast-check').counter;5const counter5 = require('fast-check').counter;6const counter6 = require('fast-check').counter;7const counter7 = require('fast-check').counter;8const counter8 = require('fast-check').counter;9const counter9 = require('fast-check').counter;10const counter10 = require('fast-check').counter;11const counter11 = require('fast-check').counter;12const counter12 = require('fast-check').counter;13const counter13 = require('fast-check').counter;14const counter14 = require('fast-check').counter;15const counter15 = require('fast-check').counter;16const counter16 = require('fast-check').counter;17const counter17 = require('fast-check').counter;18const counter18 = require('fast-check').counter;19const counter19 = require('fast-check').counter;20const counter20 = require('fast-check').counter;21const counter21 = require('fast-check').counter;22const counter22 = require('fast-check').counter;23const counter23 = require('fast-check').counter;24const counter24 = require('fast-check').counter;

Full Screen

Using AI Code Generation

copy

Full Screen

1const counter = require('fast-check-monorepo/counter');2const assert = require('assert');3assert.equal(counter(1), 2);4const counter = require('fast-check-monorepo/counter');5const assert = require('assert');6assert.equal(counter(1), 2);7const counter = require('fast-check-monorepo/counter');8const assert = require('assert');9assert.equal(counter(1), 2);10const counter = require('fast-check-monorepo/counter');11const assert = require('assert');12assert.equal(counter(1), 2);13const counter = require('fast-check-monorepo/counter');14const assert = require('assert');15assert.equal(counter(1), 2);16const counter = require('fast-check-monorepo/counter');17const assert = require('assert');18assert.equal(counter(1), 2);19const counter = require('fast-check-monorepo/counter');20const assert = require('assert');21assert.equal(counter(1), 2);22const counter = require('fast-check-monorepo/counter');23const assert = require('assert');24assert.equal(counter(1), 2);25const counter = require('fast-check-monorepo/counter');26const assert = require('assert');27assert.equal(counter(1), 2);28const counter = require('fast-check-monorepo/counter');29const assert = require('assert');30assert.equal(counter(1), 2);31const counter = require('fast-check-mon

Full Screen

Using AI Code Generation

copy

Full Screen

1import { counter } from 'fast-check-monorepo';2const res = counter(1, 2);3console.log(res);4import { counter } from 'fast-check-monorepo';5const res = counter(1, 2);6console.log(res);7import { counter } from 'fast-check-monorepo';8const res = counter(1, 2);9console.log(res);10import { counter } from 'fast-check-monorepo';11const res = counter(1, 2);12console.log(res);13import { counter } from 'fast-check-monorepo';14const res = counter(1, 2);15console.log(res);16import { counter } from 'fast-check-monorepo';17const res = counter(1, 2);18console.log(res);19import { counter } from 'fast-check-monorepo';20const res = counter(1, 2);21console.log(res);22import { counter } from 'fast-check-monorepo';23const res = counter(1, 2);24console.log(res);25import { counter } from 'fast-check-monorepo';26const res = counter(1, 2);27console.log(res);28import { counter } from 'fast-check-monorepo';29const res = counter(1, 2);30console.log(res);31import { counter } from 'fast-check-monorepo';32const res = counter(1, 2);33console.log(res);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { counter } = require('fast-check-monorepo');2console.log(counter(0));3console.log(counter(1));4console.log(counter(2));5console.log(counter(3));6console.log(counter(4));7console.log(counter(5));8console.log(counter(6));9console.log(counter(7));10console.log(counter(8));11console.log(counter(9));12console.log(counter(10));13console.log(counter(11));14console.log(counter(12));15console.log(counter(13));16console.log(counter(14));17console.log(counter(15));18console.log(counter(16));19console.log(counter(17));20console.log(counter(18));21console.log(counter(19));22console.log(counter(20));23console.log(counter(21));24console.log(counter(22));25console.log(counter(23));26console.log(counter(24));27console.log(counter(25));28console.log(counter(26));29console.log(counter(27));30console.log(counter(28));31console.log(counter(29));32console.log(counter(30));33console.log(counter(31));34console.log(counter(32));35console.log(counter(33));36console.log(counter(34));37console.log(counter(35));38console.log(counter(36));39console.log(counter(37));40console.log(counter(38));41console.log(counter(39));42console.log(counter(40));43console.log(counter(41));44console.log(counter(42));45console.log(counter(43));

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2const { counter } = require('./test2.js');3const { counter2 } = require('./test2.js');4fc.assert(5 fc.property(fc.integer(), fc.integer(), (a, b) => {6 return counter(a, b) === counter2(a, b);7 })8);9const counter = (a, b) => {10 return a + b;11};12const counter2 = (a, b) => {13 return a + b;14};15module.exports = { counter, counter2 };16const fc = require('fast-check');17const { counter } = require('./test2.js');18const { counter2 } = require('./test2.js');19fc.assert(20 fc.property(fc.integer(), fc.integer(), (a, b) => {21 return counter(a, b) === counter2(a, b);22 })23);24const fc = require('fast-check');25const { counter } = require('./test2.js');26const { counter2 } = require('./test2.js');27fc.assert(28 fc.property(fc.integer(), fc.integer(), (a, b) => {29 return counter(a, b) === counter2(a, b);30 })31);32const fc = require('fast-check');33const { counter } = require('./test2.js');34const { counter2 } = require('./test2.js');35fc.assert(36 fc.property(fc.integer(), fc.integer(), (a, b) => {37 return counter(a, b) === counter2(a, b);38 })39);40const fc = require('fast-check');41const { counter } = require('./test2.js');42const { counter2 } = require('./test2.js');43fc.assert(44 fc.property(fc.integer(), fc.integer(), (a, b) => {45 return counter(a, b) === counter2(a, b);46 })47);48const fc = require('fast-check');49const { counter } = require('./test2.js');50const { counter2 } = require('./test2.js');51fc.assert(52 fc.property(fc.integer(), fc.integer(), (a, b) => {53 return counter(a, b) === counter2(a, b);54 })55);56const fc = require('fast-check');57const { counter } = require('./test2

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 fast-check-monorepo 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